sdc_client 0.158.8 → 0.158.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +39 -24
- package/dist/ugly.index.js +1 -1
- package/eslint.config.js +9 -26
- package/gulp/gulp.jsx +1 -6
- package/{gulpfile.jsx → gulpfile.cjs} +12 -7
- package/package.json +18 -21
- package/src/simpleDomControl/AbstractSDC.js +9 -0
- package/src/simpleDomControl/sdc_controller.js +4 -1
- package/src/simpleDomControl/sdc_view.js +5 -0
- package/test/controller.test.js +1 -1
- package/test/dist.test.js +1 -1
- package/webpack.config/webpack.default.config.cjs +0 -8
package/dist/ugly.index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e={};let t;function n(){return new Promise(function(e){e()})}function r(e){return(e=(e=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)).replace(/[0-9]+/g,e=>`-${e}`)).replace(/^[-]/g,"")}function s(e){return e.replace(/-./g,e=>`${e[1].toUpperCase()}`)}e.d=(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const o=(e,t)=>{let n=t,r=Object.getOwnPropertyNames(e.prototype).concat(Object.getOwnPropertySymbols(e.prototype));for(;""!==n.name;)Object.getOwnPropertyNames(n.prototype).concat(Object.getOwnPropertySymbols(n.prototype)).forEach(t=>{t.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/)||r.includes(t)||(r.push(t),Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)))}),n=Object.getPrototypeOf(n)};function i(e,t,n){return $.ajax({url:t,type:n||"POST",xhr:function(){var e=$.ajaxSettings.xhr();return e.upload&&e.upload.addEventListener("progress",l,!1),e},data:e,cache:!1,contentType:!1,processData:!1,beforeSend:function(e,t){(function(e){return/^(GET|HEAD|OPTIONS|TRACE)$/.test(e)})(t.type)||this.crossDomain||e.setRequestHeader("X-CSRFToken",window.CSRF_TOKEN)}})}function l(e){if(e.lengthComputable){var t=Math.round(e.loaded/e.total*100),n=$(".progress-container");100===t?n.hide():n.show(),t+="%",n.find(".progress-bar").css({width:t}).text(t)}}function a(e,t=null){return"string"!=typeof e?e:t&&void 0!==t[e]?"function"==typeof t[e]?t[e].bind(t):t[e]:e.match(/^(true|false)$/)?"true"===e:"undefined"!==e?"none"===e.toLowerCase()?null:e.match(/^-?\d+$/)?parseInt(e):e.match(/^-?\d+\.?\d+$/)?parseFloat(e):e.match(/^(['][^']*['])|(["][^"]*["])$/)?e.substr(1,e.length-2):e:void 0}function c(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))}function u(e){e.find(".has-error").removeClass("has-error").find(".alert-danger").remove(),e.find(".non-field-errors").remove()}function d(e,t){t=$("<div>").append(t),e.find(".has-error").removeClass("has-error").find(".alert-danger").safeRemove(),e.find(".non-field-errors").safeRemove();let n=t.find("input[type=file]").parent();e.find("input[type=file]").parent().each(function(e){$(this).replaceWith(n[e])});let r=0===t.find(".non-field-errors").insertAfter(e.find(".hidden-form-fields")).length;return t.find(".has-error").each(function(){r=!1;let t=$(this),n=t.data("auto-id"),s=e.find(".form-group."+n);s.addClass("has-error"),s.find(".form-input-container").append(t.find(".alert-danger"))}),r}function h(e){let{type:t,name:n}=e;return n&&""!==n?"hidden"===t?(r=$(e).val()).toLowerCase().match(/^(true|false)$/)?"true"===r.toLowerCase():"undefined"!==r?"none"===r.toLowerCase()?null:r.match(/^-?\d+$/)?parseInt(r,10):r.match(/^-?\d+\.?\d+$/)?parseFloat(r):r.match(/^(['][^']*['])|(["][^"]*["])$/)?r.substring(1,r.length-1):r:void 0:"checkbox"===t?e.checked:"file"===t?e.files[0]:$(e).val():null;var r}function m(e,t){let{type:n,name:r}=e;if(r&&""!==r)if("checkbox"===n)e.checked=!!t;else if("file"===n){if(t instanceof File&&"undefined"!=typeof DataTransfer){let n=new DataTransfer;n.items.add(t),e.files=n}}else t instanceof ae?$(e).val(t.id):t instanceof le?$(e).val(`[${t.getIds().join(",")}]`):(null===t&&(t=""),$(e).val(t));return null}function f(e,t=null){return Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==A).map(([e,n])=>{if("string"==typeof n&&n.startsWith("SDC_JSON_MODEL=["))try{const{pk:t,fields:r}=JSON.parse(n.slice(16,-1));return[e,{...r,id:t,id:t}]}catch{}return[e,a(n,t)]}))}function p(e,t=null){return f(e.data(),t)}const y=["onbeforeunload","onunload"],g=Object.keys(window).filter(e=>/^on/.test(e)&&!y.includes(e)).map(e=>e.slice(2));function v(e,t,n){let r;switch(e){case"mouseleave":case"mouseout":case"mouseenter":case"mousein":return r=document.elementFromPoint(t.clientX,t.clientY),n!==r&&!n.contains(r);default:return!0}}function w(e){let t=e.type;e.hasOwnProperty("namespace")&&e.namespace&&e.namespace.length&&(t+=`.${e.namespace}`);let n=$(e.target),r=null,s=!1,o=!1;for(e.stopImmediatePropagation=()=>o=!0,e.stopPropagation=()=>o=s=!0;n.length;){let i=n.attr(`sdc_${t}`);if(i&&v(t,e,n[0])){if(!r&&(r=Q(n),!r))return;for(;r;){if(i.split(" ").forEach(o=>{if(s)return;let i=null;if("function"==typeof o)i=o;else if("function"==typeof r[o])i=r[o];else if("string"==typeof o&&o.startsWith("this.event_")){if(i=r.getEvents()[t],!i)return;if(i=i[o.slice(11)],!i)return}i&&i.call(r,n,e)}),o)return;r=r._parentController}}if(s)return;n=n.parent()}return{res:!0}}function b(e){if(e._isEventsSet)return;const t=e.getEvents();for(let n in t)if(t.hasOwnProperty(n)){let r=t[n];for(let t in r)r.hasOwnProperty(t)&&e.find(t).each(function(){let e=$(this),r=e.attr(`sdc_${n}`)||null;r=r?r.split(" "):[];const s=`this.event_${t}`;-1===r.indexOf(s)&&(r.push(s),e.attr(`sdc_${n}`,r.join(" ")))})}}let R=[],N={};function C(e,t){if(e){let n=s(t._tagName);e._childController[n]||(e._childController[n]=[]),e._childController[n].push(t)}return t._parentController=e}function O(e,t,n,r){let s=[];r=function(e,t){e=(e=e.concat(N[t][1])).filter((e,t,n)=>n.indexOf(e)===t);let n=!0;for(;n;){n=!1;for(let t of e)for(let r of N[t][1])e.includes(r)||(e.push(r),n=!0)}return e}(r,n);for(let e of r)s.push(N[e][0]);let i=new(function(e,...t){let n={[e.name]:class{constructor(...n){let r={};t.forEach(e=>{let t;Object.assign(this,t=new e),t._tagName=e.prototype._tagName,t._isMixin=!0,r[e.name]=t}),Object.assign(this,new e),this._mixins=r}static get name(){return e.name}static className(){return this.name}get mixins(){return this._mixins}}}[e.name];return o(n,e),t.forEach(e=>{o(n,e)}),n}(N[n][0],...s));return i._tagName=n,C(e,i),i.$container=t,function(e,t){!function(e,t,n){e&&"function"==typeof e.onInit&&(e.params=p(t,n._parentController))}(t,e,t)}(t,i),i}function S(e,t,n,r){if(R.includes(n)){let o=s(n);return window[o]||(window[o]=O(e,t,n,r)),window[o].$container=t,window[o]}return O(e,t,n,r)}function F(e,t){const r=function(e){return function(e){let t={args:{}};return e.contentUrl&&(t=V(e),e.contentUrl=t.url),Promise.all([D(e,t.args)]).then(function(e){let t=e[0];if(t)try{return $(t)}catch{return $("<div></div>").append(t)}return null})}(e).then(t=>!e.onLoad||e._onLoadDone?t:(e._onLoadDone=!0,(e.onLoad(t)||n()).then(()=>t)))}(e).then(function(t){return function(e,t){return W(e,t).then(function(t){if(t=t||!0,e.willShow){let n=e.willShow();if(n instanceof Promise)return n.then(function(){return t})}return t})}(e,t)}).then(()=>function(e,t){return X(null,e,t)}(e,t)).catch(function(t){return W(e,t)});return e.load_async?Promise.resolve():r}function E(e){const t=function(e){let t=[];for(;e;)e._isEventsSet=!1,t.unshift(e),e=e._parentController;return t}(e.controller[0]),n=t.concat(e.controller.slice(1));for(let t of n)b(t),t.onRefresh(e.controller[0])}function k(e,t){let n=Boolean(e);return n?e.uuids.has(t._uuid)||(e.uuids.add(t._uuid),e.controller.push(t)):e={uuids:new Set([t._uuid]),controller:[t]},{isRunningProcess:n,refreshProcess:e}}let P={},x={};function L(e,t){return j(e),x.hasOwnProperty(e)?t[x[e]]?void P[e].push(t):console.log("No event handler: "+e,t):console.log("No event: "+e,t)}function j(e,t){t||(t=e),x[e]||(x[e]=t,P[e]=[])}function I(e){for(let t in P)if(P.hasOwnProperty(t))for(let n=P[t].length-1;n>=0;n--)e===P[t][n]&&P[t].splice(n,1)}function q(e){let t=Array.apply(null,arguments);if(e=t.shift(),!P.hasOwnProperty(e)||!x.hasOwnProperty(e))return n();let r=P[e],s=x[e],o=[];for(let e=0;e<r.length;e++){let n=r[e][s].apply(r[e],t);void 0!==n&&o.push(n)}return Promise.all(o)}let T={};const A="_controller_",M="_sdc_controller_";function U(e,t,n){if(!e)return[];let r=e.children(),s=[];return r.each(function(e,r){let o=$(r),i=o.prop("tagName").toLowerCase().split("_");$.inArray(i[0],t)>=0?s.push({tag:i[0],super:i.splice(1)||[],dom:o}):i[0].startsWith("this.")?o.addClass(`_bind_to_update_handler sdc_uuid_${n._uuid}`):s=s.concat(U(o,t,n))}),s}function D(e,t){const{contentUrl:n,_tagName:r,contentReload:s}=e;return n?T[r]?Promise.resolve(T[r]):(t.VERSION=we.VERSION,t._method="content",$.get(n,t).then(function(e){return s||(T[r]=e),e}).catch(function(t){throw 301===t.status&&q("_RedirectOnView",t.responseJSON["url-link"]),"function"==typeof e.confirmPageLoaded&&q("navLoaded",{controller_name:()=>t.status}),`<sdc-error data-code="${t.status}">${t.responseText}</sdc-error>`})):Promise.resolve(!1)}function J(e,t,n=null){return t=t||e.data(A),G(we.tagNames,e,t,n)}function V(e){let t=e.contentUrl;if(e&&0===e._urlParams.length){let n,r=/%\(([^)]+)\)\w/gm;for(e._urlParams=[];n=r.exec(t);)e._urlParams.push(n[1]),e.contentReload=!0}let{args:n,params:r}=function(e,t){const n=p(t,e),[r,s]=Object.entries(n).reduce(([t,n],[r,s])=>(e._urlParams.includes(r)?t[r]=s:n[r]=s,[t,n]),[{},{}]);return{params:r,args:s}}(e,e.$container);return e._urlParams.length&&(t=function(e,t,n){for(let r in e._urlParams)if(e._urlParams.hasOwnProperty(r)){let s=e._urlParams[r],o=RegExp("%\\("+s+"\\)\\w","gm");const i=n[s];i||console.warn(`${s} is not set for controller ${e._tagName}`),t=t.replace(o,i)}return t}(e,t,r)),e.parsedContentUrl=t,{url:t,args:n}}function Q(e){return e.hasClass(M)?e.data(`${A}`):e.closest(`.${M}`).data(`${A}`)}function B(e,t,n,r,s){let o=e.data(A);return o?J(e,o,s):(o=S(r,e,t,n),e.data(A,o),e.addClass(M),F(o,s))}function W(e,t,n=null){if(t&&t.length>0){e.$container.empty(),e.$container.attr(e._tagName,"");for(let t in e._mixins)e.$container.attr(e._mixins[t]._tagName,"");e.$container.append(t)}return J(e.$container,e,n)}function G(e,t,n,r){return new Promise(s=>{let o=U(t,e,n),i=o.length;if(0===i)return s();for(let e=0;e<o.length;e++)B(o[e].dom,o[e].tag,o[e].super,n,r).then(()=>{if(i--,0===i)return s()})})}function z({$element:e,id:t=[],parent:n=null}){t.push(function(e){if(3===e[0].nodeType)return`TEXT__${e[0].nodeValue}`;const t=[e[0].tagName];return"INPUT"===e[0].nodeName&&[["name",""],["type","text"],["id",""]].forEach(([n,r])=>{const s=e.attr(n)??r;s&&t.push(s)}),t.join("__")}(e));const r={$element:e,id:t.join("::"),depth:t.length,idx:0,getRealParent:()=>n,getIdx:function(){return this.idx=Math.max(0,(this.getRealParent()?.getIdx()??-1)+e.index()+1),this.idx},op:null,parent:n};return r.getIdx.bind(r),[r].concat(e.contents().toArray().map(e=>z({$element:$(e),id:t.slice(),parent:r})).flat())}function K(e,t){const n=z({$element:t}),r=z({$element:e});n.map((e,t)=>e.idx=t),r.map((e,t)=>e.idx=t);const s=Math.max(...r.concat(n).map(e=>e.depth)),o=H(n,r,s);let i=[];window.MAIN=t,window.OPS=o,o.forEach((e,t)=>{const{op:n,$element:r,idx:s}=e;if("keep_counterpart"===n.type){if(n.counterpart.getIdx()!==s){const t=e.getBefore();t?n.counterpart.$element.insertAfter(t.$element):e.getRealParent().$element.prepend(n.counterpart.$element)}!function(e,t){const n=e[0].attributes??[],r=t[0].attributes??[];[...n].forEach(n=>{t.is(`[${n.name}]`)||e.removeAttr(n.name)}),[...r].forEach(t=>{t.name.startsWith("data")||e.attr(t.name)===t.value||e.attr(t.name,t.value)}),e.removeData(),Object.entries(t.data()).forEach(([t,n])=>{e.data(t,n)})}(n.counterpart.$element,r),r.hasClass(M)&&(r.data(A).$container=n.counterpart.$element,r.data(A,null)),i.push(r)}else if("delete"===n.type)r.safeRemove();else if("insert"===n.type){const{after:t,target:n}=e.op;t?r.insertAfter(t.$element):n&&n.$element.prepend(r)}}),i.forEach(e=>e.safeRemove())}function H(e,t,n){return t.filter(e=>e.depth===n&&!e.op).forEach(t=>{const n=e.find(e=>!e.op&&e.id===t.id);if(n){const e=(t,n)=>{t.op={type:"keep",idx:n.idx},n.op={type:"keep_counterpart",counterpart:t},t=t.parent,n=n.parent,!t||t.op||n?.op||e(t,n)};e(n,t)}}),n>1?H(e,t,n-1):(e.forEach((t,n)=>{if(!t.op){const r=(e[n-1]?.op.idx??-1)+1;t.op={type:"delete",idx:r}}}),t.forEach((e,n)=>{if(e.getBefore=()=>function(e,n){const r=e.depth;for(;n>=1&&e.depth>=r;)if((e=t[n-=1]).depth===r)return"keep_counterpart"===e.op.type?e.op.counterpart:e;return null}(e,n),e.getRealParent=()=>{return(t=e).parent?"keep_counterpart"===t.parent.op.type?t.parent.op.counterpart:t.parent:null;var t},!e.op){const t=e.getRealParent(),n="insert"===t?.op.type?"insert_ignore":"insert";e.op={type:n,target:t,after:e.getBefore()}}}),[...e,...t].sort((e,t)=>(e.op?.idx??e.idx)-(t.op?.idx??t.idx)))}function X(e,t,n=null){if(t||(t=Q(e)),!t)return Promise.resolve();const{refreshProcess:r,isRunningProcess:s}=k(n,t);return e??=t.$container,G(we.tagNames,e,t,n).then(()=>function(e,t,n){return function(e,t,n){const r=[];return t.find(`._bind_to_update_handler.sdc_uuid_${e._uuid}`).each(function(){const t=$(this);let s;if(t.hasClass("_with_handler"))s=t.data("handler");else{let t=this.tagName.toLowerCase().replace(/^this./,"");e[t]&&(s=e[t])}if("function"==typeof s){const n=f(t.data(),e);s=s.bind(e)(n)}s&&r.push(Promise.resolve(s).then(r=>{let s=$("<div></div>");return s.append(r),""===t.html()&&t.append("<div></div>"),we.reconcile(e,s,t.children(),n)}))}),Promise.all(r)}(e,t??e.$container,n)}(t,e,r).then(()=>{s||E(r)}))}const Y={};function Z(e,t){Y[e]=t}function ee(e){return Y[e]}const te=25e3,ne="_connecting_process",re=e=>Object.assign(Object.create(Object.getPrototypeOf(e)),structuredClone(e));class se extends Error{constructor(e){"string"==typeof e&&(e={msg:e,is_error:!0,header:"Error"}),super(e.msg),this.msg=e.msg,this.header=e.header,this.is_error=e.is_error,this.html=e.html}}class oe{constructor({name:e,url:t}){this.name=e,this.url=t,this.content=null}async load(e=!1){return!e&&this.content||(this.content=await new Promise((e,t)=>{$.get(this.url).then(e).catch(()=>{e("")})})),this.content}async text(){return this.load()}static isValid(e){return!(null===e||"object"!=typeof e||Array.isArray(e)||e instanceof File||"string"!=typeof e.url||"string"!=typeof e.name)}}function ie(e){const t=parseInt(e??-1,10);return Number.isNaN(t)?-1:t}class le{constructor(e,t={}){return this.valuesList=[],this.loaded=!1,this.modelName=e,this.modelQuery=t??{},this._onNoOpenRequests=[],this._isConnected=!1,this._isConnectingProcess=!1,this._autoReconnect=!0,this.socket=null,this.openRequest={},this.modelId=0,this.onUpdate=()=>{},this.onCreate=()=>{},new Proxy(this,{get:(e,t)=>"symbol"==typeof t||isNaN(t)?e[t]:e.valuesList[t],set:(e,t,n)=>isNaN(t)?(e[t]=n,!0):(e.valuesList[t]=n,!0)})}[Symbol.iterator](){let e=-1;return{next:()=>(++e,e<this.valuesList.length?{value:this.valuesList[e],done:!1}:{value:null,done:!0})}}set on_create(e){this.onCreate=e}set on_update(e){this.onUpdate=e}setIds(e){const t=this._setIds(e),n={id__in:t.map(e=>e.id)};return this.setFilter(n),t}cloneObject;_setIds(e){if(null===e||""===e||Array.isArray(e)&&0===e.length)return this.valuesList=[],this.valuesList;if(e instanceof le)return this.valuesList=e.valuesList.map(re),this.valuesList.forEach(e=>e._setQuerySet(this,!0)),this.valuesList;if(e instanceof ae)return this.valuesList=[re(e)],this.valuesList.forEach(e=>e._setQuerySet(this,!0)),this.valuesList;let t,n=Number.NaN;if(Number.isInteger(e))n=e;else if(e instanceof Array){const n=e.map(e=>parseInt(e));n.some(Number.isNaN)||(t=n)}else if("string"==typeof e){const r=e.split(",").map(e=>parseInt(e));r.some(Number.isNaN)?n=parseInt(e):t=r}if(Number.isNaN(n)){if(t){this.valuesList=this.valuesList.filter(e=>t.includes(e.id));const e=this.getIds();t.filter(t=>!e.includes(t)).forEach(e=>{this.valuesList.push(new(ee(this.modelName))({id:e}))})}}else this.valuesList=this.valuesList.filter(e=>n===e.id),0===this.valuesList.length&&(this.new().id=n);return this.valuesList}getIds(){return this.valuesList.map(e=>e.id)}get length(){return this.valuesList.length}byId(e){if(null!==e){const t=ie(e);return this.valuesList.find(e=>e.id===t)??null}return null}setFilter(e){return this.modelQuery=e,this}addFilter(e){return this.modelQuery=Object.assign({},this.modelQuery,e),this}new(e={}){const t=new(ee(this.modelName))(e);return t._setQuerySet(this,!1),this.valuesList.push(t),t}load(e=null){return this.valuesList=[],this.modelQuery=e??this.modelQuery,this._sendLoad()}update({modelQuery:e=null,item:t=null}){this.modelQuery=e??this.modelQuery;let n=t?{id:t.id}:this.modelQuery;return this._sendLoad(n)}delete({pk:e=null,id:t=null,elem:n=null}){if(e??=t,null===(e=n?n.id:e))throw new Error("pk or elem must be set");const r=c();return this.isConnected().then(()=>new Promise((t,n)=>{this.socket.send(JSON.stringify({event:"model",event_type:"delete",event_id:r,args:{model_name:this.modelName,model_query:this.modelQuery,id:e,pk:e}})),this.openRequest[r]=[t,n]}))}_sendLoad(e=null){return this.isConnected().then(()=>{const t=c();return new Promise((n,r)=>{this.socket.send(JSON.stringify({event:"model",event_type:"load",event_id:t,args:{model_name:this.modelName,model_query:e??this.modelQuery}})),this.openRequest[t]=[e=>{this.loaded=!0,n(e)},r]})})}_sendListView({modelQuery:e={},cbResolve:t=null,cbReject:n=null,templateContext:r={}}){return this.view({modelQuery:e,cbResolve:t,cbReject:n,templateContext:r,eventType:"list_view"})}view({viewName:e="html_list_template",modelQuery:t={},cbResolve:n=null,cbReject:r=null,templateContext:s={},eventType:o="named_view"}){let i=$('<div class="container-fluid">');return this.isConnected().then(()=>{const l=c();this.socket.send(JSON.stringify({event:"model",event_type:o,event_id:l,args:{view_name:e,model_name:this.modelName,model_query:t,template_context:s}})),this.openRequest[l]=[e=>{i.append(e.html),we.refresh(i),n&&n(e)},e=>{r&&r(e)}]}),i}_sendDetailView({pk:e=null,id:t=null,cbResolve:n=null,cbReject:r=null,templateContext:s={}}){e??=t,e=ie(e);let o=$('<div class="container-fluid">');return this.isConnected().then(()=>{const t=c();this.socket.send(JSON.stringify({event:"model",event_type:"detail_view",event_id:t,args:{model_name:this.modelName,model_query:this.modelQuery,id:e,pk:e,template_context:s}})),this.openRequest[t]=[e=>{o.append(e.html),we.refresh(o),n&&n(e)},e=>{r&&r(e)}]}),o}getForm({modelObj:e,eventType:t,formName:n,$divForm:r,cbResolve:s,cbReject:o,formId:i}){const l=c(),a=e.id??-1;this.isConnected().then(()=>{this.socket.send(JSON.stringify({event:"model",event_type:t,event_id:l,args:{model_name:this.modelName,id:a,pk:a,form_name:n}}))});const u=null===a||-1===a?"create":"edit";this.openRequest[l]=[t=>{r.append(t.html);let o=r.closest("form").addClass(`sdc-model-${u}-form sdc-model-form ${i}`).data("model",e).data("model_pk",a).data("form_name",n);e.addForm(o),o.length>0&&!o[0].hasAttribute("sdc_submit")&&o.attr("sdc_submit","submitModelFormDistributor"),we.refresh(r).then(()=>null),s&&s(t)},e=>{o&&o(e)}]}async get(e=null,t=!1){if(t){const t=e?.id??this.modelQuery?.id;return e&&this.setFilter(e),this.byId(t)??this.new(e||this.modelQuery)}if(await this.load(e),1!==this.length)throw new Error(`model query returns ${this.length} but only 1 expected.`);return this.addFilter({id:this.valuesList[0].id}),this.valuesList[0]}detailView({pk:e,cbResolve:t=null,cbReject:n=null,templateContext:r={}}){return this._sendDetailView({id:e,cbResolve:t,cbReject:n,templateContext:r})}listView({modelQuery:e={},searchValues:t={},cbResolve:n=null,cbReject:r=null,templateContext:s={}}){return this._sendListView({modelQuery:Object.assign({},this.modelQuery,e,{__search_values:t}),cbResolve:n,cbReject:r,templateContext:s})}save({pk:e=null,id:t=null,formName:n="edit_form",data:r=null}={}){e??=t;const s=ie(e);return this.isConnected().then(()=>{let e;if(s>-1){const t=this.byId(s);if(!t)return Promise.reject(new se(`Element not found with ID: ${s}`));e=[t]}else e=this.valuesList;let t=[];return e.forEach(e=>{const s=c();t.push(new Promise((t,o)=>{this._readFiles(e).then(i=>{const l=r?{...r}:e.serialize();l.id=e.id,this.socket.send(JSON.stringify({event:"model",event_type:"save",event_id:s,args:{form_name:n,model_name:this.modelName,model_query:this.modelQuery,data:l,id:l.id,pk:l.id,files:i}})),this.openRequest[s]=[e=>{let n="string"==typeof e.data.instance?JSON.parse(e.data.instance):e.data.instance;e.data.instance=this._parseServerRes(n),t(e)},o]})}))}),Promise.all(t)})}create({elem:e=null,data:t=null}={}){const n=c();return e||(e=this.new(t)),this.isConnected().then(()=>new Promise((r,s)=>{this._readFiles(e).then(o=>{this.socket.send(JSON.stringify({event:"model",event_type:"create",event_id:n,args:{model_name:this.modelName,model_query:this.modelQuery,data:t??e?.serialize()??{},files:o}})),this.openRequest[n]=[t=>{let n="string"==typeof t.data.instance?JSON.parse(t.data.instance):t.data.instance;e&&(e.id=n[0]?.id||n[0]?.pk),t.data.instance=this._parseServerRes(n)[0],r(t)},s]})}))}isConnected(){return new Promise((e,t)=>{if(this._isConnected)e();else if(this._isConnectingProcess&&this.openRequest[ne]){const[n,r]=this.openRequest[ne];this.openRequest[ne]=[()=>{n(),e()},()=>{r(),t()}]}else this._isConnectingProcess=!0,this.openRequest[ne]=[()=>{},()=>{}],this._connectToServer().then(()=>{e(this._checkConnection())})})}close(){this.socket&&(this._autoReconnect=!1,this.socket.onclose=()=>{},this.socket.close(),delete this.socket),this.valuesList.forEach(e=>{e._onClose()})}_readFiles(e){let t=[],n={};return e?(Object.keys(e.constructor.fields).forEach(r=>{const s=e[r];s instanceof File&&t.push(new Promise(async(e,t)=>{const o=c();this.openRequest[o]=[e,t];const i=await s.arrayBuffer();let l=new Uint8Array(i),a=Math.ceil(l.length/te);n[r]={id:o,file_name:s.name,field_name:r,content_length:s.size};for(let e=0;e<a;++e){const t=Array.from(l.slice(te*e,te*(e+1)));this.socket.send(JSON.stringify({event:"model",event_type:"upload",event_id:o,args:{chunk:t,idx:e,number_of_chunks:a,file_name:s.name,field_name:r,content_length:s.size,content_type:s.type,model_name:this.modelName,model_query:this.modelQuery}}))}}))}),Promise.all(t).then(()=>n)):Promise.resolve(n)}async _onMessage(e){let t=JSON.parse(e.data);if(t.is_error)this.openRequest.hasOwnProperty(t.event_id)&&(this.openRequest[t.event_id][1](new se(t)),this._closeOpenRequest(t.event_id)),(t.msg||t.header)&&q("pushErrorMsg",t.header||"",t.msg||""),"connect"===t.type&&(this.openRequest[ne][1](new se(t)),this._closeOpenRequest(ne),this._autoReconnect=!1,this.socket.close());else{if((t.msg||t.header)&&q("pushMsg",t.header||"",t.msg||""),"connect"===t.type)this._isConnected=!0,this._isConnectingProcess=!1,this.openRequest[ne][0](t),this._closeOpenRequest(ne);else if(["load","named_view","detail_view"].includes(t.type)){const e=JSON.parse(t.args.data);t.args.data=await this._parseServerRes(e)}else if("on_update"===t.type||"on_create"===t.type){const e=JSON.parse(t.args.data);let n,r=await this._parseServerRes(e);n="on_create"===t.type?this.onCreate:this.onUpdate,n(r),t.args.data=r}let e=t.data?.instance;e&&(t.data.instance=JSON.parse(t.data.instance)),this.openRequest.hasOwnProperty(t.event_id)&&(this.openRequest[t.event_id][0](t),this._closeOpenRequest(t.event_id))}}noOpenRequests(){return new Promise(e=>{if(0===Object.keys(this.openRequest).length)return e();this._onNoOpenRequests.push(e)})}_closeOpenRequest(e){delete this.openRequest[e],0===Object.keys(this.openRequest).length&&(this._onNoOpenRequests.forEach(e=>e()),this._onNoOpenRequests=[])}_connectToServer(){return new Promise(e=>{const t=`${this.modelName}`+(this.modelId>0?`/${this.modelId}`:"");"https:"===window.location.protocol?this.socket=new WebSocket(`wss://${window.location.host}/sdc_ws/model/${t}`):this.socket=new WebSocket(`ws://${window.location.host}/sdc_ws/model/${t}`),this.socket.onmessage=this._onMessage.bind(this),this.socket.onclose=e=>{console.error(`SDC Model (${this.modelName}, ${this.modelId}) Socket closed unexpectedly`),this._isConnected=!1;for(const[t,n]of Object.entries(this.openRequest))n[1](e);this.openRequest={},setTimeout(()=>{this._autoReconnect&&this._connectToServer().then(()=>{})},1e3)},this.socket.onerror=e=>{if(console.error(`Model Socket encountered error: ${e} Closing socket`),this._isConnected)try{this.socket.close()}catch(e){}},this.socket.onopen=()=>{e()}})}_checkConnection(){const e=c();return new Promise((t,n)=>{this.socket.send(JSON.stringify({event:"model",event_type:"connect",event_id:e,args:{model_name:this.modelName,model_query:this.modelQuery}})),this.openRequest[e]=[t,n]})}_parseServerRes(e){const t=[];for(const n of e){const e=ee(this.modelName);if(!e)throw new Error(`${this.modelName} is no SdcModel. mybe the models ar not importad.`);const r=new e({id:n.id??n.pk,...n.fields}),s=this.byId(r.id);s?(s.setValues(r),t.push(s)):(this.valuesList.push(r),r._setQuerySet(this,!0),t.push(r))}return this.valuesList.sort((e,t)=>e._id-t._id),t}}class ae{static fields={};constructor(e){this._id=null,this._forms=[],this.loaded=!1,this.formId=c(),this.modelName=e}static querySet(e=null,t=null){return t?t.querySet(this.modeName,e):new le(this.modeName,e)}addForm(e){const t=this._onChange.bind(this);this._forms.push(e),e&&e.on("input.formWatcher change.formWatcher","input, select, textarea",t)}_onChange(e){const{name:t}=e.target;this.constructor.fields[t]&&this[`set${t}`](h(e.target))}_updateForm(e){const t=this;this._forms.forEach(n=>{n.find(`[name="${e}"]`).each(function(){m(this,t[e])})})}setValues(e={}){throw new Error("setValues() must be implemented by subclass")}_setQuerySet(e,t){this._querySet=new WeakRef(e),this.loaded=t}get querySet(){return this._querySet.deref()}save({formName:e="edit_form",data:t=null}={}){return this._querySet.deref().save({pk:this.id,formName:e,data:t})}create({data:e=null}={}){return this._querySet.deref().create({elem:this,data:e})}delete(){return this._querySet.deref().delete({elem:this})}load(){return this._querySet.deref().update({item:this})}update(){return this.load()}get id(){return this._id}set id(e){this._id=e}set pk(e){this.id=e}get pk(){return this._id}close(){return this._querySet.deref().close()}_onClose(){Object.keys(this.constructor.fields).filter(e=>this[`_${e}`]instanceof le).forEach(e=>this[`_${e}`].close())}detailView({cbResolve:e=null,cbReject:t=null,templateContext:n={}}){return this._querySet.deref().detailView({pk:this.id,cbResolve:e,cbReject:t,templateContext:n})}serialize(){return Object.entries(this.constructor.fields).reduce((e,[t,n])=>{const r=this[t];if(r instanceof le)if(n.many_to_many||n.one_to_many)e[t]=r.getIds();else{const n=r.getIds();n.length>0?e[t]=n[0]:e[t]=null}else n.is_relation&&r instanceof ae?e[t]=r.id??null:e[t]=r;return e},{})}toJson(){const e={};for(let t in this.constructor.fields){const n=this[t];n instanceof File?e[t]=n.name:e[t]=n instanceof ae?n.id:n instanceof le?n.getIds():n}return e}syncFormToModel(e){return this.syncForm(e)}_resolveForms(e){return e&&e.hasClass(this.formId)?e:$(`.${this.formId}`)}syncModelToForm(e){e=this._resolveForms(e);const t=this,n=this.constructor.fields;e.each(function(){const e=ie($(this).data("model_pk"));if(t.id===e)for(let e of this.elements){let r=e.name;r&&""!==r&&n[r]&&m(e,t[r])}})}syncForm(e){e=this._resolveForms(e);const t=this,n=this.constructor.fields,r={};function s(e,s){n[e]&&(t[e]=s),r[e]=s}return e.each(function(){const e=ie($(this).data("model_pk"));if(t.id===e||null===t.id&&-1===e){for(let e of this.elements)s(e.name,h(e));return t}}),r}form({cbResolve:e=null,cbReject:t=null}={}){return null===this.id||-1===this.id?this._createForm({cbReject:t,cbResolve:e}):this._editForm({cbReject:t,cbResolve:e})}_createForm({cbResolve:e=null,cbReject:t=null}){let n=$("<div>");return this._querySet.deref().getForm({modelObj:this,eventType:"create_form",formName:null,$divForm:n,cbResolve:e,cbReject:t,formId:this.formId}),n}_editForm({cbResolve:e=null,cbReject:t=null}){let n=$("<div>");return this._querySet.deref().getForm({modelObj:this,eventType:"edit_form",formName:null,$divForm:n,cbResolve:e,cbReject:t,formId:this.formId}),n}namedForm({formName:e,cbResolve:t=null,cbReject:n=null}){let r=$('<div class="container-fluid">');return this._querySet.deref().getForm({modelObj:this,eventType:"named_form",formName:e,$divForm:r,cbResolve:t,cbReject:n,formId:this.formId}),r}validate(e,t){const n=function(e,t){const{type:n,required:r,max_length:s,is_relation:o,many_to_many:i,one_to_many:l,many_to_one:a,one_to_one:c,related_model:u}=t;if(r&&(null==e||""===e))return"This field is required";if(null==e||""===e)return null;if((i||l||a||c)&&(!(e instanceof le)||e.modelName!==u))return"string"==typeof e&&(e=JSON.parse(e)),(i||a)&&Array.isArray(e)&&e.some(e=>!Number.isNaN(parseInt(e)))?null:"object"!=typeof e&&Number.isNaN(parseInt(e))?"Must be object or ID":null;switch(n){case"CharField":case"TextField":if("string"!=typeof e)return"Must be a string";if(s&&e.length>s)return`Max length is ${s}`;break;case"IntegerField":case"AutoField":case"BigIntegerField":if(!isFinite(parseInt(e)))return"Must be an integer";break;case"FloatField":case"DecimalField":if(!isFinite(parseFloat(e)))return"Must be a number";break;case"BooleanField":if("boolean"!=typeof e)return"Must be a boolean";break;case"DateField":case"DateTimeField":if(isNaN(Date.parse(e)))return"Must be a valid date";break;case"EmailField":if("string"!=typeof e||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return"Invalid email";break;case"URLField":try{new URL(e)}catch{return"Invalid URL"}break;case"UUIDField":if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e))return"Invalid UUID";break;case"JSONField":if("object"!=typeof e)return"Must be JSON object";break;case"FileField":if(!(oe.isValid(e)||e instanceof File||e instanceof oe))return"Must be a valid file"}return null}(e,t);if(n)throw new Error(n)}parseValue(e,t){const{type:n,many_to_many:r,one_to_many:s,many_to_one:o,one_to_one:i}=t;if(null===e)return null;if((r||s||o||i)&&e&&"string"==typeof e)return JSON.parse(e);switch(n){case"CharField":case"TeextField":case"UUIDField":case"EmailField":return`${e}`;case"IntegerField":case"AutoField":case"BigIntegerField":return parseInt(e,10);case"FloatField":case"DecimalField":return parseFloat(e);case"BooleanField":return!!e;case"DateField":case"DateTimeField":return Date.parse(e);case"URLField":return new URL(e);case"FileField":if(null==e)return null;if("string"==typeof e)return null;if(oe.isValid(e))return new oe(e);if(e instanceof oe)return new oe(e);if("undefined"!=typeof File&&e instanceof File)return t.max_size&&e.size>t.max_size?`File too large (max ${t.max_size} bytes)`:t.allowed_types&&!t.allowed_types.includes(e.type)?`Invalid file type (${e.type})`:e;break;case"JSONField":if("object"==typeof e)return e;if("string"==typeof e)return JSON.parse(e)}return e}}let ce=!1,ue=!1,de=null,he={};function me(){return window.SERVER_CALL_VIA_WEB_SOCKET?new Promise(e=>ce?e():ue?void setTimeout(()=>{me().then(()=>{e()})},200):e(pe())):Promise.resolve(!0)}function fe(){window.SERVER_CALL_VIA_WEB_SOCKET&&function(){if(ce){ce=!1;try{de.close()}catch(e){}}}()}function pe(){return ue=!0,new Promise(e=>{de="https:"===window.location.protocol?new WebSocket(`wss://${window.location.host}/sdc_ws/ws/`):new WebSocket(`ws://${window.location.host}/sdc_ws/ws/`),de.onmessage=function(e){_e(JSON.parse(e.data))},de.onclose=function(){ce&&console.error("SDC Socket closed unexpectedly"),ce=!1;for(const[e,t]of Object.entries(he))t[1]({}),delete he[e];setTimeout(()=>{pe()},1e3)},de.onerror=function(e){if(console.error("Socket encountered error: ",e.message,"Closing socket"),ce)try{de.close()}catch(e){}},de.onopen=function(){ce=!0,ue=!1,e()}})}function _e(e){if(e||(e={}),e.is_error)(e.msg||e.header)&&q("pushErrorMsg",e.header||"",e.msg||""),e.id&&he[e.id]&&(he[e.id][1](e.data||null),delete he[e.id]);else if((e.msg||e.header)&&q("pushMsg",e.header||"",e.msg||""),e.type&&"sdc_recall"===e.type)e.id&&he[e.id]&&(he[e.id][0](e.data),delete he[e.id]);else if(e.type&&"sdc_event"===e.type){let t=e.event;t&&q(t,e.payload)}else e.type&&"sdc_redirect"===e.type&&q("onNavLink",e.link)}class ye{constructor(){this._uuid=c(),this.contentUrl="",this.contentReload=!1,this.parsedContentUrl=null,this.events=[],this.load_async=!1,this._isEventsSet=!1,this._allEvents=null,this._params={},this._urlParams=[],this._models=[],this._cssUrls=[],this.afterShow=()=>{console.warn("afterShow is deprecated!!")},this._mixins={},this._tagName=Object.getPrototypeOf(this)._tagName??"",this._childController={},this._parentController=null,this._onLoadDone=!1,this.$container=null,this._isMixin=!1}get params(){return this._params}set params(e){this._params=e}_runLifecycle(e,t){we.DEBUG&&!this._isMixin&&console.debug(e,this._tagName);let n=[];if(!this._isMixin){this._isMixin=!0;for(let r in this._mixins){let s=this._mixins[r];"function"==typeof s[e]&&n.push(s[e].apply(this,t))}return Promise.all(n).then(()=>{this._isMixin=!1})}}onInit(){we.DEBUG&&!this._isMixin&&console.debug(Array.apply(null,arguments),this._tagName)}get parentController(){return this._parentController}get childController(){return this._childController}onLoad(){return this._runLifecycle("onLoad",arguments)}willShow(){return this._runLifecycle("willShow",arguments)}onRefresh(){return this._runLifecycle("onRefresh",arguments)}onRemove(){return this._runLifecycle("onRemove",arguments),!0}noOpenModelRequests(){return Promise.all(this._models.map(e=>e.noOpenRequests()))}remove(){for(const e of this._models)e.close();let e=this._childController;for(let t in e)if(e.hasOwnProperty(t))for(let n of e[t])if(!n.remove())return!1;if(!this.onRemove||this.onRemove()){I(this);const e=s(this._tagName);if(this._parentController._childController[e]){let t=this._parentController._childController[e];for(let e=0;e<t.length;e++)t[e]===this&&t.splice(e,1)}return this.$container.remove(),!0}return!1}controller_name(){return this._tagName.replace(/-./g,e=>` ${e[1].toUpperCase()}`).replace(/^./g,e=>`${e.toUpperCase()}`)}addEvent(e,t,n){this.getEvents(),this._allEvents[e]=this._allEvents[e]||{},this._allEvents[e][t]=n}getEvents(){if(this._allEvents)return this._allEvents;let e=[];e=e.concat(this.events);for(let t in this._mixins){let n=this._mixins[t];Array.isArray(n.events)&&(e=e.concat(n.events))}return this._allEvents=_.merge(...e)}post(e,t){return we.post(this,e,t)}get(e,t){return we.get(this,e,t)}submitForm(e,t,n){return we.submitFormAndUpdateView(this,e,t,n)}serverCall(e,t){let n=this.contentUrl.match(/sdc_view\/([^/]+)/i);if(n&&!(n.length<2))return function(e,t,n,r,s){return window.SERVER_CALL_VIA_WEB_SOCKET?function(e,t,n,r){let s=c();return me().then(()=>{de.send(JSON.stringify({event:"sdc_call",id:s,controller:t,app:e,function:n,args:r}))}),new Promise((e,t)=>{he[s]=[e,t]})}(e,t,r,s):function(e,t,n){return"object"!=typeof n&&Array.isArray(n)&&null===n&&(n={arg0:n}),n={data:JSON.stringify(n),_sdc_func_name:t,_method:"sdc_server_call"},$.post({url:e,data:n,beforeSend:function(e,t){e.setRequestHeader("X-CSRFToken",window.CSRF_TOKEN)}}).then(e=>{const t=e._return_data;return _e(t),t}).catch(e=>{const t=e.responseJSON||{};throw t.is_error=!0,_e(t),e})}(n,r,s)}(n[1],this._tagName,this.parsedContentUrl??this.contentUrl,e,t);console.error("To use the serverCall function the contentUrl must be set: "+this.name)}querySet(e,t={}){const n=new le(e,t);return this._models.push(n),n}newModel(e,t={}){return console.warn("newModel is deprecated and will soon be removed. Please use this.querySet(modelName, modelQuery)"),this.querySet(e,t)}find(e){return this.$container.find(e)}refresh(){return we.refresh(this.$container,this)}reload(){return we.reloadController(this)}reconcile(e,t=null){return we.reconcile(this,e,t)}submitModelFormDistributor(e,t){return"function"==typeof this._submitModelForm?this._submitModelForm(e,t):"function"==typeof this.submitModelForm?this.submitModelForm(e,t):this.defaultSubmitModelForm(e,t)}iterateAllChildren(){let e=this._childController,t=[];for(let n in e)if(e.hasOwnProperty(n))for(let r of e[n])t.push(r),t.push(...r.iterateAllChildren());return t}defaultSubmitModelForm(e,t){if(!this._isMixin){t.stopPropagation(),t.preventDefault();let{model:n,form_name:r}=e.data(),s=n.syncForm(e);return new Promise((t,o)=>{let i;i=null!==n.id&&n.id>=0?n.save({formName:r,data:s}):n.create({data:s}),i.then(n=>{u(e),this.submit_model_form_success&&this.submit_model_form_success(n[0]);for(const e of this.iterateAllChildren())e.submit_model_form_success&&e.submit_model_form_success(n[0]);t(n)}).catch(t=>{this.reconcile($(`<div class="container-fluid">${t.html}</div>`),e.find(".container-fluid").first()),this.submit_model_form_error&&this.submit_model_form_error(t);for(const e of this.iterateAllChildren())e.submit_model_form_error&&e.submit_model_form_error(t);o(t)})})}return Promise.resolve()}}const ge={classname:"class"};window.sdcDom=function(e,t,...n){if(!e)return"";const r=function(e,t){let n,r=!1;if("string"==typeof e)n=$(document.createElement(e));else{const t=`this.${e.name}`;n=$(document.createElement(t)),n.data("handler",e),r=!0}return t&&Object.entries(t).forEach(([e,t])=>{e.startsWith("on")?n[0].addEventListener(e.substring(2).toLowerCase(),t):(ge[e.toLowerCase()]&&(e=ge[e.toLowerCase()]),n[0].setAttribute(e,t))}),r&&n.addClass("_bind_to_update_handler _with_handler"),n}(e,t);for(const e of n)r.append(e);return r};let ve,we={CSRF_TOKEN:window.CSRF_TOKEN||"",LANGUAGE_CODE:window.LANGUAGE_CODE||"en",DEBUG:window.DEBUG||!1,VERSION:window.VERSION||"0.0",tagNames:[],Global:R,rootController:null,globalRootController:null,_isInit:!1,_origin_trigger:null,_globalControllerClasses:[],init_sdc:()=>{we._isInit||(we._isInit=!0,we._origin_trigger?fe():(we._origin_trigger=$.fn.trigger,$.fn.trigger=function(e){const t={}.hasOwnProperty.call(e,"type")?e.type:e;return g.includes(t)||(g.push(t),$(window).on(t,w)),we._origin_trigger.call(this,e)},we.updateJquery()),me(),function(){const e=$(window);g.forEach(t=>{e.off(t).on(t,w)})}(),we.rootController=we.rootController||new ye,we.globalRootController=we.globalRootController||new ye),we.tagNames=Object.keys(N);const e=$("<div></div>");R.forEach(t=>{const n=N[t][0];e.append(`<${n.prototype._tagName}></${n.prototype._tagName}>`)});const{refreshProcess:n}=k(null,we.rootController);return G(we.tagNames,e,we.globalRootController,n).then(()=>G(we.tagNames,(t||(t=$("body")),t),we.rootController,n).then(e=>(E(n),e)))},updateJquery:()=>{$.fn.safeReplace=function(e){return we.safeReplace($(this),e)},$.fn.safeEmpty=function(){return we.safeEmpty($(this))},$.fn.safeRemove=function(){return we.safeRemove($(this))}},controllerToTag:e=>r(e.name).replace(/-controller$/,""),registerGlobal:e=>{we.register(e);let t=e.prototype._tagName;R.push(t)},cleanCache:()=>{T={}},register:(e,t=!1)=>{let n=we.controllerToTag(e);return!N[n]||t?(N[n]=[e,[]],e.prototype._tagName=n,{addMixin:(...e)=>{for(let t of e){let e;"string"==typeof t?e=r(t):t&&(e=we.controllerToTag(t)),N[n][1].push(e)}}}):{addMixin:(...e)=>{}}},post:(e,t,n)=>(n||(n={}),n.CSRF_TOKEN=we.CSRF_TOKEN,we.ajax(e,t,n,$.post)),get:(e,t,n)=>we.ajax(e,t,n,$.get),ajax:(e,t,n,r)=>{n||(n={}),n.VERSION=we.VERSION,n._method=n._method||"api";const s=new Promise((o,i)=>r(t,n).then((t,n,r)=>{o(t,n,r),"redirect"===t.status?q("onNavLink",t["url-link"]):s.then(()=>{we.refresh(e.$container)})}).catch(i));return s},submitFormAndUpdateView:(e,t,n,r)=>{let s=new FormData(t);const o=e=>{e["url-link"]?q("onNavLink",e["url-link"]):window.location.href=e.url},l=new Promise((a,c)=>{i(s,n||t.action,r||t.method).then((t,n,r)=>{a(t,n,r),"redirect"===t.status?o(t):l.then(()=>{we.refresh(e.$container,e)})}).catch((e,t,n)=>{301===e.status?(e=e.responseJSON,o(e),a(e,t,n)):c(e,t,n)})});return l},submitForm:(e,t,n)=>{let r=new FormData(e);return new Promise((s,o)=>{i(r,t||e.action,n||e.method).then(s).catch(o)})},getController:e=>Q(e),safeEmpty:e=>(e.children().each(function(e,t){let n=$(t);we.safeRemove(n)}),e),safeReplace:(e,t)=>(t.insertBefore(e),we.safeRemove(e)),safeRemove:e=>(e.each(function(){let e=$(this);e.data(`${A}`)&&e.data(`${A}`).remove()}),e.find(`.${M}`).each(function(){const e=$(this).data(`${A}`);e&&e.remove()}),e.remove()),reloadController:e=>function(e){if(e.contentUrl){let t=V(e);return e.contentUrl=t.url,D(e,t.args)}return new Promise(e=>{e($())})}(e).then(t=>{let n=$(t);return we.reconcile(e,n)}),reconcile:(e,t,n=null,r=null)=>{if(!n){let n=e.$container.clone().empty();n.data(A,null),n.removeClass(M),n.append(t),t=n}n=n??e.$container;const{refreshProcess:s,isRunningProcess:o}=k(r,e);return X(t,e,s).then(()=>{var r;return K(t,n),(r=e)._childController={},r.find(`.${M}`).each(function(){const e=Q($(this));e===r&&C(r,e)}),o||E(s),e})},refresh:(e,t=null)=>X(e,t)},be=[];function $e(){if(!jest)throw new Error("JEST is not defined");0===be.length&&(ve=$.ajax.bind($),be.push(jest.spyOn($,"ajax")),be[0].mockImplementation(function(e){return ve(e).then(e=>e).catch(e=>e)}))}const Re=fe,Ne={get_controller:async function(e,t={},n=""){$e();const r=$("body");we.updateJquery(),r.safeEmpty();const s=$(`<${e}>${n}</${e}>`);for(const[e,n]of Object.entries(t))s.data(e,n);const o=$("<div></div>").append(s);r.append(o),we._isInit=!1,we.cleanCache(),await we.init_sdc();const i=we.getController(s);return i.navControllerPath=[e],i},getCsrfToken:function(){return function(e){if(document.cookie&&""!==document.cookie){const t=document.cookie.split(";");for(let n=0;n<t.length;n++){const r=t[n].trim();if(r.substring(0,10)===e+"=")return decodeURIComponent(r.substring(10))}}return""}("csrftoken")},controllerFromTestHtml:async function(e,t=null){$e();const n=$("body");we.updateJquery(),n.safeEmpty().append(e),we._isInit=!1,we.cleanCache(),await we.init_sdc();let r=we.rootController.iterateAllChildren();if(!t)return r;const s=r[0].onRefresh,o=jest.spyOn(r[0],"onRefresh");return new Promise(e=>{o.mockImplementation(function(){o.mockRestore();const t=s.apply(r[0],arguments);return e(r),t})})}};export{ye as AbstractSDC,ae as SdcModel,le as SdcQuerySet,I as allOff,we as app,a as checkIfParamNumberBoolOrString,u as clearErrorsInForm,S as controllerFactory,L as on,Z as registerModel,F as runControlFlowFunctions,d as setErrorsInForm,j as setEvent,Re as socketReconnect,Ne as test_utils,q as trigger};
|
|
1
|
+
let e;function t(){return new Promise(function(e){e()})}function n(e){return(e=(e=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)).replace(/[0-9]+/g,e=>`-${e}`)).replace(/^[-]/g,"")}function r(e){return e.replace(/-./g,e=>`${e[1].toUpperCase()}`)}const s=(e,t)=>{let n=t,r=Object.getOwnPropertyNames(e.prototype).concat(Object.getOwnPropertySymbols(e.prototype));for(;""!==n.name;)Object.getOwnPropertyNames(n.prototype).concat(Object.getOwnPropertySymbols(n.prototype)).forEach(t=>{t.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/)||r.includes(t)||(r.push(t),Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)))}),n=Object.getPrototypeOf(n)};function o(e,t,n){return $.ajax({url:t,type:n||"POST",xhr:function(){var e=$.ajaxSettings.xhr();return e.upload&&e.upload.addEventListener("progress",i,!1),e},data:e,cache:!1,contentType:!1,processData:!1,beforeSend:function(e,t){(function(e){return/^(GET|HEAD|OPTIONS|TRACE)$/.test(e)})(t.type)||this.crossDomain||e.setRequestHeader("X-CSRFToken",window.CSRF_TOKEN)}})}function i(e){if(e.lengthComputable){var t=Math.round(e.loaded/e.total*100),n=$(".progress-container");100===t?n.hide():n.show(),t+="%",n.find(".progress-bar").css({width:t}).text(t)}}function l(e,t=null){return"string"!=typeof e?e:t&&void 0!==t[e]?"function"==typeof t[e]?t[e].bind(t):t[e]:e.match(/^(true|false)$/)?"true"===e:"undefined"!==e?"none"===e.toLowerCase()?null:e.match(/^-?\d+$/)?parseInt(e):e.match(/^-?\d+\.?\d+$/)?parseFloat(e):e.match(/^(['][^']*['])|(["][^"]*["])$/)?e.substr(1,e.length-2):e:void 0}function a(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))}function c(e){e.find(".has-error").removeClass("has-error").find(".alert-danger").remove(),e.find(".non-field-errors").remove()}function u(e,t){t=$("<div>").append(t),e.find(".has-error").removeClass("has-error").find(".alert-danger").safeRemove(),e.find(".non-field-errors").safeRemove();let n=t.find("input[type=file]").parent();e.find("input[type=file]").parent().each(function(e){$(this).replaceWith(n[e])});let r=0===t.find(".non-field-errors").insertAfter(e.find(".hidden-form-fields")).length;return t.find(".has-error").each(function(){r=!1;let t=$(this),n=t.data("auto-id"),s=e.find(".form-group."+n);s.addClass("has-error"),s.find(".form-input-container").append(t.find(".alert-danger"))}),r}function d(e){let{type:t,name:n}=e;return n&&""!==n?"hidden"===t?(r=$(e).val()).toLowerCase().match(/^(true|false)$/)?"true"===r.toLowerCase():"undefined"!==r?"none"===r.toLowerCase()?null:r.match(/^-?\d+$/)?parseInt(r,10):r.match(/^-?\d+\.?\d+$/)?parseFloat(r):r.match(/^(['][^']*['])|(["][^"]*["])$/)?r.substring(1,r.length-1):r:void 0:"checkbox"===t?e.checked:"file"===t?e.files[0]:$(e).val():null;var r}function h(e,t){let{type:n,name:r}=e;if(r&&""!==r)if("checkbox"===n)e.checked=!!t;else if("file"===n){if(t instanceof File&&"undefined"!=typeof DataTransfer){let n=new DataTransfer;n.items.add(t),e.files=n}}else t instanceof le?$(e).val(t.id):t instanceof ie?$(e).val(`[${t.getIds().join(",")}]`):(null===t&&(t=""),$(e).val(t));return null}function f(e,t=null){return Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==T).map(([e,n])=>{if("string"==typeof n&&n.startsWith("SDC_JSON_MODEL=["))try{const{pk:t,fields:r}=JSON.parse(n.slice(16,-1));return[e,{...r,id:t,id:t}]}catch{}return[e,l(n,t)]}))}function m(e,t=null){return f(e.data(),t)}const p=["onbeforeunload","onunload"],y=Object.keys(window).filter(e=>/^on/.test(e)&&!p.includes(e)).map(e=>e.slice(2));function g(e,t,n){let r;switch(e){case"mouseleave":case"mouseout":case"mouseenter":case"mousein":return r=document.elementFromPoint(t.clientX,t.clientY),n!==r&&!n.contains(r);default:return!0}}function v(e){let t=e.type;e.hasOwnProperty("namespace")&&e.namespace&&e.namespace.length&&(t+=`.${e.namespace}`);let n=$(e.target),r=null,s=!1,o=!1;for(e.stopImmediatePropagation=()=>o=!0,e.stopPropagation=()=>o=s=!0;n.length;){let i=n.attr(`sdc_${t}`);if(i&&g(t,e,n[0])){if(!r&&(r=V(n),!r))return;for(;r;){if(i.split(" ").forEach(o=>{if(s)return;let i=null;if("function"==typeof o)i=o;else if("function"==typeof r[o])i=r[o];else if("string"==typeof o&&o.startsWith("this.event_")){if(i=r.getEvents()[t],!i)return;if(i=i[o.slice(11)],!i)return}i&&i.call(r,n,e)}),o)return;r=r._parentController}}if(s)return;n=n.parent()}return{res:!0}}function w(e){if(e._isEventsSet)return;const t=e.getEvents();for(let n in t)if(t.hasOwnProperty(n)){let r=t[n];for(let t in r)r.hasOwnProperty(t)&&e.find(t).each(function(){let e=$(this),r=e.attr(`sdc_${n}`)||null;r=r?r.split(" "):[];const s=`this.event_${t}`;-1===r.indexOf(s)&&(r.push(s),e.attr(`sdc_${n}`,r.join(" ")))})}}let b=[],R={};function N(e,t){if(e){let n=r(t._tagName);e._childController[n]||(e._childController[n]=[]),e._childController[n].push(t)}return t._parentController=e}function C(e,t,n,r){let o=[];r=function(e,t){e=(e=e.concat(R[t][1])).filter((e,t,n)=>n.indexOf(e)===t);let n=!0;for(;n;){n=!1;for(let t of e)for(let r of R[t][1])e.includes(r)||(e.push(r),n=!0)}return e}(r,n);for(let e of r)o.push(R[e][0]);let i=new(function(e,...t){let n={[e.name]:class{constructor(...n){let r={};t.forEach(e=>{let t;Object.assign(this,t=new e),t._tagName=e.prototype._tagName,t._isMixin=!0,r[e.name]=t}),Object.assign(this,new e),this._mixins=r}static get name(){return e.name}static className(){return this.name}get mixins(){return this._mixins}}}[e.name];return s(n,e),t.forEach(e=>{s(n,e)}),n}(R[n][0],...o));return i._tagName=n,N(e,i),i.$container=t,function(e,t){!function(e,t,n){e&&"function"==typeof e.onInit&&(e.params=m(t,n._parentController))}(t,e,t)}(t,i),i}function O(e,t,n,s){if(b.includes(n)){let o=r(n);return window[o]||(window[o]=C(e,t,n,s)),window[o].$container=t,window[o]}return C(e,t,n,s)}function S(e,n){const r=function(e){return function(e){let t={args:{}};return e.contentUrl&&(t=J(e),e.contentUrl=t.url),Promise.all([U(e,t.args)]).then(function(e){let t=e[0];if(t)try{return $(t)}catch{return $("<div></div>").append(t)}return null})}(e).then(n=>!e.onLoad||e._onLoadDone?n:(e._onLoadDone=!0,(e.onLoad(n)||t()).then(()=>n)))}(e).then(function(t){return function(e,t){return B(e,t).then(function(t){if(t=t||!0,e.willShow){let n=e.willShow();if(n instanceof Promise)return n.then(function(){return t})}return t})}(e,t)}).then(()=>function(e,t){return H(null,e,t)}(e,n)).catch(function(t){if("string"==typeof t||t instanceof $)return B(e,t);throw t});return e.load_async?Promise.resolve():r}function F(e){const t=function(e){let t=[];for(;e;)e._isEventsSet=!1,t.unshift(e),e=e._parentController;return t}(e.controller[0]),n=t.concat(e.controller.slice(1));for(let t of n)w(t),t.onRefresh(e.controller[0])}function E(e,t){let n=Boolean(e);return n?e.uuids.has(t._uuid)||(e.uuids.add(t._uuid),e.controller.push(t)):e={uuids:new Set([t._uuid]),controller:[t]},{isRunningProcess:n,refreshProcess:e}}let k={},P={};function x(e,t){return L(e),P.hasOwnProperty(e)?t[P[e]]?void k[e].push(t):console.log("No event handler: "+e,t):console.log("No event: "+e,t)}function L(e,t){t||(t=e),P[e]||(P[e]=t,k[e]=[])}function I(e){for(let t in k)if(k.hasOwnProperty(t))for(let n=k[t].length-1;n>=0;n--)e===k[t][n]&&k[t].splice(n,1)}function j(e){let n=Array.apply(null,arguments);if(e=n.shift(),!k.hasOwnProperty(e)||!P.hasOwnProperty(e))return t();let r=k[e],s=P[e],o=[];for(let e=0;e<r.length;e++){let t=r[e][s].apply(r[e],n);void 0!==t&&o.push(t)}return Promise.all(o)}let q={};const T="_controller_",A="_sdc_controller_";function M(e,t,n){if(!e)return[];let r=e.children(),s=[];return r.each(function(e,r){let o=$(r),i=o.prop("tagName").toLowerCase().split("_");$.inArray(i[0],t)>=0?s.push({tag:i[0],super:i.splice(1)||[],dom:o}):i[0].startsWith("this.")?o.addClass(`_bind_to_update_handler sdc_uuid_${n._uuid}`):s=s.concat(M(o,t,n))}),s}function U(e,t){const{contentUrl:n,_tagName:r,contentReload:s}=e;return n?q[r]?Promise.resolve(q[r]):(t.VERSION=ve.VERSION,t._method="content",$.get(n,t).then(function(e){return s||(q[r]=e),e}).catch(function(t){if(301===t.status){const n=t.responseJSON;return j("_RedirectOnView",n["url-link"]),s||(e.autoRedirect=n["url-link"]),"<p>Redirected</p>"}throw e.autoRedirect=null,"function"==typeof e.confirmPageLoaded&&j("navLoaded",{controller_name:()=>t.status}),`<sdc-error data-code="${t.status}">${t.responseText}</sdc-error>`})):Promise.resolve(!1)}function D(e,t,n=null){return t=t||e.data(T),W(ve.tagNames,e,t,n)}function J(e){let t=e.contentUrl;if(e&&0===e._urlParams.length){let n,r=/%\(([^)]+)\)\w/gm;for(e._urlParams=[];n=r.exec(t);)e._urlParams.push(n[1]),e.contentReload=!0}let{args:n,params:r}=function(e,t){const n=m(t,e),[r,s]=Object.entries(n).reduce(([t,n],[r,s])=>(e._urlParams.includes(r)?t[r]=s:n[r]=s,[t,n]),[{},{}]);return{params:r,args:s}}(e,e.$container);return e._urlParams.length&&(t=function(e,t,n){for(let r in e._urlParams)if(e._urlParams.hasOwnProperty(r)){let s=e._urlParams[r],o=RegExp("%\\("+s+"\\)\\w","gm");const i=n[s];i||console.warn(`${s} is not set for controller ${e._tagName}`),t=t.replace(o,i)}return t}(e,t,r)),e.parsedContentUrl=t,{url:t,args:n}}function V(e){return e.hasClass(A)?e.data(`${T}`):e.closest(`.${A}`).data(`${T}`)}function Q(e,t,n,r,s){let o=e.data(T);return o?D(e,o,s):(o=O(r,e,t,n),e.data(T,o),e.addClass(A),S(o,s))}function B(e,t,n=null){if(t&&t.length>0){e.$container.empty(),e.$container.attr(e._tagName,"");for(let t in e._mixins)e.$container.attr(e._mixins[t]._tagName,"");e.$container.append(t)}return D(e.$container,e,n)}function W(e,t,n,r){return new Promise(s=>{let o=M(t,e,n),i=o.length;if(0===i)return s();for(let e=0;e<o.length;e++)Q(o[e].dom,o[e].tag,o[e].super,n,r).then(()=>{if(i--,0===i)return s()})})}function G({$element:e,id:t=[],parent:n=null}){t.push(function(e){if(3===e[0].nodeType)return`TEXT__${e[0].nodeValue}`;const t=[e[0].tagName];return"INPUT"===e[0].nodeName&&[["name",""],["type","text"],["id",""]].forEach(([n,r])=>{const s=e.attr(n)??r;s&&t.push(s)}),t.join("__")}(e));const r={$element:e,id:t.join("::"),depth:t.length,idx:0,getRealParent:()=>n,getIdx:function(){return this.idx=Math.max(0,(this.getRealParent()?.getIdx()??-1)+e.index()+1),this.idx},op:null,parent:n};return r.getIdx.bind(r),[r].concat(e.contents().toArray().map(e=>G({$element:$(e),id:t.slice(),parent:r})).flat())}function z(e,t){const n=G({$element:t}),r=G({$element:e});n.map((e,t)=>e.idx=t),r.map((e,t)=>e.idx=t);const s=Math.max(...r.concat(n).map(e=>e.depth)),o=K(n,r,s);let i=[];window.MAIN=t,window.OPS=o,o.forEach((e,t)=>{const{op:n,$element:r,idx:s}=e;if("keep_counterpart"===n.type){if(n.counterpart.getIdx()!==s){const t=e.getBefore();t?n.counterpart.$element.insertAfter(t.$element):e.getRealParent().$element.prepend(n.counterpart.$element)}!function(e,t){const n=e[0].attributes??[],r=t[0].attributes??[];[...n].forEach(n=>{t.is(`[${n.name}]`)||e.removeAttr(n.name)}),[...r].forEach(t=>{t.name.startsWith("data")||e.attr(t.name)===t.value||e.attr(t.name,t.value)}),e.removeData(),Object.entries(t.data()).forEach(([t,n])=>{e.data(t,n)})}(n.counterpart.$element,r),r.hasClass(A)&&(r.data(T).$container=n.counterpart.$element,r.data(T,null)),i.push(r)}else if("delete"===n.type)r.safeRemove();else if("insert"===n.type){const{after:t,target:n}=e.op;t?r.insertAfter(t.$element):n&&n.$element.prepend(r)}}),i.forEach(e=>e.safeRemove())}function K(e,t,n){return t.filter(e=>e.depth===n&&!e.op).forEach(t=>{const n=e.find(e=>!e.op&&e.id===t.id);if(n){const e=(t,n)=>{t.op={type:"keep",idx:n.idx},n.op={type:"keep_counterpart",counterpart:t},t=t.parent,n=n.parent,!t||t.op||n?.op||e(t,n)};e(n,t)}}),n>1?K(e,t,n-1):(e.forEach((t,n)=>{if(!t.op){const r=(e[n-1]?.op.idx??-1)+1;t.op={type:"delete",idx:r}}}),t.forEach((e,n)=>{if(e.getBefore=()=>function(e,n){const r=e.depth;for(;n>=1&&e.depth>=r;)if((e=t[n-=1]).depth===r)return"keep_counterpart"===e.op.type?e.op.counterpart:e;return null}(e,n),e.getRealParent=()=>{return(t=e).parent?"keep_counterpart"===t.parent.op.type?t.parent.op.counterpart:t.parent:null;var t},!e.op){const t=e.getRealParent(),n="insert"===t?.op.type?"insert_ignore":"insert";e.op={type:n,target:t,after:e.getBefore()}}}),[...e,...t].sort((e,t)=>(e.op?.idx??e.idx)-(t.op?.idx??t.idx)))}function H(e,t,n=null){if(t||(t=V(e)),!t)return Promise.resolve();const{refreshProcess:r,isRunningProcess:s}=E(n,t);return e??=t.$container,W(ve.tagNames,e,t,n).then(()=>function(e,t,n){return function(e,t,n){const r=[];return t.find(`._bind_to_update_handler.sdc_uuid_${e._uuid}`).each(function(){const t=$(this);let s;if(t.hasClass("_with_handler"))s=t.data("handler");else{let t=this.tagName.toLowerCase().replace(/^this./,"");e[t]&&(s=e[t])}if("function"==typeof s){const n=f(t.data(),e);s=s.bind(e)(n)}s&&r.push(Promise.resolve(s).then(r=>{let s=$("<div></div>");return s.append(r),""===t.html()&&t.append("<div></div>"),ve.reconcile(e,s,t.children(),n)}))}),Promise.all(r)}(e,t??e.$container,n)}(t,e,r).then(()=>{s||F(r)}))}const X={};function Y(e,t){X[e]=t}function Z(e){return X[e]}const ee=25e3,te="_connecting_process",ne=e=>Object.assign(Object.create(Object.getPrototypeOf(e)),structuredClone(e));class re extends Error{constructor(e){"string"==typeof e&&(e={msg:e,is_error:!0,header:"Error"}),super(e.msg),this.msg=e.msg,this.header=e.header,this.is_error=e.is_error,this.html=e.html}}class se{constructor({name:e,url:t}){this.name=e,this.url=t,this.content=null}async load(e=!1){return!e&&this.content||(this.content=await new Promise((e,t)=>{$.get(this.url).then(e).catch(()=>{e("")})})),this.content}async text(){return this.load()}static isValid(e){return!(null===e||"object"!=typeof e||Array.isArray(e)||e instanceof File||"string"!=typeof e.url||"string"!=typeof e.name)}}function oe(e){const t=parseInt(e??-1,10);return Number.isNaN(t)?-1:t}class ie{constructor(e,t={}){return this.valuesList=[],this.loaded=!1,this.modelName=e,this.modelQuery=t??{},this._onNoOpenRequests=[],this._isConnected=!1,this._isConnectingProcess=!1,this._autoReconnect=!0,this.socket=null,this.openRequest={},this.modelId=0,this.onUpdate=()=>{},this.onCreate=()=>{},new Proxy(this,{get:(e,t)=>"symbol"==typeof t||isNaN(t)?e[t]:e.valuesList[t],set:(e,t,n)=>isNaN(t)?(e[t]=n,!0):(e.valuesList[t]=n,!0)})}[Symbol.iterator](){let e=-1;return{next:()=>(++e,e<this.valuesList.length?{value:this.valuesList[e],done:!1}:{value:null,done:!0})}}set on_create(e){this.onCreate=e}set on_update(e){this.onUpdate=e}setIds(e){const t=this._setIds(e),n={id__in:t.map(e=>e.id)};return this.setFilter(n),t}cloneObject;_setIds(e){if(null===e||""===e||Array.isArray(e)&&0===e.length)return this.valuesList=[],this.valuesList;if(e instanceof ie)return this.valuesList=e.valuesList.map(ne),this.valuesList.forEach(e=>e._setQuerySet(this,!0)),this.valuesList;if(e instanceof le)return this.valuesList=[ne(e)],this.valuesList.forEach(e=>e._setQuerySet(this,!0)),this.valuesList;let t,n=Number.NaN;if(Number.isInteger(e))n=e;else if(e instanceof Array){const n=e.map(e=>parseInt(e));n.some(Number.isNaN)||(t=n)}else if("string"==typeof e){const r=e.split(",").map(e=>parseInt(e));r.some(Number.isNaN)?n=parseInt(e):t=r}if(Number.isNaN(n)){if(t){this.valuesList=this.valuesList.filter(e=>t.includes(e.id));const e=this.getIds();t.filter(t=>!e.includes(t)).forEach(e=>{this.valuesList.push(new(Z(this.modelName))({id:e}))})}}else this.valuesList=this.valuesList.filter(e=>n===e.id),0===this.valuesList.length&&(this.new().id=n);return this.valuesList}getIds(){return this.valuesList.map(e=>e.id)}get length(){return this.valuesList.length}byId(e){if(null!==e){const t=oe(e);return this.valuesList.find(e=>e.id===t)??null}return null}setFilter(e){return this.modelQuery=e,this}addFilter(e){return this.modelQuery=Object.assign({},this.modelQuery,e),this}new(e={}){const t=new(Z(this.modelName))(e);return t._setQuerySet(this,!1),this.valuesList.push(t),t}load(e=null){return this.valuesList=[],this.modelQuery=e??this.modelQuery,this._sendLoad()}update({modelQuery:e=null,item:t=null}){this.modelQuery=e??this.modelQuery;let n=t?{id:t.id}:this.modelQuery;return this._sendLoad(n)}delete({pk:e=null,id:t=null,elem:n=null}){if(e??=t,null===(e=n?n.id:e))throw new Error("pk or elem must be set");const r=a();return this.isConnected().then(()=>new Promise((t,n)=>{this.socket.send(JSON.stringify({event:"model",event_type:"delete",event_id:r,args:{model_name:this.modelName,model_query:this.modelQuery,id:e,pk:e}})),this.openRequest[r]=[t,n]}))}_sendLoad(e=null){return this.isConnected().then(()=>{const t=a();return new Promise((n,r)=>{this.socket.send(JSON.stringify({event:"model",event_type:"load",event_id:t,args:{model_name:this.modelName,model_query:e??this.modelQuery}})),this.openRequest[t]=[e=>{this.loaded=!0,n(e)},r]})})}_sendListView({modelQuery:e={},cbResolve:t=null,cbReject:n=null,templateContext:r={}}){return this.view({modelQuery:e,cbResolve:t,cbReject:n,templateContext:r,eventType:"list_view"})}view({viewName:e="html_list_template",modelQuery:t={},cbResolve:n=null,cbReject:r=null,templateContext:s={},eventType:o="named_view"}){let i=$('<div class="container-fluid">');return this.isConnected().then(()=>{const l=a();this.socket.send(JSON.stringify({event:"model",event_type:o,event_id:l,args:{view_name:e,model_name:this.modelName,model_query:t,template_context:s}})),this.openRequest[l]=[e=>{i.append(e.html),ve.refresh(i),n&&n(e)},e=>{r&&r(e)}]}),i}_sendDetailView({pk:e=null,id:t=null,cbResolve:n=null,cbReject:r=null,templateContext:s={}}){e??=t,e=oe(e);let o=$('<div class="container-fluid">');return this.isConnected().then(()=>{const t=a();this.socket.send(JSON.stringify({event:"model",event_type:"detail_view",event_id:t,args:{model_name:this.modelName,model_query:this.modelQuery,id:e,pk:e,template_context:s}})),this.openRequest[t]=[e=>{o.append(e.html),ve.refresh(o),n&&n(e)},e=>{r&&r(e)}]}),o}getForm({modelObj:e,eventType:t,formName:n,$divForm:r,cbResolve:s,cbReject:o,formId:i}){const l=a(),c=e.id??-1;this.isConnected().then(()=>{this.socket.send(JSON.stringify({event:"model",event_type:t,event_id:l,args:{model_name:this.modelName,id:c,pk:c,form_name:n}}))});const u=null===c||-1===c?"create":"edit";this.openRequest[l]=[t=>{r.append(t.html);let o=r.closest("form").addClass(`sdc-model-${u}-form sdc-model-form ${i}`).data("model",e).data("model_pk",c).data("form_name",n);e.addForm(o),o.length>0&&!o[0].hasAttribute("sdc_submit")&&o.attr("sdc_submit","submitModelFormDistributor"),ve.refresh(r).then(()=>null),s&&s(t)},e=>{o&&o(e)}]}async get(e=null,t=!1){if(t){const t=e?.id??this.modelQuery?.id;return e&&this.setFilter(e),this.byId(t)??this.new(e||this.modelQuery)}if(await this.load(e),1!==this.length)throw new Error(`model query returns ${this.length} but only 1 expected.`);return this.addFilter({id:this.valuesList[0].id}),this.valuesList[0]}detailView({pk:e,cbResolve:t=null,cbReject:n=null,templateContext:r={}}){return this._sendDetailView({id:e,cbResolve:t,cbReject:n,templateContext:r})}listView({modelQuery:e={},searchValues:t={},cbResolve:n=null,cbReject:r=null,templateContext:s={}}){return this._sendListView({modelQuery:Object.assign({},this.modelQuery,e,{__search_values:t}),cbResolve:n,cbReject:r,templateContext:s})}save({pk:e=null,id:t=null,formName:n="edit_form",data:r=null}={}){e??=t;const s=oe(e);return this.isConnected().then(()=>{let e;if(s>-1){const t=this.byId(s);if(!t)return Promise.reject(new re(`Element not found with ID: ${s}`));e=[t]}else e=this.valuesList;let t=[];return e.forEach(e=>{const s=a();t.push(new Promise((t,o)=>{this._readFiles(e).then(i=>{const l=r?{...r}:e.serialize();l.id=e.id,this.socket.send(JSON.stringify({event:"model",event_type:"save",event_id:s,args:{form_name:n,model_name:this.modelName,model_query:this.modelQuery,data:l,id:l.id,pk:l.id,files:i}})),this.openRequest[s]=[e=>{let n="string"==typeof e.data.instance?JSON.parse(e.data.instance):e.data.instance;e.data.instance=this._parseServerRes(n),t(e)},o]})}))}),Promise.all(t)})}create({elem:e=null,data:t=null}={}){const n=a();return e||(e=this.new(t)),this.isConnected().then(()=>new Promise((r,s)=>{this._readFiles(e).then(o=>{this.socket.send(JSON.stringify({event:"model",event_type:"create",event_id:n,args:{model_name:this.modelName,model_query:this.modelQuery,data:t??e?.serialize()??{},files:o}})),this.openRequest[n]=[t=>{let n="string"==typeof t.data.instance?JSON.parse(t.data.instance):t.data.instance;e&&(e.id=n[0]?.id||n[0]?.pk),t.data.instance=this._parseServerRes(n)[0],r(t)},s]})}))}isConnected(){return new Promise((e,t)=>{if(this._isConnected)e();else if(this._isConnectingProcess&&this.openRequest[te]){const[n,r]=this.openRequest[te];this.openRequest[te]=[()=>{n(),e()},()=>{r(),t()}]}else this._isConnectingProcess=!0,this.openRequest[te]=[()=>{},()=>{}],this._connectToServer().then(()=>{e(this._checkConnection())})})}close(){this.socket&&(this._autoReconnect=!1,this.socket.onclose=()=>{},this.socket.close(),delete this.socket),this.valuesList.forEach(e=>{e._onClose()})}_readFiles(e){let t=[],n={};return e?(Object.keys(e.constructor.fields).forEach(r=>{const s=e[r];s instanceof File&&t.push(new Promise(async(e,t)=>{const o=a();this.openRequest[o]=[e,t];const i=await s.arrayBuffer();let l=new Uint8Array(i),c=Math.ceil(l.length/ee);n[r]={id:o,file_name:s.name,field_name:r,content_length:s.size};for(let e=0;e<c;++e){const t=Array.from(l.slice(ee*e,ee*(e+1)));this.socket.send(JSON.stringify({event:"model",event_type:"upload",event_id:o,args:{chunk:t,idx:e,number_of_chunks:c,file_name:s.name,field_name:r,content_length:s.size,content_type:s.type,model_name:this.modelName,model_query:this.modelQuery}}))}}))}),Promise.all(t).then(()=>n)):Promise.resolve(n)}async _onMessage(e){let t=JSON.parse(e.data);if(t.is_error)this.openRequest.hasOwnProperty(t.event_id)&&(this.openRequest[t.event_id][1](new re(t)),this._closeOpenRequest(t.event_id)),(t.msg||t.header)&&j("pushErrorMsg",t.header||"",t.msg||""),"connect"===t.type&&(this.openRequest[te][1](new re(t)),this._closeOpenRequest(te),this._autoReconnect=!1,this.socket.close());else{if((t.msg||t.header)&&j("pushMsg",t.header||"",t.msg||""),"connect"===t.type)this._isConnected=!0,this._isConnectingProcess=!1,this.openRequest[te][0](t),this._closeOpenRequest(te);else if(["load","named_view","detail_view"].includes(t.type)){const e=JSON.parse(t.args.data);t.args.data=await this._parseServerRes(e)}else if("on_update"===t.type||"on_create"===t.type){const e=JSON.parse(t.args.data);let n,r=await this._parseServerRes(e);n="on_create"===t.type?this.onCreate:this.onUpdate,n(r),t.args.data=r}let e=t.data?.instance;e&&(t.data.instance=JSON.parse(t.data.instance)),this.openRequest.hasOwnProperty(t.event_id)&&(this.openRequest[t.event_id][0](t),this._closeOpenRequest(t.event_id))}}noOpenRequests(){return new Promise(e=>{if(0===Object.keys(this.openRequest).length)return e();this._onNoOpenRequests.push(e)})}_closeOpenRequest(e){delete this.openRequest[e],0===Object.keys(this.openRequest).length&&(this._onNoOpenRequests.forEach(e=>e()),this._onNoOpenRequests=[])}_connectToServer(){return new Promise(e=>{const t=`${this.modelName}`+(this.modelId>0?`/${this.modelId}`:"");"https:"===window.location.protocol?this.socket=new WebSocket(`wss://${window.location.host}/sdc_ws/model/${t}`):this.socket=new WebSocket(`ws://${window.location.host}/sdc_ws/model/${t}`),this.socket.onmessage=this._onMessage.bind(this),this.socket.onclose=e=>{console.error(`SDC Model (${this.modelName}, ${this.modelId}) Socket closed unexpectedly`),this._isConnected=!1;for(const[t,n]of Object.entries(this.openRequest))n[1](e);this.openRequest={},setTimeout(()=>{this._autoReconnect&&this._connectToServer().then(()=>{})},1e3)},this.socket.onerror=e=>{if(console.error(`Model Socket encountered error: ${e} Closing socket`),this._isConnected)try{this.socket.close()}catch(e){}},this.socket.onopen=()=>{e()}})}_checkConnection(){const e=a();return new Promise((t,n)=>{this.socket.send(JSON.stringify({event:"model",event_type:"connect",event_id:e,args:{model_name:this.modelName,model_query:this.modelQuery}})),this.openRequest[e]=[t,n]})}_parseServerRes(e){const t=[];for(const n of e){const e=Z(this.modelName);if(!e)throw new Error(`${this.modelName} is no SdcModel. mybe the models ar not importad.`);const r=new e({id:n.id??n.pk,...n.fields}),s=this.byId(r.id);s?(s.setValues(r),t.push(s)):(this.valuesList.push(r),r._setQuerySet(this,!0),t.push(r))}return this.valuesList.sort((e,t)=>e._id-t._id),t}}class le{static fields={};constructor(e){this._id=null,this._forms=[],this.loaded=!1,this.formId=a(),this.modelName=e}static querySet(e=null,t=null){return t?t.querySet(this.modeName,e):new ie(this.modeName,e)}addForm(e){const t=this._onChange.bind(this);this._forms.push(e),e&&e.on("input.formWatcher change.formWatcher","input, select, textarea",t)}_onChange(e){const{name:t}=e.target;this.constructor.fields[t]&&this[`set${t}`](d(e.target))}_updateForm(e){const t=this;this._forms.forEach(n=>{n.find(`[name="${e}"]`).each(function(){h(this,t[e])})})}setValues(e={}){throw new Error("setValues() must be implemented by subclass")}_setQuerySet(e,t){this._querySet=new WeakRef(e),this.loaded=t}get querySet(){return this._querySet.deref()}save({formName:e="edit_form",data:t=null}={}){return this._querySet.deref().save({pk:this.id,formName:e,data:t})}create({data:e=null}={}){return this._querySet.deref().create({elem:this,data:e})}delete(){return this._querySet.deref().delete({elem:this})}load(){return this._querySet.deref().update({item:this})}update(){return this.load()}get id(){return this._id}set id(e){this._id=e}set pk(e){this.id=e}get pk(){return this._id}close(){return this._querySet.deref().close()}_onClose(){Object.keys(this.constructor.fields).filter(e=>this[`_${e}`]instanceof ie).forEach(e=>this[`_${e}`].close())}detailView({cbResolve:e=null,cbReject:t=null,templateContext:n={}}){return this._querySet.deref().detailView({pk:this.id,cbResolve:e,cbReject:t,templateContext:n})}serialize(){return Object.entries(this.constructor.fields).reduce((e,[t,n])=>{const r=this[t];if(r instanceof ie)if(n.many_to_many||n.one_to_many)e[t]=r.getIds();else{const n=r.getIds();n.length>0?e[t]=n[0]:e[t]=null}else n.is_relation&&r instanceof le?e[t]=r.id??null:e[t]=r;return e},{})}toJson(){const e={};for(let t in this.constructor.fields){const n=this[t];n instanceof File?e[t]=n.name:e[t]=n instanceof le?n.id:n instanceof ie?n.getIds():n}return e}syncFormToModel(e){return this.syncForm(e)}_resolveForms(e){return e&&e.hasClass(this.formId)?e:$(`.${this.formId}`)}syncModelToForm(e){e=this._resolveForms(e);const t=this,n=this.constructor.fields;e.each(function(){const e=oe($(this).data("model_pk"));if(t.id===e)for(let e of this.elements){let r=e.name;r&&""!==r&&n[r]&&h(e,t[r])}})}syncForm(e){e=this._resolveForms(e);const t=this,n=this.constructor.fields,r={};function s(e,s){n[e]&&(t[e]=s),r[e]=s}return e.each(function(){const e=oe($(this).data("model_pk"));if(t.id===e||null===t.id&&-1===e){for(let e of this.elements)s(e.name,d(e));return t}}),r}form({cbResolve:e=null,cbReject:t=null}={}){return null===this.id||-1===this.id?this._createForm({cbReject:t,cbResolve:e}):this._editForm({cbReject:t,cbResolve:e})}_createForm({cbResolve:e=null,cbReject:t=null}){let n=$("<div>");return this._querySet.deref().getForm({modelObj:this,eventType:"create_form",formName:null,$divForm:n,cbResolve:e,cbReject:t,formId:this.formId}),n}_editForm({cbResolve:e=null,cbReject:t=null}){let n=$("<div>");return this._querySet.deref().getForm({modelObj:this,eventType:"edit_form",formName:null,$divForm:n,cbResolve:e,cbReject:t,formId:this.formId}),n}namedForm({formName:e,cbResolve:t=null,cbReject:n=null}){let r=$('<div class="container-fluid">');return this._querySet.deref().getForm({modelObj:this,eventType:"named_form",formName:e,$divForm:r,cbResolve:t,cbReject:n,formId:this.formId}),r}validate(e,t){const n=function(e,t){const{type:n,required:r,max_length:s,is_relation:o,many_to_many:i,one_to_many:l,many_to_one:a,one_to_one:c,related_model:u}=t;if(r&&(null==e||""===e))return"This field is required";if(null==e||""===e)return null;if((i||l||a||c)&&(!(e instanceof ie)||e.modelName!==u))return"string"==typeof e&&(e=JSON.parse(e)),(i||a)&&Array.isArray(e)&&e.some(e=>!Number.isNaN(parseInt(e)))?null:"object"!=typeof e&&Number.isNaN(parseInt(e))?"Must be object or ID":null;switch(n){case"CharField":case"TextField":if("string"!=typeof e)return"Must be a string";if(s&&e.length>s)return`Max length is ${s}`;break;case"IntegerField":case"AutoField":case"BigIntegerField":if(!isFinite(parseInt(e)))return"Must be an integer";break;case"FloatField":case"DecimalField":if(!isFinite(parseFloat(e)))return"Must be a number";break;case"BooleanField":if("boolean"!=typeof e)return"Must be a boolean";break;case"DateField":case"DateTimeField":if(isNaN(Date.parse(e)))return"Must be a valid date";break;case"EmailField":if("string"!=typeof e||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return"Invalid email";break;case"URLField":try{new URL(e)}catch{return"Invalid URL"}break;case"UUIDField":if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e))return"Invalid UUID";break;case"JSONField":if("object"!=typeof e)return"Must be JSON object";break;case"FileField":if(!(se.isValid(e)||e instanceof File||e instanceof se))return"Must be a valid file"}return null}(e,t);if(n)throw new Error(n)}parseValue(e,t){const{type:n,many_to_many:r,one_to_many:s,many_to_one:o,one_to_one:i}=t;if(null===e)return null;if((r||s||o||i)&&e&&"string"==typeof e)return JSON.parse(e);switch(n){case"CharField":case"TeextField":case"UUIDField":case"EmailField":return`${e}`;case"IntegerField":case"AutoField":case"BigIntegerField":return parseInt(e,10);case"FloatField":case"DecimalField":return parseFloat(e);case"BooleanField":return!!e;case"DateField":case"DateTimeField":return Date.parse(e);case"URLField":return new URL(e);case"FileField":if(null==e)return null;if("string"==typeof e)return null;if(se.isValid(e))return new se(e);if(e instanceof se)return new se(e);if("undefined"!=typeof File&&e instanceof File)return t.max_size&&e.size>t.max_size?`File too large (max ${t.max_size} bytes)`:t.allowed_types&&!t.allowed_types.includes(e.type)?`Invalid file type (${e.type})`:e;break;case"JSONField":if("object"==typeof e)return e;if("string"==typeof e)return JSON.parse(e)}return e}}let ae=!1,ce=!1,ue=null,de={};function he(){return window.SERVER_CALL_VIA_WEB_SOCKET?new Promise(e=>ae?e():ce?void setTimeout(()=>{he().then(()=>{e()})},200):e(me())):Promise.resolve(!0)}function fe(){window.SERVER_CALL_VIA_WEB_SOCKET&&function(){if(ae){ae=!1;try{ue.close()}catch(e){}}}()}function me(){return ce=!0,new Promise(e=>{ue="https:"===window.location.protocol?new WebSocket(`wss://${window.location.host}/sdc_ws/ws/`):new WebSocket(`ws://${window.location.host}/sdc_ws/ws/`),ue.onmessage=function(e){pe(JSON.parse(e.data))},ue.onclose=function(){ae&&console.error("SDC Socket closed unexpectedly"),ae=!1;for(const[e,t]of Object.entries(de))t[1]({}),delete de[e];setTimeout(()=>{me()},1e3)},ue.onerror=function(e){if(console.error("Socket encountered error: ",e.message,"Closing socket"),ae)try{ue.close()}catch(e){}},ue.onopen=function(){ae=!0,ce=!1,e()}})}function pe(e){if(e||(e={}),e.is_error)(e.msg||e.header)&&j("pushErrorMsg",e.header||"",e.msg||""),e.id&&de[e.id]&&(de[e.id][1](e.data||null),delete de[e.id]);else if((e.msg||e.header)&&j("pushMsg",e.header||"",e.msg||""),e.type&&"sdc_recall"===e.type)e.id&&de[e.id]&&(de[e.id][0](e.data),delete de[e.id]);else if(e.type&&"sdc_event"===e.type){let t=e.event;t&&j(t,e.payload)}else e.type&&"sdc_redirect"===e.type&&j("onNavLink",e.link)}class _e{constructor(){this._uuid=a(),this.contentUrl="",this.contentReload=!1,this.parsedContentUrl=null,this.events=[],this.load_async=!1,this._isEventsSet=!1,this._allEvents=null,this._autoRedirect=null,this._params={},this._urlParams=[],this._models=[],this._cssUrls=[],this.afterShow=()=>{console.warn("afterShow is deprecated!!")},this._mixins={},this._tagName=Object.getPrototypeOf(this)._tagName??"",this._childController={},this._parentController=null,this._onLoadDone=!1,this.$container=null,this._isMixin=!1}get params(){return this._params}set params(e){this._params=e}_runLifecycle(e,t){ve.DEBUG&&!this._isMixin&&console.debug(e,this._tagName);let n=[];if(!this._isMixin){this._isMixin=!0;for(let r in this._mixins){let s=this._mixins[r];"function"==typeof s[e]&&n.push(s[e].apply(this,t))}return Promise.all(n).then(()=>{this._isMixin=!1})}}onInit(){ve.DEBUG&&!this._isMixin&&console.debug(Array.apply(null,arguments),this._tagName)}set autoRedirect(e){this._autoRedirect=e}get autoRedirect(){return this._autoRedirect}get parentController(){return this._parentController}get childController(){return this._childController}onLoad(){return this._runLifecycle("onLoad",arguments)}willShow(){return this._runLifecycle("willShow",arguments)}onRefresh(){return this._runLifecycle("onRefresh",arguments)}onRemove(){return this._runLifecycle("onRemove",arguments),!0}noOpenModelRequests(){return Promise.all(this._models.map(e=>e.noOpenRequests()))}remove(){for(const e of this._models)e.close();let e=this._childController;for(let t in e)if(e.hasOwnProperty(t))for(let n of e[t])if(!n.remove())return!1;if(!this.onRemove||this.onRemove()){I(this);const e=r(this._tagName);if(this._parentController._childController[e]){let t=this._parentController._childController[e];for(let e=0;e<t.length;e++)t[e]===this&&t.splice(e,1)}return this.$container.remove(),!0}return!1}controller_name(){return this._tagName.replace(/-./g,e=>` ${e[1].toUpperCase()}`).replace(/^./g,e=>`${e.toUpperCase()}`)}addEvent(e,t,n){this.getEvents(),this._allEvents[e]=this._allEvents[e]||{},this._allEvents[e][t]=n}getEvents(){if(this._allEvents)return this._allEvents;let e=[];e=e.concat(this.events);for(let t in this._mixins){let n=this._mixins[t];Array.isArray(n.events)&&(e=e.concat(n.events))}return this._allEvents=_.merge(...e)}post(e,t){return ve.post(this,e,t)}get(e,t){return ve.get(this,e,t)}submitForm(e,t,n){return ve.submitFormAndUpdateView(this,e,t,n)}serverCall(e,t){let n=this.contentUrl.match(/sdc_view\/([^/]+)/i);if(n&&!(n.length<2))return function(e,t,n,r,s){return window.SERVER_CALL_VIA_WEB_SOCKET?function(e,t,n,r){let s=a();return he().then(()=>{ue.send(JSON.stringify({event:"sdc_call",id:s,controller:t,app:e,function:n,args:r}))}),new Promise((e,t)=>{de[s]=[e,t]})}(e,t,r,s):function(e,t,n){return"object"!=typeof n&&Array.isArray(n)&&null===n&&(n={arg0:n}),n={data:JSON.stringify(n),_sdc_func_name:t,_method:"sdc_server_call"},$.post({url:e,data:n,beforeSend:function(e,t){e.setRequestHeader("X-CSRFToken",window.CSRF_TOKEN)}}).then(e=>{const t=e._return_data;return pe(t),t}).catch(e=>{const t=e.responseJSON||{};throw t.is_error=!0,pe(t),e})}(n,r,s)}(n[1],this._tagName,this.parsedContentUrl??this.contentUrl,e,t);console.error("To use the serverCall function the contentUrl must be set: "+this.name)}querySet(e,t={}){const n=new ie(e,t);return this._models.push(n),n}newModel(e,t={}){return console.warn("newModel is deprecated and will soon be removed. Please use this.querySet(modelName, modelQuery)"),this.querySet(e,t)}find(e){return this.$container.find(e)}refresh(){return ve.refresh(this.$container,this)}reload(){return ve.reloadController(this)}reconcile(e,t=null){return ve.reconcile(this,e,t)}submitModelFormDistributor(e,t){return"function"==typeof this._submitModelForm?this._submitModelForm(e,t):"function"==typeof this.submitModelForm?this.submitModelForm(e,t):this.defaultSubmitModelForm(e,t)}iterateAllChildren(){let e=this._childController,t=[];for(let n in e)if(e.hasOwnProperty(n))for(let r of e[n])t.push(r),t.push(...r.iterateAllChildren());return t}defaultSubmitModelForm(e,t){if(!this._isMixin){t.stopPropagation(),t.preventDefault();let{model:n,form_name:r}=e.data(),s=n.syncForm(e);return new Promise((t,o)=>{let i;i=null!==n.id&&n.id>=0?n.save({formName:r,data:s}):n.create({data:s}),i.then(n=>{c(e),this.submit_model_form_success&&this.submit_model_form_success(n[0]);for(const e of this.iterateAllChildren())e.submit_model_form_success&&e.submit_model_form_success(n[0]);t(n)}).catch(t=>{this.reconcile($(`<div class="container-fluid">${t.html}</div>`),e.find(".container-fluid").first()),this.submit_model_form_error&&this.submit_model_form_error(t);for(const e of this.iterateAllChildren())e.submit_model_form_error&&e.submit_model_form_error(t);o(t)})})}return Promise.resolve()}}const ye={classname:"class"};window.sdcDom=function(e,t,...n){if(!e)return"";const r=function(e,t){let n,r=!1;if("string"==typeof e)n=$(document.createElement(e));else{const t=`this.${e.name}`;n=$(document.createElement(t)),n.data("handler",e),r=!0}return t&&Object.entries(t).forEach(([e,t])=>{e.startsWith("on")?n[0].addEventListener(e.substring(2).toLowerCase(),t):(ye[e.toLowerCase()]&&(e=ye[e.toLowerCase()]),n[0].setAttribute(e,t))}),r&&n.addClass("_bind_to_update_handler _with_handler"),n}(e,t);for(const e of n)r.append(e);return r};let ge,ve={CSRF_TOKEN:window.CSRF_TOKEN||"",LANGUAGE_CODE:window.LANGUAGE_CODE||"en",DEBUG:window.DEBUG||!1,VERSION:window.VERSION||"0.0",tagNames:[],Global:b,rootController:null,globalRootController:null,_isInit:!1,_origin_trigger:null,_globalControllerClasses:[],init_sdc:()=>{ve._isInit||(ve._isInit=!0,ve._origin_trigger?fe():(ve._origin_trigger=$.fn.trigger,$.fn.trigger=function(e){const t={}.hasOwnProperty.call(e,"type")?e.type:e;return y.includes(t)||(y.push(t),$(window).on(t,v)),ve._origin_trigger.call(this,e)},ve.updateJquery()),he(),function(){const e=$(window);y.forEach(t=>{e.off(t).on(t,v)})}(),ve.rootController=ve.rootController||new _e,ve.globalRootController=ve.globalRootController||new _e),ve.tagNames=Object.keys(R);const t=$("<div></div>");b.forEach(e=>{const n=R[e][0];t.append(`<${n.prototype._tagName}></${n.prototype._tagName}>`)});const{refreshProcess:n}=E(null,ve.rootController);return W(ve.tagNames,t,ve.globalRootController,n).then(()=>W(ve.tagNames,(e||(e=$("body")),e),ve.rootController,n).then(e=>(F(n),e)))},updateJquery:()=>{$.fn.safeReplace=function(e){return ve.safeReplace($(this),e)},$.fn.safeEmpty=function(){return ve.safeEmpty($(this))},$.fn.safeRemove=function(){return ve.safeRemove($(this))}},controllerToTag:e=>n(e.name).replace(/-controller$/,""),registerGlobal:e=>{ve.register(e);let t=e.prototype._tagName;b.push(t)},cleanCache:()=>{q={}},register:(e,t=!1)=>{let r=ve.controllerToTag(e);return!R[r]||t?(R[r]=[e,[]],e.prototype._tagName=r,{addMixin:(...e)=>{for(let t of e){let e;"string"==typeof t?e=n(t):t&&(e=ve.controllerToTag(t)),R[r][1].push(e)}}}):{addMixin:(...e)=>{}}},post:(e,t,n)=>(n||(n={}),n.CSRF_TOKEN=ve.CSRF_TOKEN,ve.ajax(e,t,n,$.post)),get:(e,t,n)=>ve.ajax(e,t,n,$.get),ajax:(e,t,n,r)=>{n||(n={}),n.VERSION=ve.VERSION,n._method=n._method||"api";const s=new Promise((o,i)=>r(t,n).then((t,n,r)=>{o(t,n,r),"redirect"===t.status?j("onNavLink",t["url-link"]):s.then(()=>{ve.refresh(e.$container)})}).catch(i));return s},submitFormAndUpdateView:(e,t,n,r)=>{let s=new FormData(t);const i=e=>{e["url-link"]?j("onNavLink",e["url-link"]):window.location.href=e.url},l=new Promise((a,c)=>{o(s,n||t.action,r||t.method).then((t,n,r)=>{a(t,n,r),"redirect"===t.status?i(t):l.then(()=>{ve.refresh(e.$container,e)})}).catch((e,t,n)=>{301===e.status?(e=e.responseJSON,i(e),a(e,t,n)):c(e,t,n)})});return l},submitForm:(e,t,n)=>{let r=new FormData(e);return new Promise((s,i)=>{o(r,t||e.action,n||e.method).then(s).catch(i)})},getController:e=>V(e),safeEmpty:e=>(e.children().each(function(e,t){let n=$(t);ve.safeRemove(n)}),e),safeReplace:(e,t)=>(t.insertBefore(e),ve.safeRemove(e)),safeRemove:e=>(e.each(function(){let e=$(this);e.data(`${T}`)&&e.data(`${T}`).remove()}),e.find(`.${A}`).each(function(){const e=$(this).data(`${T}`);e&&e.remove()}),e.remove()),reloadController:e=>function(e){if(e.contentUrl){let t=J(e);return e.contentUrl=t.url,U(e,t.args)}return new Promise(e=>{e($())})}(e).then(t=>{let n=$(t);return ve.reconcile(e,n)}),reconcile:(e,t,n=null,r=null)=>{if(!n){let n=e.$container.clone().empty();n.data(T,null),n.removeClass(A),n.append(t),t=n}n=n??e.$container;const{refreshProcess:s,isRunningProcess:o}=E(r,e);return H(t,e,s).then(()=>{var r;return z(t,n),(r=e)._childController={},r.find(`.${A}`).each(function(){const e=V($(this));e===r&&N(r,e)}),o||F(s),e})},refresh:(e,t=null)=>H(e,t)},we=[];function be(){if(!jest)throw new Error("JEST is not defined");0===we.length&&(ge=$.ajax.bind($),we.push(jest.spyOn($,"ajax")),we[0].mockImplementation(function(e){return ge(e).then(e=>e).catch(e=>e)}))}const $e=fe,Re={get_controller:async function(e,t={},n=""){be();const r=$("body");ve.updateJquery(),r.safeEmpty();const s=$(`<${e}>${n}</${e}>`);for(const[e,n]of Object.entries(t))s.data(e,n);const o=$("<div></div>").append(s);r.append(o),ve._isInit=!1,ve.cleanCache(),await ve.init_sdc();const i=ve.getController(s);return i.navControllerPath=[e],i},getCsrfToken:function(){return function(e){if(document.cookie&&""!==document.cookie){const t=document.cookie.split(";");for(let n=0;n<t.length;n++){const r=t[n].trim();if(r.substring(0,10)===e+"=")return decodeURIComponent(r.substring(10))}}return""}("csrftoken")},controllerFromTestHtml:async function(e,t=null){be();const n=$("body");ve.updateJquery(),n.safeEmpty().append(e),ve._isInit=!1,ve.cleanCache(),await ve.init_sdc();let r=ve.rootController.iterateAllChildren();if(!t)return r;const s=r[0].onRefresh,o=jest.spyOn(r[0],"onRefresh");return new Promise(e=>{o.mockImplementation(function(){o.mockRestore();const t=s.apply(r[0],arguments);return e(r),t})})}};export{_e as AbstractSDC,le as SdcModel,ie as SdcQuerySet,I as allOff,ve as app,l as checkIfParamNumberBoolOrString,c as clearErrorsInForm,O as controllerFactory,x as on,Y as registerModel,S as runControlFlowFunctions,u as setErrorsInForm,L as setEvent,$e as socketReconnect,Re as test_utils,j as trigger};
|
package/eslint.config.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import js from "@eslint/js";
|
|
2
2
|
import globals from "globals";
|
|
3
|
-
import babelParser from "@babel/eslint-parser";
|
|
4
|
-
import reactPlugin from "eslint-plugin-react";
|
|
5
|
-
import noRelativeImportPaths from "eslint-plugin-no-relative-import-paths";
|
|
6
3
|
|
|
7
4
|
export default [
|
|
8
5
|
{
|
|
@@ -11,42 +8,28 @@ export default [
|
|
|
11
8
|
{
|
|
12
9
|
files: ["src/**/*.js"],
|
|
13
10
|
languageOptions: {
|
|
14
|
-
parser: babelParser,
|
|
15
11
|
sourceType: "module",
|
|
16
12
|
ecmaVersion: "latest",
|
|
17
|
-
parserOptions: {
|
|
18
|
-
requireConfigFile: false,
|
|
19
|
-
babelOptions: {
|
|
20
|
-
presets: ["@babel/preset-env", "@babel/preset-react"],
|
|
21
|
-
},
|
|
22
|
-
ecmaFeatures: {
|
|
23
|
-
jsx: true,
|
|
24
|
-
},
|
|
25
|
-
},
|
|
26
13
|
globals: {
|
|
27
14
|
...globals.browser,
|
|
28
15
|
...globals.node,
|
|
29
16
|
},
|
|
30
17
|
},
|
|
31
|
-
plugins: {
|
|
32
|
-
react: reactPlugin,
|
|
33
|
-
"no-relative-import-paths": noRelativeImportPaths,
|
|
34
|
-
},
|
|
35
|
-
settings: {
|
|
36
|
-
react: {
|
|
37
|
-
version: "detect",
|
|
38
|
-
},
|
|
39
|
-
},
|
|
40
18
|
rules: {
|
|
41
19
|
...js.configs.recommended.rules,
|
|
42
|
-
...reactPlugin.configs.recommended.rules,
|
|
43
20
|
"no-console": "off",
|
|
44
21
|
"comma-dangle": ["warn", "only-multiline"],
|
|
45
|
-
"react/jsx-filename-extension": ["warn", { extensions: [".js", ".jsx"] }],
|
|
46
22
|
"prefer-destructuring": ["error", { object: true, array: false }],
|
|
47
|
-
"no-
|
|
23
|
+
"no-restricted-imports": [
|
|
48
24
|
"error",
|
|
49
|
-
{
|
|
25
|
+
{
|
|
26
|
+
patterns: [
|
|
27
|
+
{
|
|
28
|
+
group: ["./*", "../*"],
|
|
29
|
+
message: "import statements should have an absolute path",
|
|
30
|
+
},
|
|
31
|
+
],
|
|
32
|
+
},
|
|
50
33
|
],
|
|
51
34
|
"max-len": [
|
|
52
35
|
"error",
|
package/gulp/gulp.jsx
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
const sass = require('gulp-sass')(require('sass'));
|
|
2
2
|
const through = require('through2');
|
|
3
3
|
const {src, dest, series, parallel} = require('gulp');
|
|
4
|
-
const gclean = require('gulp-clean');
|
|
5
4
|
const fs = require('fs');
|
|
6
5
|
const exec = require('gulp-exec');
|
|
7
6
|
const dotenv = require("dotenv");
|
|
@@ -59,11 +58,7 @@ function pre_compile_javascript() {
|
|
|
59
58
|
}
|
|
60
59
|
|
|
61
60
|
function clean(done) {
|
|
62
|
-
|
|
63
|
-
return src('./_build').pipe(gclean());
|
|
64
|
-
} else {
|
|
65
|
-
done()
|
|
66
|
-
}
|
|
61
|
+
fs.rm('./_build', {recursive: true, force: true}, done);
|
|
67
62
|
}
|
|
68
63
|
|
|
69
64
|
function link_files(cb) {
|
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
'use strict'
|
|
2
2
|
|
|
3
3
|
const gulp = require('gulp');
|
|
4
|
-
const webpack = require('webpack
|
|
5
|
-
var named = require('vinyl-named');
|
|
4
|
+
const webpack = require('webpack');
|
|
6
5
|
|
|
7
|
-
function javascript() {
|
|
6
|
+
function javascript(done) {
|
|
8
7
|
const webpack_config = (process.env.NODE_ENV === 'development' ? './webpack.config/webpack.development.config.cjs' : './webpack.config/webpack.production.config.cjs');
|
|
9
8
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
9
|
+
const config = Object.assign({entry: {index: './src/index.js'}}, require(webpack_config));
|
|
10
|
+
|
|
11
|
+
webpack(config, (err, stats) => {
|
|
12
|
+
if (err) {
|
|
13
|
+
return done(err);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
console.log(stats.toString({colors: true, chunks: false}));
|
|
17
|
+
return done(stats.hasErrors() ? new Error('webpack build failed') : undefined);
|
|
18
|
+
});
|
|
14
19
|
}
|
|
15
20
|
|
|
16
21
|
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sdc_client",
|
|
3
|
-
"version": "0.158.
|
|
3
|
+
"version": "0.158.9",
|
|
4
4
|
"description": "Simple Dom Control",
|
|
5
5
|
"main": "dist/ugly.index.js",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"scripts": {
|
|
8
|
-
"build": "gulp development
|
|
9
|
-
"test": "gulp development
|
|
8
|
+
"build": "gulp development && gulp build",
|
|
9
|
+
"test": "gulp development && NODE_OPTIONS=--experimental-vm-modules jest",
|
|
10
10
|
"format": "prettier --write \"src/**/*.{js,jsx,scss,css,html,json}\"",
|
|
11
11
|
"format:js": "eslint --fix \"src/**/*.js\"",
|
|
12
12
|
"lint:js": "eslint \"src/**/*.js\""
|
|
@@ -26,37 +26,34 @@
|
|
|
26
26
|
"author": "Martin Starman",
|
|
27
27
|
"license": "MIT",
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@
|
|
30
|
-
"@babel/eslint-parser": "^7.27.1",
|
|
31
|
-
"@babel/plugin-transform-runtime": "^7.26.10",
|
|
32
|
-
"@babel/preset-env": "^7.26.9",
|
|
33
|
-
"@babel/preset-react": "^7.26.3",
|
|
34
|
-
"@babel/register": "^7.25.9",
|
|
35
|
-
"@eslint/js": "^9.19.0",
|
|
36
|
-
"babel-loader": "^10.0.0",
|
|
29
|
+
"@eslint/js": "^10.0.1",
|
|
37
30
|
"baseline-browser-mapping": "^2.9.19",
|
|
38
31
|
"dotenv": "^16.4.7",
|
|
39
|
-
"eslint": "^
|
|
40
|
-
"eslint-plugin-no-relative-import-paths": "^1.6.1",
|
|
41
|
-
"eslint-plugin-react": "^7.37.5",
|
|
32
|
+
"eslint": "^10.8.1",
|
|
42
33
|
"glob-parent": "^6.0.2",
|
|
43
34
|
"globals": "^15.14.0",
|
|
44
35
|
"gulp": "^5.0.1",
|
|
45
|
-
"gulp-clean": "^0.4.0",
|
|
46
36
|
"gulp-exec": "^5.0.0",
|
|
47
37
|
"gulp-sass": "^6.0.1",
|
|
48
|
-
"jest": "^
|
|
49
|
-
"jest-environment-jsdom": "^
|
|
38
|
+
"jest": "^30.4.2",
|
|
39
|
+
"jest-environment-jsdom": "^30.4.1",
|
|
50
40
|
"micromatch": "^4.0.8",
|
|
51
41
|
"prettier": "^3.8.1",
|
|
52
42
|
"sass": "^1.85.1",
|
|
53
43
|
"through2": "^4.0.2",
|
|
54
|
-
"
|
|
55
|
-
"webpack": "^5.104.1",
|
|
56
|
-
"webpack-stream": "^7.0.0"
|
|
44
|
+
"webpack": "^5.104.1"
|
|
57
45
|
},
|
|
58
46
|
"overrides": {
|
|
59
|
-
"glob
|
|
47
|
+
"glob": "^13.0.6",
|
|
48
|
+
"glob-parent": "$glob-parent",
|
|
49
|
+
"jsdom": "^29.1.1",
|
|
50
|
+
"test-exclude": "^8.0.0"
|
|
51
|
+
},
|
|
52
|
+
"resolutions": {
|
|
53
|
+
"glob": "^13.0.6",
|
|
54
|
+
"glob-parent": "^6.0.2",
|
|
55
|
+
"jsdom": "^29.1.1",
|
|
56
|
+
"test-exclude": "^8.0.0"
|
|
60
57
|
},
|
|
61
58
|
"dependencies": {
|
|
62
59
|
"@popperjs/core": "^2.11.8",
|
|
@@ -19,6 +19,7 @@ export class AbstractSDC {
|
|
|
19
19
|
this.load_async = false;
|
|
20
20
|
this._isEventsSet = false;
|
|
21
21
|
this._allEvents = null;
|
|
22
|
+
this._autoRedirect = null;
|
|
22
23
|
this._params = {};
|
|
23
24
|
|
|
24
25
|
this._urlParams = [];
|
|
@@ -115,6 +116,14 @@ export class AbstractSDC {
|
|
|
115
116
|
}
|
|
116
117
|
}
|
|
117
118
|
|
|
119
|
+
set autoRedirect(url){
|
|
120
|
+
this._autoRedirect = url;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
get autoRedirect() {
|
|
124
|
+
return this._autoRedirect;
|
|
125
|
+
}
|
|
126
|
+
|
|
118
127
|
get parentController() {
|
|
119
128
|
return this._parentController;
|
|
120
129
|
}
|
|
@@ -229,7 +229,10 @@ export function runControlFlowFunctions(controller, process) {
|
|
|
229
229
|
return runRefresh(controller, process);
|
|
230
230
|
})
|
|
231
231
|
.catch(function ($html) {
|
|
232
|
-
|
|
232
|
+
if (typeof $html === 'string' || $html instanceof $) {
|
|
233
|
+
return runControllerFillContent(controller, $html);
|
|
234
|
+
}
|
|
235
|
+
throw $html;
|
|
233
236
|
});
|
|
234
237
|
|
|
235
238
|
if (controller.load_async) {
|
|
@@ -118,7 +118,12 @@ function loadHTMLFile(controller, args) {
|
|
|
118
118
|
if (err.status === 301) {
|
|
119
119
|
const data = err.responseJSON;
|
|
120
120
|
trigger("_RedirectOnView", data["url-link"]);
|
|
121
|
+
if (!contentReload) {
|
|
122
|
+
controller.autoRedirect = data["url-link"];
|
|
123
|
+
}
|
|
124
|
+
return '<p>Redirected</p>';
|
|
121
125
|
}
|
|
126
|
+
controller.autoRedirect = null;
|
|
122
127
|
if (typeof controller.confirmPageLoaded === "function") {
|
|
123
128
|
trigger("navLoaded", { controller_name: () => err.status });
|
|
124
129
|
}
|
package/test/controller.test.js
CHANGED
|
@@ -29,7 +29,7 @@ describe('Controller', () => {
|
|
|
29
29
|
let ctr = new TestCtr();
|
|
30
30
|
ctr.$container = $('<test-ctr></test-ctr>');
|
|
31
31
|
let files = await sdc_view.loadFilesFromController(ctr);
|
|
32
|
-
expect(ajaxSpy).
|
|
32
|
+
expect(ajaxSpy).toHaveBeenCalledWith({
|
|
33
33
|
type: 'get',
|
|
34
34
|
url: 'TestCtr',
|
|
35
35
|
data: {
|
package/test/dist.test.js
CHANGED
|
@@ -63,7 +63,7 @@ describe('Controller', () => {
|
|
|
63
63
|
let ctr = new TestCtr();
|
|
64
64
|
ctr.$container = $('<test-ctr></test-ctr>');
|
|
65
65
|
let files = await sdc_view.loadFilesFromController(ctr);
|
|
66
|
-
expect(ajaxSpy).
|
|
66
|
+
expect(ajaxSpy).toHaveBeenCalledWith({
|
|
67
67
|
type: 'get',
|
|
68
68
|
url: 'TestCtr',
|
|
69
69
|
data: {
|