sdc_client 0.158.2 → 0.158.4

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.
@@ -1 +1 @@
1
- var e={};let t;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 n=/(?<=^|,\s?)[^=\s,]+/g,r=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;function s(){return new Promise(function(e){e()})}function o(e){return(e=(e=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)).replace(/[0-9]+/g,e=>`-${e}`)).replace(/^[-]/g,"")}function i(e){return e.replace(/-./g,e=>`${e[1].toUpperCase()}`)}const l=(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 a(e,t,n){return $.ajax({url:t,type:n||"POST",xhr:function(){var e=$.ajaxSettings.xhr();return e.upload&&e.upload.addEventListener("progress",c,!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 c(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 u(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 d(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))}function h(e){e.find(".has-error").removeClass("has-error").find(".alert-danger").remove(),e.find(".non-field-errors").remove()}function f(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 m(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 p(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 ue?$(e).val(t.id):t instanceof ce?$(e).val(`[${t.getIds().join(",")}]`):$(e).val(t);return null}function y(e,t=[]){return Object.fromEntries(Object.entries(e).filter(([e,n])=>e!==D&&!t.includes(e)).map(([e,t])=>{if("string"==typeof t&&t.startsWith("SDC_JSON_MODEL=["))try{const{pk:n,fields:r}=JSON.parse(t.slice(16,-1));return[e,{...r,id:n,pk:n}]}catch{}return[e,t]}))}function g(e,t,n=null){let r=function(e,t){let n;e||(e=[]);let r=t.data(),s=y(r,e);n=[];for(let t=0;t<e.length;t++){let s=e[t];r.hasOwnProperty(s)?n.push(r[s]):n.push("undefined")}return n.push(s),n}(e,t);return function(e,t=null){let n=[];for(let r=0;r<e.length;r++){let s=u(e[r],t);n.push(s)}return n}(r,n)}function v(e,t,s){if(!e)return!1;if("function"!=typeof e.onInit)return!1;let o;var i;"function"==typeof e._on_init_params?o=e._on_init_params():o=(i=e.onInit.toString().replace(r,"")).slice(i.indexOf("(")+1,i.indexOf(")")).match(n)||[];let l=g(o,t,s._parentController);if(e.onInit.apply(s,l),s===e)for(let n in e._mixins)v(e._mixins[n],t,s)}const w=["onbeforeunload","onunload"],b=Object.keys(window).filter(e=>/^on/.test(e)&&!w.includes(e)).map(e=>e.slice(2));function R(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 N(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&&R(t,e,n[0])){if(!r&&(r=G(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 C(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 O=[],S={};function k(e,t){if(e){let n=i(t._tagName);e._childController[n]||(e._childController[n]=[]),e._childController[n].push(t)}return t._parentController=e}function E(e,t,n,r){let s=[];r=function(e,t){e=(e=e.concat(S[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 S[t][1])e.includes(r)||(e.push(r),n=!0)}return e}(r,n);for(let e of r)s.push(S[e][0]);let o=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 l(n,e),t.forEach(e=>{l(n,e)}),n}(S[n][0],...s));return o._tagName=n,k(e,o),o.$container=t,function(e,t){v(t,e,t)}(t,o),o}function F(e,t,n,r){if(O.includes(n)){let s=i(n);return window[s]||(window[s]=E(e,t,n,r)),window[s].$container=t,window[s]}return E(e,t,n,r)}function P(e,t){const n=function(e){return function(e){let t={args:{}};return e.contentUrl&&(t=W(e),e.contentUrl=t.url),Promise.all([Q(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)||s()).then(()=>t)))}(e).then(function(t){return function(e,t){return K(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 ee(null,e,t)}(e,t)).catch(function(t){return K(e,t)});return e.load_async?Promise.resolve():n}function x(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)C(t),t.onRefresh(e.controller[0])}function I(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 L={},j={};function q(e,t){return T(e),j.hasOwnProperty(e)?t[j[e]]?void L[e].push(t):console.log("No event handler: "+e,t):console.log("No event: "+e,t)}function T(e,t){t||(t=e),j[e]||(j[e]=t,L[e]=[])}function M(e){for(let t in L)if(L.hasOwnProperty(t))for(let n=L[t].length-1;n>=0;n--)e===L[t][n]&&L[t].splice(n,1)}function A(e){let t=Array.apply(null,arguments);if(e=t.shift(),!L.hasOwnProperty(e)||!j.hasOwnProperty(e))return s();let n=L[e],r=j[e],o=[];for(let e=0;e<n.length;e++){let s=n[e][r].apply(n[e],t);void 0!==s&&o.push(s)}return Promise.all(o)}let U={};const D="_controller_",J="_sdc_controller_";function V(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(V(o,t,n))}),s}function Q(e,t){const{contentUrl:n,_tagName:r,contentReload:s}=e;return n?U[r]?Promise.resolve(U[r]):(t.VERSION=$e.VERSION,t._method="content",$.get(n,t).then(function(e){return s||(U[r]=e),e}).catch(function(t){throw 301===t.status&&A("_RedirectOnView",t.responseJSON["url-link"]),"function"==typeof e.confirmPageLoaded&&A("navLoaded",{controller_name:()=>t.status}),`<sdc-error data-code="${t.status}">${t.responseText}</sdc-error>`})):Promise.resolve(!1)}function B(e,t,n=null){return t=t||e.data(D),H($e.tagNames,e,t,n)}function W(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 n=function(e,t){return g(e._urlParams,t)}(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");t=t.replace(o,""+n.shift())}return t}(e,t,n)),e.parsedContentUrl=t,{url:t,args:n[n.length-1]}}function G(e){return e.hasClass(J)?e.data(`${D}`):e.closest(`.${J}`).data(`${D}`)}function z(e,t,n,r,s){let o=e.data(D);return o?B(e,o,s):(o=F(r,e,t,n),e.data(D,o),e.addClass(J),P(o,s))}function K(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 B(e.$container,e,n)}function H(e,t,n,r){return new Promise(s=>{let o=V(t,e,n),i=o.length;if(0===i)return s();for(let e=0;e<o.length;e++)z(o[e].dom,o[e].tag,o[e].super,n,r).then(()=>{if(i--,0===i)return s()})})}function X({$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=>X({$element:$(e),id:t.slice(),parent:r})).flat())}function Y(e,t){const n=X({$element:t}),r=X({$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=Z(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(J)&&(r.data(D).$container=n.counterpart.$element,r.data(D,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 Z(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?Z(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 ee(e,t,n=null){if(t||(t=G(e)),!t)return Promise.resolve();const{refreshProcess:r,isRunningProcess:s}=I(n,t);return e??=t.$container,H($e.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=y(t.data());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>"),$e.reconcile(e,s,t.children(),n)}))}),Promise.all(r)}(e,t??e.$container,n)}(t,e,r).then(()=>{s||x(r)}))}const te={};function ne(e,t){te[e]=t}function re(e){return te[e]}const se=25e3,oe="_connecting_process";class ie 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 le{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 ae(e){const t=parseInt(e??-1,10);return Number.isNaN(t)?-1:t}class ce{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){if(null===e||""===e||Array.isArray(e)&&0===e.length)return this.valuesList=[],this.valuesList;if(e instanceof ce)return this.valuesList=structuredClone(e.valuesList),this.valuesList.forEach(e=>e._setQuerySet(this,!0)),this.valuesList;if(e instanceof ue)return this.valuesList=[structuredClone(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(re(this.modelName))({id:e}))})}}else 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=ae(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(re(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?{pk:t.id}:this.modelQuery;return this._sendLoad(n)}delete({pk:e=null,elem:t=null}){if(null===(e=t?t.id:e))throw new Error("pk or elem must be set");const n=d();return this.isConnected().then(()=>new Promise((t,r)=>{this.socket.send(JSON.stringify({event:"model",event_type:"delete",event_id:n,args:{model_name:this.modelName,model_query:this.modelQuery,pk:e}})),this.openRequest[n]=[t,r]}))}_sendLoad(e=null){return this.isConnected().then(()=>{const t=d();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=d();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),$e.refresh(i),n&&n(e)},e=>{r&&r(e)}]}),i}_sendDetailView({pk:e=null,cbResolve:t=null,cbReject:n=null,templateContext:r={}}){e=ae(e);let s=$('<div class="container-fluid">');return this.isConnected().then(()=>{const o=d();this.socket.send(JSON.stringify({event:"model",event_type:"detail_view",event_id:o,args:{model_name:this.modelName,model_query:this.modelQuery,pk:e,template_context:r}})),this.openRequest[o]=[e=>{s.append(e.html),$e.refresh(s),t&&t(e)},e=>{n&&n(e)}]}),s}getForm({modelObj:e,eventType:t,formName:n,$divForm:r,cbResolve:s,cbReject:o,formId:i}){const l=d(),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,pk:a,form_name:n}}))});const c=null===a||-1===a?"create":"edit";this.openRequest[l]=[t=>{r.append(t.html);let o=r.closest("form").addClass(`sdc-model-${c}-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"),$e.refresh(r).then(()=>null),s&&s(t)},e=>{o&&o(e)}]}async get(e=null,t=!1){if(t){const t=e?.id??e?.pk;return 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.valuesList[0]}detailView({pk:e,cbResolve:t=null,cbReject:n=null,templateContext:r={}}){return this._sendDetailView({pk: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,formName:t="edit_form",data:n=null}={}){const r=ae(e);return this.isConnected().then(()=>{let e;if(r>-1){const t=this.byId(r);if(!t)return Promise.reject(new ie(`Element not found with ID: ${r}`));e=[t]}else e=this.valuesList;let s=[];return e.forEach(e=>{const r=d();s.push(new Promise((s,o)=>{this._readFiles(e).then(i=>{const l=n?{...n}:e.serialize();l.pk=e.id,this.socket.send(JSON.stringify({event:"model",event_type:"save",event_id:r,args:{form_name:t,model_name:this.modelName,model_query:this.modelQuery,data:l,pk:l.pk,files:i}})),this.openRequest[r]=[e=>{let t="string"==typeof e.data.instance?JSON.parse(e.data.instance):e.data.instance;e.data.instance=this._parseServerRes(t),s(e)},o]})}))}),Promise.all(s)})}create({elem:e=null,data:t=null}={}){const n=d();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]?.pk||n[0]?.id),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[oe]){const[n,r]=this.openRequest[oe];this.openRequest[oe]=[()=>{n(),e()},()=>{r(),t()}]}else this._isConnectingProcess=!0,this.openRequest[oe]=[()=>{},()=>{}],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=d();this.openRequest[o]=[e,t];const i=await s.arrayBuffer();let l=new Uint8Array(i),a=Math.ceil(l.length/se);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(se*e,se*(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 ie(t)),this._closeOpenRequest(t.event_id)),(t.msg||t.header)&&A("pushErrorMsg",t.header||"",t.msg||""),"connect"===t.type&&(this.openRequest[oe][1](new ie(t)),this._closeOpenRequest(oe),this._autoReconnect=!1,this.socket.close());else{if((t.msg||t.header)&&A("pushMsg",t.header||"",t.msg||""),"connect"===t.type)this._isConnected=!0,this._isConnectingProcess=!1,this.openRequest[oe][0](t),this._closeOpenRequest(oe);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=d();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=re(this.modelName);if(!e)throw new Error(`${this.modelName} is no SdcModel. mybe the models ar not importad.`);const r=new e({id:n.pk??n.id,...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 ue{static fields={};constructor(e){this._id=null,this._forms=[],this.loaded=!1,this.formId=d(),this.modelName=e}static querySet(e=null,t=null){return t?t.querySet(this.modeName,e):new ce(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}`](m(e.target))}_updateForm(e){const t=this;this._forms.forEach(n=>{n.find(`[name="${e}"]`).each(function(){p(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}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})}get id(){return this._id}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 ce).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 ce)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 ue?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 ue?n.id:n instanceof ce?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=ae($(this).data("model_pk"));if(t.id===e)for(let e of this.elements){let r=e.name;r&&""!==r&&n[r]&&p(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=ae($(this).data("model_pk"));if(t.id===e||null===t.id&&-1===e){for(let e of this.elements)s(e.name,m(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 ce)||e.modelName!==u))return"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(!Number.isInteger(e))return"Must be an integer";break;case"FloatField":case"DecimalField":if("number"!=typeof 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(!(le.isValid(e)||e instanceof File||e instanceof le))return"Must be a valid file"}return null}(e,t);if(n)throw new Error(n)}parseValue(e,t){const{type:n}=t;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":if("number"!=typeof e)return"Must be a number";break;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(le.isValid(e))return new le(e);if(e instanceof le)return new le(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 de=!1,he=!1,fe=null,me={};function pe(){return window.SERVER_CALL_VIA_WEB_SOCKET?new Promise(e=>de?e():he?void setTimeout(()=>{pe().then(()=>{e()})},200):e(ye())):Promise.resolve(!0)}function _e(){window.SERVER_CALL_VIA_WEB_SOCKET&&function(){if(de){de=!1;try{fe.close()}catch(e){}}}()}function ye(){return he=!0,new Promise(e=>{fe="https:"===window.location.protocol?new WebSocket(`wss://${window.location.host}/sdc_ws/ws/`):new WebSocket(`ws://${window.location.host}/sdc_ws/ws/`),fe.onmessage=function(e){ge(JSON.parse(e.data))},fe.onclose=function(){de&&console.error("SDC Socket closed unexpectedly"),de=!1;for(const[e,t]of Object.entries(me))t[1]({}),delete me[e];setTimeout(()=>{ye()},1e3)},fe.onerror=function(e){if(console.error("Socket encountered error: ",e.message,"Closing socket"),de)try{fe.close()}catch(e){}},fe.onopen=function(){de=!0,he=!1,e()}})}function ge(e){if(e||(e={}),e.is_error)(e.msg||e.header)&&A("pushErrorMsg",e.header||"",e.msg||""),e.id&&me[e.id]&&(me[e.id][1](e.data||null),delete me[e.id]);else if((e.msg||e.header)&&A("pushMsg",e.header||"",e.msg||""),e.type&&"sdc_recall"===e.type)e.id&&me[e.id]&&(me[e.id][0](e.data),delete me[e.id]);else if(e.type&&"sdc_event"===e.type){let t=e.event;t&&A(t,e.payload)}else e.type&&"sdc_redirect"===e.type&&A("onNavLink",e.link)}class ve{constructor(){this._uuid=d(),this.contentUrl="",this.contentReload=!1,this.parsedContentUrl=null,this.events=[],this.load_async=!1,this._isEventsSet=!1,this._allEvents=null,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}_runLifecycle(e,t){$e.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(){$e.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()){M(this);const e=i(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 $e.post(this,e,t)}get(e,t){return $e.get(this,e,t)}submitForm(e,t,n){return $e.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=d();return pe().then(()=>{fe.send(JSON.stringify({event:"sdc_call",id:s,controller:t,app:e,function:n,args:r}))}),new Promise((e,t)=>{me[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 ge(t),t}).catch(e=>{const t=e.responseJSON;throw t.is_error=!0,ge(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 ce(e,t);return this._models.push(n),n}newModel(e,t={}){return console.warn("newModel is deprecated and will soon be removed"),this.querySet(e,t)}find(e){return this.$container.find(e)}refresh(){return $e.refresh(this.$container,this)}reload(){return $e.reloadController(this)}reconcile(e,t=null){return $e.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=>{h(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 we={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):(we[e.toLowerCase()]&&(e=we[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 be,$e={CSRF_TOKEN:window.CSRF_TOKEN||"",LANGUAGE_CODE:window.LANGUAGE_CODE||"en",DEBUG:window.DEBUG||!1,VERSION:window.VERSION||"0.0",tagNames:[],Global:O,rootController:null,globalRootController:null,_isInit:!1,_origin_trigger:null,_globalControllerClasses:[],init_sdc:()=>{$e._isInit||($e._isInit=!0,$e._origin_trigger?_e():($e._origin_trigger=$.fn.trigger,$.fn.trigger=function(e){const t={}.hasOwnProperty.call(e,"type")?e.type:e;return b.includes(t)||(b.push(t),$(window).on(t,N)),$e._origin_trigger.call(this,e)},$e.updateJquery()),pe(),function(){const e=$(window);b.forEach(t=>{e.off(t).on(t,N)})}(),$e.rootController=$e.rootController||new ve,$e.globalRootController=$e.globalRootController||new ve),$e.tagNames=Object.keys(S);const e=$("<div></div>");O.forEach(t=>{const n=S[t][0];e.append(`<${n.prototype._tagName}></${n.prototype._tagName}>`)});const{refreshProcess:n}=I(null,$e.rootController);return H($e.tagNames,e,$e.globalRootController,n).then(()=>H($e.tagNames,(t||(t=$("body")),t),$e.rootController,n).then(e=>(x(n),e)))},updateJquery:()=>{$.fn.safeReplace=function(e){return $e.safeReplace($(this),e)},$.fn.safeEmpty=function(){return $e.safeEmpty($(this))},$.fn.safeRemove=function(){return $e.safeRemove($(this))}},controllerToTag:e=>o(e.name).replace(/-controller$/,""),registerGlobal:e=>{$e.register(e);let t=e.prototype._tagName;O.push(t)},cleanCache:()=>{U={}},register:(e,t=!1)=>{let n=$e.controllerToTag(e);return!S[n]||t?(S[n]=[e,[]],e.prototype._tagName=n,{addMixin:(...e)=>{for(let t of e){let e;"string"==typeof t?e=o(t):t&&(e=$e.controllerToTag(t)),S[n][1].push(e)}}}):{addMixin:(...e)=>{}}},post:(e,t,n)=>(n||(n={}),n.CSRF_TOKEN=$e.CSRF_TOKEN,$e.ajax(e,t,n,$.post)),get:(e,t,n)=>$e.ajax(e,t,n,$.get),ajax:(e,t,n,r)=>{n||(n={}),n.VERSION=$e.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?A("onNavLink",t["url-link"]):s.then(()=>{$e.refresh(e.$container)})}).catch(i));return s},submitFormAndUpdateView:(e,t,n,r)=>{let s=new FormData(t);const o=e=>{e["url-link"]?A("onNavLink",e["url-link"]):window.location.href=e.url},i=new Promise((l,c)=>{a(s,n||t.action,r||t.method).then((t,n,r)=>{l(t,n,r),"redirect"===t.status?o(t):i.then(()=>{$e.refresh(e.$container,e)})}).catch((e,t,n)=>{301===e.status?(e=e.responseJSON,o(e),l(e,t,n)):c(e,t,n)})});return i},submitForm:(e,t,n)=>{let r=new FormData(e);return new Promise((s,o)=>{a(r,t||e.action,n||e.method).then(s).catch(o)})},getController:e=>G(e),safeEmpty:e=>(e.children().each(function(e,t){let n=$(t);$e.safeRemove(n)}),e),safeReplace:(e,t)=>(t.insertBefore(e),$e.safeRemove(e)),safeRemove:e=>(e.each(function(){let e=$(this);e.data(`${D}`)&&e.data(`${D}`).remove()}),e.find(`.${J}`).each(function(){const e=$(this).data(`${D}`);e&&e.remove()}),e.remove()),reloadController:e=>function(e){if(e.contentUrl){let t=W(e);return e.contentUrl=t.url,Q(e,t.args)}return new Promise(e=>{e($())})}(e).then(t=>{let n=$(t);return $e.reconcile(e,n)}),reconcile:(e,t,n=null,r=null)=>{if(!n){let n=e.$container.clone().empty();n.data(D,null),n.removeClass(J),n.append(t),t=n}n=n??e.$container;const{refreshProcess:s,isRunningProcess:o}=I(r,e);return ee(t,e,s).then(()=>{var r;return Y(t,n),(r=e)._childController={},r.find(`.${J}`).each(function(){const e=G($(this));e===r&&k(r,e)}),o||x(s),e})},refresh:(e,t=null)=>ee(e,t)},Re=[];function Ne(){if(!jest)throw new Error("JEST is not defined");0===Re.length&&(be=$.ajax.bind($),Re.push(jest.spyOn($,"ajax")),Re[0].mockImplementation(function(e){return be(e).then(e=>e).catch(e=>e)}))}const Ce=_e,Oe={get_controller:async function(e,t={},n=""){Ne();const r=$("body");$e.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);return r.append(o),$e._isInit=!1,$e.cleanCache(),await $e.init_sdc(),$e.getController(s)},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){Ne();const n=$("body");$e.updateJquery(),n.safeEmpty().append(e),$e._isInit=!1,$e.cleanCache(),await $e.init_sdc();let r=$e.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{ve as AbstractSDC,ue as SdcModel,ce as SdcQuerySet,M as allOff,$e as app,u as checkIfParamNumberBoolOrString,h as clearErrorsInForm,F as controllerFactory,q as on,ne as registerModel,P as runControlFlowFunctions,f as setErrorsInForm,T as setEvent,Ce as socketReconnect,Oe as test_utils,A as trigger};
1
+ var e={};let t;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 n=/(?<=^|,\s?)[^=\s,]+/g,r=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;function s(){return new Promise(function(e){e()})}function o(e){return(e=(e=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)).replace(/[0-9]+/g,e=>`-${e}`)).replace(/^[-]/g,"")}function i(e){return e.replace(/-./g,e=>`${e[1].toUpperCase()}`)}const l=(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 a(e,t,n){return $.ajax({url:t,type:n||"POST",xhr:function(){var e=$.ajaxSettings.xhr();return e.upload&&e.upload.addEventListener("progress",c,!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 c(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 u(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 d(){return([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))}function h(e){e.find(".has-error").removeClass("has-error").find(".alert-danger").remove(),e.find(".non-field-errors").remove()}function f(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 m(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 p(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 ue?$(e).val(t.id):t instanceof ce?$(e).val(`[${t.getIds().join(",")}]`):(null===t&&(t=""),$(e).val(t));return null}function y(e,t=[]){return Object.fromEntries(Object.entries(e).filter(([e,n])=>e!==D&&!t.includes(e)).map(([e,t])=>{if("string"==typeof t&&t.startsWith("SDC_JSON_MODEL=["))try{const{pk:n,fields:r}=JSON.parse(t.slice(16,-1));return[e,{...r,id:n,pk:n}]}catch{}return[e,t]}))}function g(e,t,n=null){let r=function(e,t){let n;e||(e=[]);let r=t.data(),s=y(r,e);n=[];for(let t=0;t<e.length;t++){let s=e[t];r.hasOwnProperty(s)?n.push(r[s]):n.push("undefined")}return n.push(s),n}(e,t);return function(e,t=null){let n=[];for(let r=0;r<e.length;r++){let s=u(e[r],t);n.push(s)}return n}(r,n)}function v(e,t,s){if(!e)return!1;if("function"!=typeof e.onInit)return!1;let o;var i;"function"==typeof e._on_init_params?o=e._on_init_params():o=(i=e.onInit.toString().replace(r,"")).slice(i.indexOf("(")+1,i.indexOf(")")).match(n)||[];let l=g(o,t,s._parentController);if(e.onInit.apply(s,l),s===e)for(let n in e._mixins)v(e._mixins[n],t,s)}const w=["onbeforeunload","onunload"],b=Object.keys(window).filter(e=>/^on/.test(e)&&!w.includes(e)).map(e=>e.slice(2));function R(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 N(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&&R(t,e,n[0])){if(!r&&(r=G(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 C(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 O=[],S={};function k(e,t){if(e){let n=i(t._tagName);e._childController[n]||(e._childController[n]=[]),e._childController[n].push(t)}return t._parentController=e}function E(e,t,n,r){let s=[];r=function(e,t){e=(e=e.concat(S[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 S[t][1])e.includes(r)||(e.push(r),n=!0)}return e}(r,n);for(let e of r)s.push(S[e][0]);let o=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 l(n,e),t.forEach(e=>{l(n,e)}),n}(S[n][0],...s));return o._tagName=n,k(e,o),o.$container=t,function(e,t){v(t,e,t)}(t,o),o}function F(e,t,n,r){if(O.includes(n)){let s=i(n);return window[s]||(window[s]=E(e,t,n,r)),window[s].$container=t,window[s]}return E(e,t,n,r)}function P(e,t){const n=function(e){return function(e){let t={args:{}};return e.contentUrl&&(t=W(e),e.contentUrl=t.url),Promise.all([Q(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)||s()).then(()=>t)))}(e).then(function(t){return function(e,t){return K(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 ee(null,e,t)}(e,t)).catch(function(t){return K(e,t)});return e.load_async?Promise.resolve():n}function x(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)C(t),t.onRefresh(e.controller[0])}function I(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 L={},j={};function q(e,t){return T(e),j.hasOwnProperty(e)?t[j[e]]?void L[e].push(t):console.log("No event handler: "+e,t):console.log("No event: "+e,t)}function T(e,t){t||(t=e),j[e]||(j[e]=t,L[e]=[])}function M(e){for(let t in L)if(L.hasOwnProperty(t))for(let n=L[t].length-1;n>=0;n--)e===L[t][n]&&L[t].splice(n,1)}function A(e){let t=Array.apply(null,arguments);if(e=t.shift(),!L.hasOwnProperty(e)||!j.hasOwnProperty(e))return s();let n=L[e],r=j[e],o=[];for(let e=0;e<n.length;e++){let s=n[e][r].apply(n[e],t);void 0!==s&&o.push(s)}return Promise.all(o)}let U={};const D="_controller_",J="_sdc_controller_";function V(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(V(o,t,n))}),s}function Q(e,t){const{contentUrl:n,_tagName:r,contentReload:s}=e;return n?U[r]?Promise.resolve(U[r]):(t.VERSION=$e.VERSION,t._method="content",$.get(n,t).then(function(e){return s||(U[r]=e),e}).catch(function(t){throw 301===t.status&&A("_RedirectOnView",t.responseJSON["url-link"]),"function"==typeof e.confirmPageLoaded&&A("navLoaded",{controller_name:()=>t.status}),`<sdc-error data-code="${t.status}">${t.responseText}</sdc-error>`})):Promise.resolve(!1)}function B(e,t,n=null){return t=t||e.data(D),H($e.tagNames,e,t,n)}function W(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 n=function(e,t){return g(e._urlParams,t)}(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");t=t.replace(o,""+n.shift())}return t}(e,t,n)),e.parsedContentUrl=t,{url:t,args:n[n.length-1]}}function G(e){return e.hasClass(J)?e.data(`${D}`):e.closest(`.${J}`).data(`${D}`)}function z(e,t,n,r,s){let o=e.data(D);return o?B(e,o,s):(o=F(r,e,t,n),e.data(D,o),e.addClass(J),P(o,s))}function K(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 B(e.$container,e,n)}function H(e,t,n,r){return new Promise(s=>{let o=V(t,e,n),i=o.length;if(0===i)return s();for(let e=0;e<o.length;e++)z(o[e].dom,o[e].tag,o[e].super,n,r).then(()=>{if(i--,0===i)return s()})})}function X({$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=>X({$element:$(e),id:t.slice(),parent:r})).flat())}function Y(e,t){const n=X({$element:t}),r=X({$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=Z(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(J)&&(r.data(D).$container=n.counterpart.$element,r.data(D,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 Z(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?Z(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 ee(e,t,n=null){if(t||(t=G(e)),!t)return Promise.resolve();const{refreshProcess:r,isRunningProcess:s}=I(n,t);return e??=t.$container,H($e.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=y(t.data());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>"),$e.reconcile(e,s,t.children(),n)}))}),Promise.all(r)}(e,t??e.$container,n)}(t,e,r).then(()=>{s||x(r)}))}const te={};function ne(e,t){te[e]=t}function re(e){return te[e]}const se=25e3,oe="_connecting_process";class ie 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 le{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 ae(e){const t=parseInt(e??-1,10);return Number.isNaN(t)?-1:t}class ce{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){if(null===e||""===e||Array.isArray(e)&&0===e.length)return this.valuesList=[],this.valuesList;if(e instanceof ce)return this.valuesList=structuredClone(e.valuesList),this.valuesList.forEach(e=>e._setQuerySet(this,!0)),this.valuesList;if(e instanceof ue)return this.valuesList=[structuredClone(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(re(this.modelName))({id:e}))})}}else 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=ae(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(re(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?{pk:t.id}:this.modelQuery;return this._sendLoad(n)}delete({pk:e=null,elem:t=null}){if(null===(e=t?t.id:e))throw new Error("pk or elem must be set");const n=d();return this.isConnected().then(()=>new Promise((t,r)=>{this.socket.send(JSON.stringify({event:"model",event_type:"delete",event_id:n,args:{model_name:this.modelName,model_query:this.modelQuery,pk:e}})),this.openRequest[n]=[t,r]}))}_sendLoad(e=null){return this.isConnected().then(()=>{const t=d();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=d();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),$e.refresh(i),n&&n(e)},e=>{r&&r(e)}]}),i}_sendDetailView({pk:e=null,cbResolve:t=null,cbReject:n=null,templateContext:r={}}){e=ae(e);let s=$('<div class="container-fluid">');return this.isConnected().then(()=>{const o=d();this.socket.send(JSON.stringify({event:"model",event_type:"detail_view",event_id:o,args:{model_name:this.modelName,model_query:this.modelQuery,pk:e,template_context:r}})),this.openRequest[o]=[e=>{s.append(e.html),$e.refresh(s),t&&t(e)},e=>{n&&n(e)}]}),s}getForm({modelObj:e,eventType:t,formName:n,$divForm:r,cbResolve:s,cbReject:o,formId:i}){const l=d(),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,pk:a,form_name:n}}))});const c=null===a||-1===a?"create":"edit";this.openRequest[l]=[t=>{r.append(t.html);let o=r.closest("form").addClass(`sdc-model-${c}-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"),$e.refresh(r).then(()=>null),s&&s(t)},e=>{o&&o(e)}]}async get(e=null,t=!1){if(t){const t=e?.id??e?.pk;return 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.valuesList[0]}detailView({pk:e,cbResolve:t=null,cbReject:n=null,templateContext:r={}}){return this._sendDetailView({pk: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,formName:t="edit_form",data:n=null}={}){const r=ae(e);return this.isConnected().then(()=>{let e;if(r>-1){const t=this.byId(r);if(!t)return Promise.reject(new ie(`Element not found with ID: ${r}`));e=[t]}else e=this.valuesList;let s=[];return e.forEach(e=>{const r=d();s.push(new Promise((s,o)=>{this._readFiles(e).then(i=>{const l=n?{...n}:e.serialize();l.pk=e.id,this.socket.send(JSON.stringify({event:"model",event_type:"save",event_id:r,args:{form_name:t,model_name:this.modelName,model_query:this.modelQuery,data:l,pk:l.pk,files:i}})),this.openRequest[r]=[e=>{let t="string"==typeof e.data.instance?JSON.parse(e.data.instance):e.data.instance;e.data.instance=this._parseServerRes(t),s(e)},o]})}))}),Promise.all(s)})}create({elem:e=null,data:t=null}={}){const n=d();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]?.pk||n[0]?.id),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[oe]){const[n,r]=this.openRequest[oe];this.openRequest[oe]=[()=>{n(),e()},()=>{r(),t()}]}else this._isConnectingProcess=!0,this.openRequest[oe]=[()=>{},()=>{}],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=d();this.openRequest[o]=[e,t];const i=await s.arrayBuffer();let l=new Uint8Array(i),a=Math.ceil(l.length/se);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(se*e,se*(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 ie(t)),this._closeOpenRequest(t.event_id)),(t.msg||t.header)&&A("pushErrorMsg",t.header||"",t.msg||""),"connect"===t.type&&(this.openRequest[oe][1](new ie(t)),this._closeOpenRequest(oe),this._autoReconnect=!1,this.socket.close());else{if((t.msg||t.header)&&A("pushMsg",t.header||"",t.msg||""),"connect"===t.type)this._isConnected=!0,this._isConnectingProcess=!1,this.openRequest[oe][0](t),this._closeOpenRequest(oe);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=d();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=re(this.modelName);if(!e)throw new Error(`${this.modelName} is no SdcModel. mybe the models ar not importad.`);const r=new e({id:n.pk??n.id,...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 ue{static fields={};constructor(e){this._id=null,this._forms=[],this.loaded=!1,this.formId=d(),this.modelName=e}static querySet(e=null,t=null){return t?t.querySet(this.modeName,e):new ce(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}`](m(e.target))}_updateForm(e){const t=this;this._forms.forEach(n=>{n.find(`[name="${e}"]`).each(function(){p(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}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})}get id(){return this._id}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 ce).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 ce)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 ue?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 ue?n.id:n instanceof ce?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=ae($(this).data("model_pk"));if(t.id===e)for(let e of this.elements){let r=e.name;r&&""!==r&&n[r]&&p(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=ae($(this).data("model_pk"));if(t.id===e||null===t.id&&-1===e){for(let e of this.elements)s(e.name,m(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 ce)||e.modelName!==u))return"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(!Number.isInteger(e))return"Must be an integer";break;case"FloatField":case"DecimalField":if("number"!=typeof 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(!(le.isValid(e)||e instanceof File||e instanceof le))return"Must be a valid file"}return null}(e,t);if(n)throw new Error(n)}parseValue(e,t){const{type:n}=t;if(null===e)return null;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":if("number"!=typeof e)return"Must be a number";break;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(le.isValid(e))return new le(e);if(e instanceof le)return new le(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 de=!1,he=!1,fe=null,me={};function pe(){return window.SERVER_CALL_VIA_WEB_SOCKET?new Promise(e=>de?e():he?void setTimeout(()=>{pe().then(()=>{e()})},200):e(ye())):Promise.resolve(!0)}function _e(){window.SERVER_CALL_VIA_WEB_SOCKET&&function(){if(de){de=!1;try{fe.close()}catch(e){}}}()}function ye(){return he=!0,new Promise(e=>{fe="https:"===window.location.protocol?new WebSocket(`wss://${window.location.host}/sdc_ws/ws/`):new WebSocket(`ws://${window.location.host}/sdc_ws/ws/`),fe.onmessage=function(e){ge(JSON.parse(e.data))},fe.onclose=function(){de&&console.error("SDC Socket closed unexpectedly"),de=!1;for(const[e,t]of Object.entries(me))t[1]({}),delete me[e];setTimeout(()=>{ye()},1e3)},fe.onerror=function(e){if(console.error("Socket encountered error: ",e.message,"Closing socket"),de)try{fe.close()}catch(e){}},fe.onopen=function(){de=!0,he=!1,e()}})}function ge(e){if(e||(e={}),e.is_error)(e.msg||e.header)&&A("pushErrorMsg",e.header||"",e.msg||""),e.id&&me[e.id]&&(me[e.id][1](e.data||null),delete me[e.id]);else if((e.msg||e.header)&&A("pushMsg",e.header||"",e.msg||""),e.type&&"sdc_recall"===e.type)e.id&&me[e.id]&&(me[e.id][0](e.data),delete me[e.id]);else if(e.type&&"sdc_event"===e.type){let t=e.event;t&&A(t,e.payload)}else e.type&&"sdc_redirect"===e.type&&A("onNavLink",e.link)}class ve{constructor(){this._uuid=d(),this.contentUrl="",this.contentReload=!1,this.parsedContentUrl=null,this.events=[],this.load_async=!1,this._isEventsSet=!1,this._allEvents=null,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}_runLifecycle(e,t){$e.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(){$e.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()){M(this);const e=i(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 $e.post(this,e,t)}get(e,t){return $e.get(this,e,t)}submitForm(e,t,n){return $e.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=d();return pe().then(()=>{fe.send(JSON.stringify({event:"sdc_call",id:s,controller:t,app:e,function:n,args:r}))}),new Promise((e,t)=>{me[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 ge(t),t}).catch(e=>{const t=e.responseJSON;throw t.is_error=!0,ge(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 ce(e,t);return this._models.push(n),n}newModel(e,t={}){return console.warn("newModel is deprecated and will soon be removed"),this.querySet(e,t)}find(e){return this.$container.find(e)}refresh(){return $e.refresh(this.$container,this)}reload(){return $e.reloadController(this)}reconcile(e,t=null){return $e.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=>{h(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 we={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):(we[e.toLowerCase()]&&(e=we[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 be,$e={CSRF_TOKEN:window.CSRF_TOKEN||"",LANGUAGE_CODE:window.LANGUAGE_CODE||"en",DEBUG:window.DEBUG||!1,VERSION:window.VERSION||"0.0",tagNames:[],Global:O,rootController:null,globalRootController:null,_isInit:!1,_origin_trigger:null,_globalControllerClasses:[],init_sdc:()=>{$e._isInit||($e._isInit=!0,$e._origin_trigger?_e():($e._origin_trigger=$.fn.trigger,$.fn.trigger=function(e){const t={}.hasOwnProperty.call(e,"type")?e.type:e;return b.includes(t)||(b.push(t),$(window).on(t,N)),$e._origin_trigger.call(this,e)},$e.updateJquery()),pe(),function(){const e=$(window);b.forEach(t=>{e.off(t).on(t,N)})}(),$e.rootController=$e.rootController||new ve,$e.globalRootController=$e.globalRootController||new ve),$e.tagNames=Object.keys(S);const e=$("<div></div>");O.forEach(t=>{const n=S[t][0];e.append(`<${n.prototype._tagName}></${n.prototype._tagName}>`)});const{refreshProcess:n}=I(null,$e.rootController);return H($e.tagNames,e,$e.globalRootController,n).then(()=>H($e.tagNames,(t||(t=$("body")),t),$e.rootController,n).then(e=>(x(n),e)))},updateJquery:()=>{$.fn.safeReplace=function(e){return $e.safeReplace($(this),e)},$.fn.safeEmpty=function(){return $e.safeEmpty($(this))},$.fn.safeRemove=function(){return $e.safeRemove($(this))}},controllerToTag:e=>o(e.name).replace(/-controller$/,""),registerGlobal:e=>{$e.register(e);let t=e.prototype._tagName;O.push(t)},cleanCache:()=>{U={}},register:(e,t=!1)=>{let n=$e.controllerToTag(e);return!S[n]||t?(S[n]=[e,[]],e.prototype._tagName=n,{addMixin:(...e)=>{for(let t of e){let e;"string"==typeof t?e=o(t):t&&(e=$e.controllerToTag(t)),S[n][1].push(e)}}}):{addMixin:(...e)=>{}}},post:(e,t,n)=>(n||(n={}),n.CSRF_TOKEN=$e.CSRF_TOKEN,$e.ajax(e,t,n,$.post)),get:(e,t,n)=>$e.ajax(e,t,n,$.get),ajax:(e,t,n,r)=>{n||(n={}),n.VERSION=$e.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?A("onNavLink",t["url-link"]):s.then(()=>{$e.refresh(e.$container)})}).catch(i));return s},submitFormAndUpdateView:(e,t,n,r)=>{let s=new FormData(t);const o=e=>{e["url-link"]?A("onNavLink",e["url-link"]):window.location.href=e.url},i=new Promise((l,c)=>{a(s,n||t.action,r||t.method).then((t,n,r)=>{l(t,n,r),"redirect"===t.status?o(t):i.then(()=>{$e.refresh(e.$container,e)})}).catch((e,t,n)=>{301===e.status?(e=e.responseJSON,o(e),l(e,t,n)):c(e,t,n)})});return i},submitForm:(e,t,n)=>{let r=new FormData(e);return new Promise((s,o)=>{a(r,t||e.action,n||e.method).then(s).catch(o)})},getController:e=>G(e),safeEmpty:e=>(e.children().each(function(e,t){let n=$(t);$e.safeRemove(n)}),e),safeReplace:(e,t)=>(t.insertBefore(e),$e.safeRemove(e)),safeRemove:e=>(e.each(function(){let e=$(this);e.data(`${D}`)&&e.data(`${D}`).remove()}),e.find(`.${J}`).each(function(){const e=$(this).data(`${D}`);e&&e.remove()}),e.remove()),reloadController:e=>function(e){if(e.contentUrl){let t=W(e);return e.contentUrl=t.url,Q(e,t.args)}return new Promise(e=>{e($())})}(e).then(t=>{let n=$(t);return $e.reconcile(e,n)}),reconcile:(e,t,n=null,r=null)=>{if(!n){let n=e.$container.clone().empty();n.data(D,null),n.removeClass(J),n.append(t),t=n}n=n??e.$container;const{refreshProcess:s,isRunningProcess:o}=I(r,e);return ee(t,e,s).then(()=>{var r;return Y(t,n),(r=e)._childController={},r.find(`.${J}`).each(function(){const e=G($(this));e===r&&k(r,e)}),o||x(s),e})},refresh:(e,t=null)=>ee(e,t)},Re=[];function Ne(){if(!jest)throw new Error("JEST is not defined");0===Re.length&&(be=$.ajax.bind($),Re.push(jest.spyOn($,"ajax")),Re[0].mockImplementation(function(e){return be(e).then(e=>e).catch(e=>e)}))}const Ce=_e,Oe={get_controller:async function(e,t={},n=""){Ne();const r=$("body");$e.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);return r.append(o),$e._isInit=!1,$e.cleanCache(),await $e.init_sdc(),$e.getController(s)},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){Ne();const n=$("body");$e.updateJquery(),n.safeEmpty().append(e),$e._isInit=!1,$e.cleanCache(),await $e.init_sdc();let r=$e.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{ve as AbstractSDC,ue as SdcModel,ce as SdcQuerySet,M as allOff,$e as app,u as checkIfParamNumberBoolOrString,h as clearErrorsInForm,F as controllerFactory,q as on,ne as registerModel,P as runControlFlowFunctions,f as setErrorsInForm,T as setEvent,Ce as socketReconnect,Oe as test_utils,A as trigger};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sdc_client",
3
- "version": "0.158.2",
3
+ "version": "0.158.4",
4
4
  "description": "Simple Dom Control",
5
5
  "main": "dist/ugly.index.js",
6
6
  "type": "module",
@@ -1,7 +1,7 @@
1
- import {getValueFromField, setValueInField, uuidv4} from "./sdc_utils.js";
2
- import {getModel} from "./sdc_socket.js"
3
- import {app} from "./sdc_main.js";
4
- import {trigger} from "./sdc_events.js";
1
+ import { getValueFromField, setValueInField, uuidv4 } from "./sdc_utils.js";
2
+ import { getModel } from "./sdc_socket.js"
3
+ import { app } from "./sdc_main.js";
4
+ import { trigger } from "./sdc_events.js";
5
5
 
6
6
  const MAX_FILE_UPLOAD = 25000;
7
7
  const CONNECTING_REQUEST_ID = "_connecting_process";
@@ -24,7 +24,7 @@ class SdcModelError extends Error {
24
24
  }
25
25
 
26
26
  class FileLoaded {
27
- constructor({name, url}) {
27
+ constructor({ name, url }) {
28
28
  this.name = name;
29
29
  this.url = url;
30
30
  this.content = null;
@@ -128,9 +128,9 @@ export class SdcQuerySet {
128
128
  next: () => {
129
129
  ++idx;
130
130
  if (idx < this.valuesList.length) {
131
- return {value: this.valuesList[idx], done: false};
131
+ return { value: this.valuesList[idx], done: false };
132
132
  }
133
- return {value: null, done: true};
133
+ return { value: null, done: true };
134
134
  },
135
135
  };
136
136
  }
@@ -187,7 +187,7 @@ export class SdcQuerySet {
187
187
  this.valuesList = this.valuesList.filter((item) => numList.includes(item.id));
188
188
  const valueIds = this.getIds();
189
189
  numList.filter(x => !valueIds.includes(x)).forEach((id) => {
190
- this.valuesList.push(new (getModel(this.modelName))({id}));
190
+ this.valuesList.push(new (getModel(this.modelName))({ id }));
191
191
  });
192
192
  }
193
193
  return this.valuesList;
@@ -267,9 +267,9 @@ export class SdcQuerySet {
267
267
  * @param {?SdcModel} item
268
268
  * @returns {Promise<SdcQuerySet>}
269
269
  */
270
- update({modelQuery = null, item = null}) {
270
+ update({ modelQuery = null, item = null }) {
271
271
  this.modelQuery = modelQuery ?? this.modelQuery;
272
- let loadQuery = item ? {pk: item.id} : this.modelQuery;
272
+ let loadQuery = item ? { pk: item.id } : this.modelQuery;
273
273
  return this._sendLoad(loadQuery);
274
274
  }
275
275
 
@@ -279,7 +279,7 @@ export class SdcQuerySet {
279
279
  * @param elem {SdcModel}
280
280
  * @returns {Promise<unknown>}
281
281
  */
282
- delete({pk = null, elem = null}) {
282
+ delete({ pk = null, elem = null }) {
283
283
  pk = !elem ? pk : elem.id;
284
284
  if (pk === null) {
285
285
  throw new Error("pk or elem must be set");
@@ -326,7 +326,7 @@ export class SdcQuerySet {
326
326
  }),
327
327
  );
328
328
 
329
- this.openRequest[id] = [(data)=> {
329
+ this.openRequest[id] = [(data) => {
330
330
  this.loaded = true;
331
331
  resolve(data);
332
332
  }, reject];
@@ -454,7 +454,7 @@ export class SdcQuerySet {
454
454
  * @param {string} eventType
455
455
  * @param {SdcModel} modelObj
456
456
  */
457
- getForm({modelObj, eventType, formName, $divForm, cbResolve, cbReject, formId}) {
457
+ getForm({ modelObj, eventType, formName, $divForm, cbResolve, cbReject, formId }) {
458
458
  const id = uuidv4();
459
459
  const pk = modelObj.id ?? -1;
460
460
  this.isConnected().then(() => {
@@ -519,7 +519,7 @@ export class SdcQuerySet {
519
519
  return this.valuesList[0];
520
520
  }
521
521
 
522
- detailView({pk, cbResolve = null, cbReject = null, templateContext = {}}) {
522
+ detailView({ pk, cbResolve = null, cbReject = null, templateContext = {} }) {
523
523
  return this._sendDetailView({
524
524
  pk,
525
525
  cbResolve,
@@ -528,7 +528,7 @@ export class SdcQuerySet {
528
528
  });
529
529
  }
530
530
 
531
- listView({modelQuery = {}, searchValues = {}, cbResolve = null, cbReject = null, templateContext = {}}) {
531
+ listView({ modelQuery = {}, searchValues = {}, cbResolve = null, cbReject = null, templateContext = {} }) {
532
532
  return this._sendListView({
533
533
  modelQuery: Object.assign({}, this.modelQuery, modelQuery, { '__search_values': searchValues }),
534
534
  cbResolve,
@@ -537,7 +537,7 @@ export class SdcQuerySet {
537
537
  });
538
538
  }
539
539
 
540
- save({pk = null, formName = "edit_form", data = null} = {}) {
540
+ save({ pk = null, formName = "edit_form", data = null } = {}) {
541
541
  const normPk = normalizePk(pk);
542
542
  return this.isConnected().then(() => {
543
543
  let elemList;
@@ -556,7 +556,7 @@ export class SdcQuerySet {
556
556
  pList.push(
557
557
  new Promise((resolve, reject) => {
558
558
  this._readFiles(elem).then((files) => {
559
- const sendData = data ? {...data} : elem.serialize();
559
+ const sendData = data ? { ...data } : elem.serialize();
560
560
  sendData.pk = elem.id;
561
561
  this.socket.send(
562
562
  JSON.stringify({
@@ -600,7 +600,7 @@ export class SdcQuerySet {
600
600
  * @param data {?object}
601
601
  * @returns {Promise<unknown>}
602
602
  */
603
- create({elem = null, data = null} = {}) {
603
+ create({ elem = null, data = null } = {}) {
604
604
  const id = uuidv4();
605
605
  if (!elem) {
606
606
  elem = this.new(data);
@@ -943,10 +943,10 @@ export class SdcQuerySet {
943
943
  const newModels = []
944
944
  for (const x of results) {
945
945
  const ModelClass = getModel(this.modelName);
946
- if(!ModelClass) {
946
+ if (!ModelClass) {
947
947
  throw new Error(`${this.modelName} is no SdcModel. mybe the models ar not importad.`);
948
948
  }
949
- const newModel = new ModelClass({'id': x.pk ?? x.id, ...x.fields});
949
+ const newModel = new ModelClass({ 'id': x.pk ?? x.id, ...x.fields });
950
950
  const currentModel = this.byId(newModel.id);
951
951
  if (currentModel) {
952
952
  currentModel.setValues(newModel);
@@ -1009,7 +1009,7 @@ export default class SdcModel {
1009
1009
  }
1010
1010
 
1011
1011
  _onChange(event) {
1012
- const {name} = event.target;
1012
+ const { name } = event.target;
1013
1013
  if (this.constructor.fields[name]) {
1014
1014
  this[`set${name}`](getValueFromField(event.target));
1015
1015
  }
@@ -1039,20 +1039,20 @@ export default class SdcModel {
1039
1039
  this.loaded = isLoaded;
1040
1040
  }
1041
1041
 
1042
- save({formName = "edit_form", data = null} = {}) {
1043
- return this._querySet.deref().save({pk: this.id, formName, data});
1042
+ save({ formName = "edit_form", data = null } = {}) {
1043
+ return this._querySet.deref().save({ pk: this.id, formName, data });
1044
1044
  }
1045
1045
 
1046
- create({data = null} = {}) {
1047
- return this._querySet.deref().create({elem: this, data});
1046
+ create({ data = null } = {}) {
1047
+ return this._querySet.deref().create({ elem: this, data });
1048
1048
  }
1049
1049
 
1050
1050
  delete() {
1051
- return this._querySet.deref().delete({elem: this});
1051
+ return this._querySet.deref().delete({ elem: this });
1052
1052
  }
1053
1053
 
1054
1054
  load() {
1055
- return this._querySet.deref().update({item: this});
1055
+ return this._querySet.deref().update({ item: this });
1056
1056
  }
1057
1057
 
1058
1058
  get id() {
@@ -1083,8 +1083,8 @@ export default class SdcModel {
1083
1083
  * @param {object} options
1084
1084
  * @returns {*}
1085
1085
  */
1086
- detailView({cbResolve = null, cbReject = null, templateContext = {}}) {
1087
- return this._querySet.deref().detailView({pk: this.id, cbResolve, cbReject, templateContext});
1086
+ detailView({ cbResolve = null, cbReject = null, templateContext = {} }) {
1087
+ return this._querySet.deref().detailView({ pk: this.id, cbResolve, cbReject, templateContext });
1088
1088
  }
1089
1089
 
1090
1090
  serialize() {
@@ -1224,11 +1224,11 @@ export default class SdcModel {
1224
1224
  * @param {object} options
1225
1225
  * @returns {*}
1226
1226
  */
1227
- form({cbResolve = null, cbReject = null} = {}) {
1227
+ form({ cbResolve = null, cbReject = null } = {}) {
1228
1228
  if (this.id === null || this.id === -1) {
1229
- return this._createForm({cbReject, cbResolve});
1229
+ return this._createForm({ cbReject, cbResolve });
1230
1230
  }
1231
- return this._editForm({cbReject, cbResolve});
1231
+ return this._editForm({ cbReject, cbResolve });
1232
1232
  }
1233
1233
 
1234
1234
  /**
@@ -1237,7 +1237,7 @@ export default class SdcModel {
1237
1237
  * @param {object} options
1238
1238
  * @returns {*}
1239
1239
  */
1240
- _createForm({cbResolve = null, cbReject = null}) {
1240
+ _createForm({ cbResolve = null, cbReject = null }) {
1241
1241
  let $divForm = $("<div>");
1242
1242
  this._querySet.deref().getForm({
1243
1243
  modelObj: this,
@@ -1258,7 +1258,7 @@ export default class SdcModel {
1258
1258
  * @param {object} options
1259
1259
  * @returns {*}
1260
1260
  */
1261
- _editForm({cbResolve = null, cbReject = null}) {
1261
+ _editForm({ cbResolve = null, cbReject = null }) {
1262
1262
  let $divForm = $("<div>");
1263
1263
 
1264
1264
  this._querySet.deref().getForm({
@@ -1280,7 +1280,7 @@ export default class SdcModel {
1280
1280
  * @param {object} options
1281
1281
  * @returns {*}
1282
1282
  */
1283
- namedForm({formName, cbResolve = null, cbReject = null}) {
1283
+ namedForm({ formName, cbResolve = null, cbReject = null }) {
1284
1284
  let $divForm = $('<div class="container-fluid">');
1285
1285
 
1286
1286
  this._querySet.deref().getForm({
@@ -1318,6 +1318,9 @@ export default class SdcModel {
1318
1318
  const {
1319
1319
  type
1320
1320
  } = config;
1321
+ if (value === null) {
1322
+ return null;
1323
+ }
1321
1324
 
1322
1325
  switch (type) {
1323
1326
  case "CharField":
@@ -356,7 +356,7 @@ export function setValueInField(formItem, value) {
356
356
  if (name && name !== "") {
357
357
 
358
358
  if (type === "checkbox") {
359
- formItem.checked = value;
359
+ formItem.checked = !!value;
360
360
  } else if (type === "file") {
361
361
  if (value instanceof File) {
362
362
  if (typeof DataTransfer !== "undefined") {
@@ -370,6 +370,9 @@ export function setValueInField(formItem, value) {
370
370
  } else if (value instanceof SdcQuerySet) {
371
371
  $(formItem).val(`[${value.getIds().join(',')}]`);
372
372
  } else {
373
+ if (value === null) {
374
+ value = "";
375
+ }
373
376
  $(formItem).val(value);
374
377
  }
375
378
  }