forked from lekoala/data-grid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data-grid.min.js
40 lines (40 loc) · 38 KB
/
data-grid.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var At=Object.defineProperty;var nt=Object.getOwnPropertySymbols;var Ct=Object.prototype.hasOwnProperty,Pt=Object.prototype.propertyIsEnumerable;var ot=(r,t,e)=>t in r?At(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,lt=(r,t)=>{for(var e in t||(t={}))Ct.call(t,e)&&ot(r,e,t[e]);if(nt)for(var e of nt(t))Pt.call(t,e)&&ot(r,e,t[e]);return r};function T(r){return r.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,(t,e)=>e.toUpperCase())}function $(r){if(r==="true")return!0;if(r==="false")return!1;if(r===""||r==="null")return null;if(r===Number(r).toString())return Number(r);if(r&&(r.indexOf("[")===0||r.indexOf("{")===0))try{return r.indexOf('"')===-1&&(r=r.replace(/'/g,'"')),JSON.parse(decodeURIComponent(r))}catch(t){return console.log("Failed to parse "+r),{}}return r}var Et=["scroll","wheel","touchstart","touchmove","touchenter","touchend","touchleave","mouseout","mouseleave","mouseup","mousedown","mousemove","mouseenter","mousewheel","mouseover"];function dt(r){return Et.includes(r)?{passive:!0}:{}}function E(r,t){return r.getAttribute(t)}function N(r,t){return r.hasAttribute(t)}function p(r,t,e,i=!1){i&&N(r,t)||r.setAttribute(t,""+e)}function L(r,t){N(r,t)&&r.removeAttribute(t)}function A(r,t,e){r.addEventListener(t,e,dt(t))}function z(r,t,e){r.removeEventListener(t,e,dt(t))}function x(r,t,e={},i=!1){let s={};i&&(s.bubbles=!0),e&&(s.detail=e),r.dispatchEvent(new CustomEvent(t,s))}function B(r,t){return r.classList.contains(t)}function q(r,t){r.classList.add(t)}function V(r,t){r.classList.remove(t)}function wt(r,t=document){return r instanceof HTMLElement?r:t.querySelector(r)}function K(r,t=document){return Array.from(t.querySelectorAll(r))}function C(r,t){return wt(t,r)}function w(r,t){return K(t,r)}function k(r){return r instanceof HTMLElement?r:new HTMLElement}function ht(r){return r instanceof HTMLElement?r:new HTMLElement}var X=class extends HTMLElement{constructor(t={}){super(),this.options=Object.assign(this.defaultOptions,this.normalizedDataset,t),this.log("constructor"),this.fireEvents=!0,this._ready(),this.log("ready")}get defaultOptions(){return{}}getOption(t){return this.options[t]}setOption(t,e){p(this,`data-${t}`,e)}toggleOption(t){p(this,`data-${t}`,!this.getOption(t))}get normalizedDataset(){let t=lt({},this.dataset);for(var e in t)t[e]=$(t[e]);return t}static template(){return""}_ready(){}log(t){this.options.debug&&console.log("["+E(this,"id")+"] "+t)}handleEvent(t){this[`on${t.type}`]&&this[`on${t.type}`](t)}_connected(){}connectedCallback(){setTimeout(()=>{this.log("connectedCallback");let t=document.createElement("template");t.innerHTML=this.constructor.template(),this.appendChild(t.content.cloneNode(!0)),this._connected(),x(this,"connected")},0)}_disconnected(){}disconnectedCallback(){this.log("disconnectedCallback"),this._disconnected(),x(this,"disconnected")}get transformAttributes(){return{}}attributeChangedCallback(t,e,i){var a;if(e===i)return;this.log("attributeChangedCallback: "+t);let s=!1,o=(a=this.transformAttributes[t])!=null?a:$;t.indexOf("data-")===0&&(t=t.slice(5),s=!0),t=T(t),s?this.options[t]=o(i):this[t]=o(i),this.fireEvents&&this[`${t}Changed`]&&this[`${t}Changed`]()}},ct=X;function G(r,t,e,i=!1){let s=document.createElement("option");s.value=""+t,i&&(s.selected=!0),s.label=e,r.appendChild(s)}function Y(r,t={}){Object.keys(t).forEach(e=>{Array.isArray(t[e])?Object.keys(t[e]).forEach(i=>r.searchParams.append(isNaN(i)?`${e}[${i}]`:e,t[e][i])):r.searchParams.append(e,t[e])})}function j(r){return typeof r=="string"?r[0]==="["?(r.indexOf('"')===-1&&(r=r.replace(/'/g,'"')),JSON.parse(r)):r.split(","):Array.isArray(r)?r:(console.error("Invalid array",r),[])}function W(r){var t=r.getBoundingClientRect(),e=window.pageXOffset||document.documentElement.scrollLeft,i=window.pageYOffset||document.documentElement.scrollTop;return{top:t.top+i,left:t.left+e}}function D(r,t=document.body,e=!1){t||(t=document.createElement("div"));let i=window.getComputedStyle(t),s=i.getPropertyValue("font-weight")||"normal",o=i.getPropertyValue("font-size")||"1rem",a=i.getPropertyValue("font-family")||"Arial",d=0;if(e){let h=i.getPropertyValue("padding-left")||"0",m=i.getPropertyValue("padding-right")||"0";d=parseInt(h)+parseInt(m)}let n=(D.canvas||(D.canvas=document.createElement("canvas"))).getContext("2d");n.font=`${s} ${o} ${a}`;let u=n.measureText(r);return parseInt(u.width)+d}function J(r,t){return r.replace(/\{([^}]+)?\}/g,function(e,i){return t[i]})}function O(r){return Math.random().toString(36).replace("0.",r||"")}var c={},v={itemsPerPage:"Items per page",gotoPage:"Go to page",gotoFirstPage:"Go to first page",gotoPrevPage:"Go to previous page",gotoNextPage:"Go to next page",gotoLastPage:"Go to last page",of:"of",items:"items",resizeColumn:"Resize column",noData:"No data",areYouSure:"Are you sure?"},H=class extends ct{_ready(){var t,e,i;p(this,"id",(t=this.options.id)!=null?t:O("el-"),!0),this.data=[],this.originalData=[],this.options=this.options||this.defaultOptions,this.fireEvents=!1,this.defaultHeight=0,this.page=this.options.defaultPage||1,this.pages=0,this.meta={};for(let s of H.observedAttributes)s.indexOf("data-")===0&&p(this,s,this.options[T(s.slice(5))]);this.columns=(e=this.columns)!=null?e:null,this.actions=(i=this.actions)!=null?i:null,this.selectAll=null,this.toggleSelectAll=null,this.touch=null,this.touchstart=null,this.touchmove=null,this.isResizing=!1}static template(){return`
<table role="grid" >
<thead role="rowgroup">
<tr role="row" aria-rowindex="1" class="dg-head-columns"><th><!-- keep for getTextWidth --></th></tr>
<tr role="row" aria-rowindex="2" class="dg-head-filters"></tr>
</thead>
<tbody role="rowgroup" data-empty="${v.noData}"></tbody>
<tfoot role="rowgroup" hidden>
<tr role="row" aria-rowindex="1">
<td role="gridcell">
<div class="dg-footer">
<div class="dg-page-nav">
<select class="dg-select-per-page" aria-label="${v.itemsPerPage}"></select>
</div>
<div class="dg-pagination">
<button type="button" class="dg-btn-first dg-rotate" title="${v.gotoFirstPage}" aria-label="${v.gotoFirstPage}" disabled>
<i class="dg-skip-icon"></i>
</button>
<button type="button" class="dg-btn-prev dg-rotate" title="${v.gotoPrevPage}" aria-label="${v.gotoPrevPage}" disabled>
<i class="dg-nav-icon"></i>
</button>
<input type="number" class="dg-input-page" min="1" step="1" value="1" aria-label="${v.gotoPage}">
<button type="button" class="dg-btn-next" title="${v.gotoNextPage}" aria-label="${v.gotoNextPage}" disabled>
<i class="dg-nav-icon"></i>
</button>
<button type="button" class="dg-btn-last" title="${v.gotoLastPage}" aria-label="${v.gotoLastPage}" disabled>
<i class="dg-skip-icon"></i>
</button>
</div>
<div class="dg-meta">
<span class="dg-low">0</span> - <span class="dg-high">0</span> ${v.of} <span class="dg-total">0</span> ${v.items}
</div>
</div>
</td>
</tr>
</tfoot>
<ul class="dg-menu" hidden></ul>
</table>
`}static setLabels(t){v=Object.assign(v,t)}get defaultColumn(){return{field:"",title:"",width:0,class:"",attr:"",hidden:!1,editable:!1,noSort:!1,responsive:1}}get defaultOptions(){return{id:null,url:null,perPage:10,debug:!1,filter:!1,menu:!1,sort:!1,server:!1,serverParams:{start:"start",length:"length",search:"search",sort:"sort",sortDir:"sortDir",dataKey:"data",errorKey:"error",metaKey:"meta",metaTotalKey:"total",metaFilteredKey:"filtered",optionsKey:"options",paramsKey:"params"},defaultSort:"",reorder:!1,dir:"ltr",perPageValues:[10,25,50,100,250],columns:[],actions:[],collapseActions:!1,selectable:!1,selectVisibleOnly:!0,defaultPage:1,resizable:!1,autosize:!0,expand:!1,autoheight:!0,responsive:!1}}static registerPlugins(t){c=t}static unregisterPlugins(){c={}}static plugins(){return c}static applyColumnDefinition(t,e){e.width&&t.setAttribute("width",e.width),e.class&&t.setAttribute("class",e.class)}convertColumns(t){let e=[];return typeof t=="object"&&!Array.isArray(t)?Object.keys(t).forEach(i=>{let s=this.defaultColumn;s.title=t[i],s.field=i,e.push(s)}):t.forEach(i=>{let s=this.defaultColumn;typeof i=="string"?(s.title=i,s.field=i):typeof i=="object"?(s=i,s.field||console.error("Invalid column definition",i)):console.error("Column definition must be a string or an object"),e.push(s)}),e}static get observedAttributes(){return["page","data-filter","data-sort","data-debug","data-reorder","data-menu","data-selectable","data-url","data-per-page","data-responsive"]}get transformAttributes(){return{columns:t=>this.convertColumns(j(t)),actions:t=>j(t),defaultPage:t=>parseInt(t),perPage:t=>parseInt(t)}}get page(){return parseInt(this.getAttribute("page"))}set page(t){p(this,"page",this.constrainPageValue(t))}urlChanged(){this.loadData().then(()=>{this.configureUi()})}constrainPageValue(t){return this.pages<t&&(t=this.pages),(t<1||!t)&&(t=1),t}fixPage(){this.pages=this.totalPages(),this.page=this.constrainPageValue(this.page),this.inputPage.setAttribute("max",""+this.pages),this.inputPage.value=""+this.page,this.inputPage.disabled=this.pages===1}pageChanged(){this.reload()}responsiveChanged(){!c.ResponsiveGrid||(this.options.responsive?c.ResponsiveGrid.observe(this):c.ResponsiveGrid.unobserve(this))}menuChanged(){this.renderHeader()}changePerPage(){this.options.perPage=parseInt(this.selectPerPage.options[this.selectPerPage.selectedIndex].value),this.perPageChanged()}perPageChanged(){this.options.perPage!==parseInt(this.selectPerPage.options[this.selectPerPage.selectedIndex].value)&&this.perPageValuesChanged();let t=this.page;for(;t>1&&this.page*this.options.perPage>this.totalRecords();)t--;t!=this.page?this.page=t:this.reload(()=>{this.hasAttribute("sticky")&&window.scroll({top:W(this.selectPerPage).top-this.defaultHeight})})}dirChanged(){this.setAttribute("dir",this.options.dir)}defaultSortChanged(){this.sortChanged()}perPageValuesChanged(){if(!!this.selectPerPage){for(;this.selectPerPage.lastChild;)this.selectPerPage.removeChild(this.selectPerPage.lastChild);this.options.perPageValues.forEach(t=>{G(this.selectPerPage,t,t,t===this.options.perPage)})}}_connected(){this.table=C(this,"table"),this.btnFirst=C(this,".dg-btn-first"),this.btnPrev=C(this,".dg-btn-prev"),this.btnNext=C(this,".dg-btn-next"),this.btnLast=C(this,".dg-btn-last"),this.selectPerPage=C(this,".dg-select-per-page"),this.inputPage=C(this,".dg-input-page"),this.getFirst=this.getFirst.bind(this),this.getPrev=this.getPrev.bind(this),this.getNext=this.getNext.bind(this),this.getLast=this.getLast.bind(this),this.changePerPage=this.changePerPage.bind(this),this.gotoPage=this.gotoPage.bind(this),this.btnFirst.addEventListener("click",this.getFirst),this.btnPrev.addEventListener("click",this.getPrev),this.btnNext.addEventListener("click",this.getNext),this.btnLast.addEventListener("click",this.getLast),this.selectPerPage.addEventListener("change",this.changePerPage),this.inputPage.addEventListener("input",this.gotoPage);for(let t in c)c[t].connected(this);this.dirChanged(),this.perPageValuesChanged(),this.loadData().finally(()=>{this.configureUi(),this.sortChanged(),this.filterChanged(),this.reorderChanged(),this.dirChanged(),this.perPageValuesChanged(),this.pageChanged(),this.classList.add("dg-initialized"),this.fireEvents=!0,this.log("initialized")})}_disconnected(){this.btnFirst.removeEventListener("click",this.getFirst),this.btnPrev.removeEventListener("click",this.getPrev),this.btnNext.removeEventListener("click",this.getNext),this.btnLast.removeEventListener("click",this.getLast),this.selectPerPage.removeEventListener("change",this.changePerPage),this.inputPage.removeEventListener("input",this.gotoPage);for(let t in c)c[t].disconnected(this)}getCol(t){let e=null;return this.options.columns.forEach(i=>{i.field==t&&(e=i)}),e}getColProp(t,e){let i=this.getCol(t);return i?i[e]:null}setColProp(t,e,i){let s=this.getCol(t);s&&(s[e]=i)}visibleColumns(){return this.options.columns.filter(t=>!t.hidden)}hiddenColumns(){return this.options.columns.filter(t=>t.hidden===!0)}showColumn(t,e=!0){this.setColProp(t,"hidden",!1),e&&this.renderTable(),x(this,"columnVisibility",{col:t,visibility:"visible"})}hideColumn(t,e=!0){this.setColProp(t,"hidden",!0),e&&this.renderTable(),x(this,"columnVisibility",{col:t,visibility:"hidden"})}startColIndex(){return this.options.selectable&&c.SelectableRows?2:1}hasActions(){return this.options.actions.length>0}get actionClass(){return this.options.actions.length<3&&!this.options.collapseActions?"dg-actions-"+this.options.actions.length:"dg-actions-more"}columnsLength(t=!1){let e=0;return this.options.columns.forEach(i=>{t&&i.hidden||i.attr||e++}),this.options.selectable&&c.SelectableRows&&e++,this.options.actions.length&&e++,e}configureUi(){if(this.querySelector("table").setAttribute("aria-rowcount",this.data.length),this.table.style.visibility="hidden",this.renderTable(),this.options.responsive&&c.ResponsiveGrid||(this.table.style.visibility="visible"),!this.rowHeight){let t=this.querySelector("tbody tr")||this.querySelector("table tr");t instanceof HTMLTableRowElement&&(this.rowHeight=t.offsetHeight)}}filterChanged(){let t=this.querySelector("thead tr.dg-head-filters");this.options.filter?t.removeAttribute("hidden"):(this.clearFilters(),t.setAttribute("hidden",""))}reorderChanged(){this.querySelectorAll("thead tr.dg-head-columns th").forEach(t=>{t.classList.contains("dg-selectable")||t.classList.contains("dg-actions")||t instanceof HTMLTableRowElement&&(this.options.reorder&&c.DraggableHeaders?t.draggable=!0:t.removeAttribute("draggable"))})}sortChanged(){this.log("toggle sort"),this.querySelectorAll("thead tr.dg-head-columns th").forEach(t=>{let e=t.getAttribute("field");t.classList.contains("dg-not-sortable")||!this.fireEvents&&e==this.options.defaultSort||(this.options.sort&&!this.getColProp(e,"noSort")?t.setAttribute("aria-sort","none"):t.removeAttribute("aria-sort"))})}selectableChanged(){this.renderTable()}addRow(t){this.log("Add row"),this.originalData.push(t),this.data=this.originalData.slice(),this.sortData()}removeRow(t=null,e=null){e===null&&(e=this.options.columns[0].field),t===null&&(t=this.originalData[this.originalData.length-1][e]),this.log("Removing "+e+":"+t);for(let i=0;i<this.originalData.length;i++)if(this.originalData[i][e]===t){this.originalData.splice(i,1);break}this.data=this.originalData.slice(),this.sortData()}getSelection(t=null){return c.SelectableRows?c.SelectableRows.getSelection(this,t):[]}getData(){return this.originalData}clearData(){this.data.length!==0&&(this.data=this.originalData=[],this.renderBody(),c.FixedHeight&&c.FixedHeight.computeDefaultHeight(this))}refresh(t=null){return this.data=this.originalData=[],this.reload(t)}reload(t=null){this.log("reload");let e=this.originalData.length===0;this.fixPage(),this.loadData().finally(()=>{this.options.server||e?this.renderBody():this.paginate(),t&&t()})}loadData(){return this.originalData.length&&(!this.options.server||this.options.server&&!this.fireEvents)?(this.log("skip loadData"),new Promise(t=>{t()})):(this.log("loadData"),this.loading=!0,this.classList.add("dg-loading"),this.fetchData().then(t=>{var e,i;if(this.classList.remove("dg-loading"),this.loading=!1,Array.isArray(t))this.data=t;else{if(t[this.options.serverParams.errorKey]){this.querySelector("tbody").setAttribute("data-empty",t[this.options.serverParams.errorKey].replace(/^\s+|\r\n|\n|\r$/g,"")),this.removeAttribute("data-url");return}if(!t[this.options.serverParams.dataKey]){console.error("Invalid response, it should contain a data key with an array or be a plain array",t),this.options.url=null;return}this.options=Object.assign(this.options,(e=t[this.options.serverParams.optionsKey])!=null?e:{}),this.meta=(i=t[this.options.serverParams.metaKey])!=null?i:{},this.data=t[this.options.serverParams.dataKey]}this.originalData=this.data.slice(),this.fixPage(),this.options.columns.length===0&&this.originalData.length&&(this.options.columns=this.convertColumns(Object.keys(this.originalData[0])))}).catch(t=>{this.log(t)}))}getFirst(){this.loading||(this.page=1)}getLast(){this.loading||(this.page=this.pages)}getPrev(){this.loading||(this.page=this.page-1)}getNext(){this.loading||(this.page=this.page+1)}gotoPage(t){if(t.type==="keypress"){let e=t.keyCode||t.key;if(e===13||e==="Enter")t.preventDefault();else return}this.page=parseInt(this.inputPage.value)}getSort(){let t=this.querySelector("thead tr.dg-head-columns th[aria-sort$='scending']");return t?t.getAttribute("field"):this.options.defaultSort}getSortDir(){let t=this.querySelector("thead tr.dg-head-columns th[aria-sort$='scending']");return t&&t.getAttribute("aria-sort")||""}getFilters(){let t=[];return this.querySelectorAll("thead tr.dg-head-filters input").forEach(e=>{e instanceof HTMLInputElement&&(t[e.dataset.name]=e.value)}),t}clearFilters(){this.querySelectorAll("thead tr.dg-head-filters input").forEach(t=>{t instanceof HTMLInputElement&&(t.value="")}),this.filterData()}filterData(){if(this.log("filter data"),this.page=1,this.options.server)this.reload();else{this.data=this.originalData.slice(),this.querySelectorAll("thead tr.dg-head-filters input").forEach(e=>{if(!(e instanceof HTMLInputElement))return;let i=e.value;if(i){let s=e.dataset.name;this.data=this.data.filter(o=>(o[s]+"").toLowerCase().indexOf(i.toLowerCase())!==-1)}}),this.pageChanged();let t=this.querySelector("thead tr.dg-head-columns th[aria-sort$='scending']");this.options.sort&&t?this.sortData():this.renderBody()}}sortData(t=null){if(this.log("sort data"),t&&this.getColProp(t.getAttribute("field"),"noSort")){this.log("sorting prevented because column is not sortable");return}if(this.loading){this.log("sorting prevented because loading");return}if(t!==null?(this.querySelectorAll("thead tr:first-child th").forEach(e=>{e.classList.contains("dg-selectable")||e.classList.contains("dg-actions")||e!==t&&e.setAttribute("aria-sort","none")}),!t.hasAttribute("aria-sort")||t.getAttribute("aria-sort")==="none"?t.setAttribute("aria-sort","ascending"):t.getAttribute("aria-sort")==="ascending"?t.setAttribute("aria-sort","descending"):t.getAttribute("aria-sort")==="descending"&&t.setAttribute("aria-sort","none")):t=this.querySelector("thead tr.dg-head-columns th[aria-sort$='scending']"),this.options.server)this.loadData().finally(()=>{this.renderBody()});else{let e=t?t.getAttribute("aria-sort"):"none";if(e==="none"){let i=[];this.originalData.some(s=>(this.data.some(o=>JSON.stringify(s)===JSON.stringify(o)?(i.push(o),!0):!1),i.length===this.data.length)),this.data=i}else{let i=t.getAttribute("field");this.data.sort((s,o)=>{if(!isNaN(s[i])&&!isNaN(o[i]))return e==="ascending"?s[i]-o[i]:o[i]-s[i];let a=e==="ascending"?s[i].toUpperCase():o[i].toUpperCase(),d=e==="ascending"?o[i].toUpperCase():s[i].toUpperCase();switch(!0){case a>d:return 1;case a<d:return-1;case a===d:return 0}})}this.renderBody()}}fetchData(){if(!this.options.url)return new Promise((i,s)=>s("No url set"));let t=new URL(this.options.url,window.location.href),e={r:Date.now()};return this.options.server&&(e[this.options.serverParams.start]=this.page-1,e[this.options.serverParams.length]=this.options.perPage,e[this.options.serverParams.search]=this.getFilters(),e[this.options.serverParams.sort]=this.getSort()||"",e[this.options.serverParams.sortDir]=this.getSortDir(),this.meta[this.options.serverParams.paramsKey]&&(e=Object.assign(e,this.meta[this.options.serverParams.paramsKey]))),Y(t,e),fetch(t).then(i=>{if(!i.ok)throw new Error(i.statusText);return i.json()}).catch(i=>({error:i.message}))}renderTable(){this.log("render table"),this.options.menu&&c.ContextMenu&&c.ContextMenu.createMenu(this);let t;this.renderHeader(),this.options.defaultSort&&(t=this.querySelector("thead tr.dg-head-columns th[field='"+this.options.defaultSort+"']")),t?this.sortData(t):this.renderBody(),this.renderFooter()}renderHeader(){this.log("render header");let t=this.querySelector("thead");this.createColumnHeaders(t),this.createColumnFilters(t),this.options.resizable&&c.ColumnResizer&&c.ColumnResizer.renderResizer(this,v.resizeColumn),this.dispatchEvent(new CustomEvent("headerRendered"))}renderFooter(){this.log("render footer");let t=this.querySelector("tfoot"),e=t.querySelector("td");t.removeAttribute("hidden"),p(e,"colspan",this.columnsLength(!0)),t.style.display=""}createColumnHeaders(t){let i=this.clientWidth,s=Math.round(i/this.columnsLength(!0)*2),o=0,a;a=document.createElement("tr"),this.headerRow=a,a.setAttribute("role","row"),a.setAttribute("aria-rowindex","1"),a.setAttribute("class","dg-head-columns"),this.options.selectable&&c.SelectableRows&&c.SelectableRows.createHeaderCol(this,a);let d=t.querySelector("tr.dg-head-columns th");d||(d=document.createElement("th"),t.querySelector("tr").appendChild(d)),o=0;let l=0;if(this.options.columns.forEach(n=>{if(n.attr)return;let u=o+this.startColIndex(),h=document.createElement("th");h.setAttribute("scope","col"),h.setAttribute("role","columnheader button"),h.setAttribute("aria-colindex",""+u),h.setAttribute("id",O("dg-col-")),this.options.sort&&h.setAttribute("aria-sort","none"),h.setAttribute("field",n.field),c.ResponsiveGrid&&p(h,"data-responsive",n.responsive);let m=D(n.title,d,!0)+20;h.dataset.minWidth=""+m,H.applyColumnDefinition(h,n),h.tabIndex=0,h.textContent=n.title;let f=0;if(this.options.autosize&&c.AutosizeColumn){let g=Math.min(i-l,s);f=c.AutosizeColumn.autosizeColumn(this,h,n,parseInt(h.dataset.minWidth),g)}else f=Math.max(parseInt(h.dataset.minWidth),parseInt(h.getAttribute("width")));p(h,"width",f),n.hidden?h.setAttribute("hidden",""):l+=f,this.options.reorder&&c.DraggableHeaders&&c.DraggableHeaders.makeHeaderDraggable(this,h),a.appendChild(h),o++}),l<=i){let n=w(a,"th:not([hidden])");if(n.length){let u=n[n.length-1];L(u,"width")}}if(this.options.actions.length){let n=document.createElement("th");p(n,"role","columnheader button"),p(n,"aria-colindex",this.columnsLength(!0)),n.classList.add("dg-actions","dg-not-sortable","dg-not-resizable",this.actionClass),n.tabIndex=0,a.appendChild(n)}if(t.replaceChild(a,t.querySelector("tr.dg-head-columns")),t.offsetWidth>i){this.log("adjust width to fix size");let n=t.offsetWidth-i-8;this.options.responsive&&c.ResponsiveGrid&&(n+=8),a.querySelectorAll("th[width]").forEach(u=>{if(B(u,"dg-not-resizable")||n<=0)return;let h=k(u),m=parseInt(h.getAttribute("width")),f=h.dataset.minWidth?parseInt(h.dataset.minWidth):0;if(m>f){let g=m-n;g<f&&(g=f),n-=m-g,p(u,"width",g)}})}this.options.menu&&c.ContextMenu&&c.ContextMenu.attachContextMenu(this),a.querySelectorAll("[aria-sort]").forEach(n=>{n.addEventListener("click",()=>this.sortData(n))}),p(this.querySelector("table"),"aria-colcount",this.columnsLength(!0))}createColumnFilters(t){let e=0,i;if(i=document.createElement("tr"),this.filterRow=i,i.setAttribute("role","row"),i.setAttribute("aria-rowindex","2"),i.setAttribute("class","dg-head-filters"),this.options.filter||i.setAttribute("hidden",""),this.options.selectable&&c.SelectableRows&&c.SelectableRows.createFilterCol(this,i),this.options.columns.forEach(s=>{if(s.attr)return;let o=e+this.startColIndex(),a=t.querySelector("tr.dg-head-columns th[aria-colindex='"+o+"']");if(!a){console.warn("Related th not found",o);return}let d=document.createElement("th");d.setAttribute("aria-colindex",""+o);let l=document.createElement("input");l.type="text",l.autocomplete="off",l.spellcheck=!1,l.dataset.name=s.field,l.id=O("dg-filter-"),l.setAttribute("aria-labelledby",a.getAttribute("id")),this.options.filter?l.tabIndex=0:d.tabIndex=0,s.hidden&&d.setAttribute("hidden",""),d.appendChild(l),i.appendChild(d),e++}),this.options.actions.length){let s=document.createElement("th");s.setAttribute("role","columnheader button"),s.setAttribute("aria-colindex",""+this.columnsLength(!0)),s.classList.add("dg-actions",this.actionClass),s.tabIndex=0,i.appendChild(s)}t.replaceChild(i,t.querySelector("tr.dg-head-filters")),i.querySelectorAll("input").forEach(s=>{s.addEventListener("keypress",o=>{let a=o.keyCode||o.key;(a===13||a==="Enter")&&this.filterData.call(this)})})}renderBody(){this.log("render body");let t,e,i,s=document.createElement("tbody");this.data.forEach((a,d)=>{if(t=document.createElement("tr"),t.setAttribute("role","row"),t.setAttribute("hidden",""),t.setAttribute("aria-rowindex",d+1),t.tabIndex=0,this.options.selectable&&c.SelectableRows&&c.SelectableRows.createDataCol(this,t),this.options.expand&&(t.classList.add("dg-expandable"),t.addEventListener("click",function(){this.classList.toggle("dg-expanded")})),i=0,this.options.columns.forEach(l=>{if(l||console.log(this.options.columns),l.attr){t.setAttribute(l.attr,a[l.field]);return}if(e=document.createElement("td"),e.setAttribute("role","gridcell"),e.setAttribute("aria-colindex",i+this.startColIndex()),H.applyColumnDefinition(e,l),e.setAttribute("data-name",l.title),e.tabIndex=-1,l.editable){let n=document.createElement("input");n.type="text",n.autocomplete="off",n.spellcheck=!1,n.tabIndex=0,n.classList.add("dg-editable"),n.name=this.getAttribute("id").replace("-","_")+"["+(d+1)+"]["+l.field+"]",n.value=a[l.field],n.dataset.field=l.field,n.addEventListener("click",u=>u.stopPropagation()),n.addEventListener("keypress",u=>{if(u.type==="keypress"){let h=u.keyCode||u.key;(h===13||h==="Enter")&&n.blur()}}),n.addEventListener("blur",()=>{n.value!=a[n.dataset.field]&&(a[n.dataset.field]=n.value,x(this,"edit",{data:a,value:n.value}))}),e.appendChild(n)}else e.textContent=a[l.field];l.hidden&&p(e,"hidden",""),t.appendChild(e),i++}),this.options.actions.length){e=document.createElement("td"),p(e,"role","gridcell"),p(e,"aria-colindex",this.columnsLength(!0)),e.classList.add("dg-actions",this.actionClass),e.tabIndex=0;let l=document.createElement("button");l.classList.add("dg-actions-toggle"),l.innerHTML="\u2630",e.appendChild(l),l.addEventListener("click",n=>{n.target instanceof HTMLElement&&n.target.parentElement.classList.toggle("dg-actions-expand")}),this.options.actions.forEach(n=>{var m;let u=document.createElement("button");n.html?u.innerHTML=n.html:u.innerText=(m=n.title)!=null?m:n.name,n.title&&(u.title=n.title),n.url&&(u.type="submit",u.formAction=J(n.url,a)),n.class&&u.classList.add(...n.class.split(" "));let h=f=>{if(f.stopPropagation(),n.confirm&&!confirm(v.areYouSure)){f.preventDefault();return}x(this,"action",{data:a,action:n.name})};u.addEventListener("click",h),e.appendChild(u),n.default&&(t.classList.add("dg-actionable"),t.addEventListener("click",h))}),t.appendChild(e)}s.appendChild(t)}),s.setAttribute("role","rowgroup");let o=this.querySelector("tbody");s.setAttribute("data-empty",o.getAttribute("data-empty")),this.querySelector("table").replaceChild(s,o),c.FixedHeight&&c.FixedHeight.createFakeRow(this),this.paginate(),c.SelectableRows&&c.SelectableRows.shouldSelectAll(this,s),this.dispatchEvent(new CustomEvent("bodyRendered"))}paginate(){this.log("paginate");let t=this.totalRecords(),e=this.page||1,i,s=e*this.options.perPage,o=s-this.options.perPage+1,a=this.querySelector("tbody"),d=this.querySelector("tfoot");s>t&&(s=t),t||(o=0),a.querySelectorAll("tr").forEach(l=>{if(this.options.server){l.removeAttribute("hidden");return}i=Number(l.getAttribute("aria-rowindex")),i>s||i<o?p(l,"hidden",""):l.removeAttribute("hidden")}),this.options.selectable&&c.SelectableRows&&c.SelectableRows.clearCheckboxes(this,a),c.FixedHeight&&(this.defaultHeight==0&&c.FixedHeight.computeDefaultHeight(this),c.FixedHeight.updateFakeRow(this)),this.btnFirst&&(this.btnFirst.disabled=this.page<=1,this.btnPrev.disabled=this.page<=1,this.btnNext.disabled=this.page>=this.pages,this.btnLast.disabled=this.page>=this.pages),d.querySelector(".dg-low").textContent=o.toString(),d.querySelector(".dg-high").textContent=s.toString(),d.querySelector(".dg-total").textContent=this.totalRecords()}totalPages(){return Math.ceil(this.totalRecords()/this.options.perPage)}totalRecords(){return this.options.server?this.meta[this.options.serverParams.metaFilteredKey]||0:this.data.length}},U=H;var _=class{static get pluginName(){return this.name}static connected(t){}static disconnected(t){}},y=_;var Z=class extends y{static get pluginName(){return"ColumnResizer"}static connected(t){t.isResizing=!1}static renderResizer(t,e){let i=t.table,s=K("thead tr.dg-head-columns th",t);s.forEach(o=>{if(B(o,"dg-not-resizable"))return;let a=document.createElement("div");q(a,"dg-resizer"),a.ariaLabel=e,o.appendChild(a);let d=0,l=0,n=0,u=0,h=f=>{if(f.clientX>u)return;let g=l+(f.clientX-d);o.dataset.minWidth&&g>parseInt(o.dataset.minWidth)&&p(o,"width",g)},m=()=>{t.log("resized column"),t.isResizing=!1,V(a,"dg-resizer-active"),t.options.reorder&&(o.draggable=!0),o.style.overflow="hidden",z(document,"mousemove",h),z(document,"mouseup",m),x(t,"columnResized",{col:E(o,"field"),width:E(o,"width")})};A(a,"click",f=>{f.stopPropagation()}),A(a,"mousedown",f=>{f.stopPropagation(),t.isResizing=!0;let g=k(f.target),b=K(".dg-head-columns th",t),P=Array.from(b).filter(S=>!S.hasAttribute("hidden")),at=Array.from(P).findIndex(S=>S==g.parentNode);t.log("resize column"),q(a,"dg-resizer-active"),L(o,"draggable"),o.style.overflow="visible",a.style.height=i.offsetHeight-1+"px",d=f.clientX,l=o.offsetWidth,n=(P.length-at)*30,u=W(g).left+t.offsetWidth-n,p(o,"width",l);for(let S=0;S<P.length;S++)S>at&&L(s[S],"width");A(document,"mousemove",h),A(document,"mouseup",m)})})}},ut=Z;function M(r,t,e="nodeName"){let i=r;for(;i[e]!=t;)i=i.parentElement;return i}var F=class extends y{static get pluginName(){return"ContextMenu"}static disconnected(t){t.headerRow&&(t.headerRow.oncontextmenu=null)}static attachContextMenu(t){A(t.headerRow,"contextmenu",e=>{F.showContextMenu(t,e)})}static showContextMenu(t,e){e.preventDefault();let i=M(e.target,"THEAD"),s=C(t,".dg-menu"),o=i.getBoundingClientRect(),a=e.clientX-o.left,d=e.clientY-o.top;s.style.top=`${d}px`,s.style.left=`${a}px`,L(s,"hidden"),a+150>o.width&&(a-=s.offsetWidth,s.style.left=`${a}px`);let l=n=>{s.contains(n.target)||(p(s,"hidden",""),z(document,"click",l))};A(document,"click",l)}static createMenu(t){let e=C(t,".dg-menu");for(;e.lastChild;)e.removeChild(e.lastChild);t.options.columns.forEach(i=>{if(i.attr)return;let s=i.field,o=document.createElement("li"),a=document.createElement("label"),d=document.createElement("input");p(d,"type","checkbox"),p(d,"data-name",i.field),i.hidden||(d.checked=!0),A(d,"change",n=>{let u=ht(n.target);if(u.checked)t.showColumn(s);else{if(t.visibleColumns().length<=1){u.checked=!0;return}t.hideColumn(s)}});let l=document.createTextNode(i.title);a.appendChild(d),a.appendChild(l),o.appendChild(a),e.appendChild(o)})}},ft=F;var Q=class extends y{static get pluginName(){return"DraggableHeaders"}static makeHeaderDraggable(t,e){e.draggable=!0,A(e,"dragstart",i=>{if(t.isResizing&&i.preventDefault){i.preventDefault();return}i.target instanceof HTMLElement&&(t.log("reorder col"),i.dataTransfer.effectAllowed="move",i.dataTransfer.setData("text/plain",i.target.getAttribute("aria-colindex")))}),A(e,"dragover",i=>(i.preventDefault&&i.preventDefault(),i.dataTransfer.dropEffect="move",!1)),A(e,"drop",i=>{i.stopPropagation&&i.stopPropagation();let s=k(i.target),o=M(s,"TH"),a=parseInt(i.dataTransfer.getData("text/plain")),d=parseInt(o.getAttribute("aria-colindex"));if(a===d){t.log("reordered col stayed the same");return}t.log("reordered col from "+a+" to "+d);let l=t.startColIndex(),n=t.options.columns[a-l];t.options.columns[a-l]=t.options.columns[d-l],t.options.columns[d-l]=n;let u=(h,m)=>{let f=m.parentNode.getAttribute("aria-rowindex"),g=t.querySelector(h+" tr[aria-rowindex='"+f+"'] [aria-colindex='"+d+"']");p(m,"aria-colindex",d),p(g,"aria-colindex",a);let b=document.createElement("th");m.parentNode.insertBefore(b,m),g.parentNode.replaceChild(m,g),b.parentNode.replaceChild(g,b)};return w(t,"thead th[aria-colindex='"+a+"']").forEach(h=>{u("thead",h)}),w(t,'tbody td[aria-colindex="'+a+'"]').forEach(h=>{u("tbody",h)}),t.options.columns=w(t,"thead tr.dg-head-columns th[field]").map(h=>t.options.columns.find(m=>m.field==E(h,"field"))),x(t,"columnReordered",{col:n.field,from:a,to:d}),!1})}},pt=Q;var I=class extends y{static get pluginName(){return"TouchSupport"}static connected(t){t.touch=null,t.touchstart=I.touchstart.bind(t),t.touchmove=I.touchmove.bind(t),t.addEventListener("touchstart",t.touchstart,{passive:!0}),t.addEventListener("touchmove",t.touchmove,{passive:!0})}static disconnected(t){t.removeEventListener("touchstart",t.touchstart),t.removeEventListener("touchmove",t.touchmove)}static touchstart(t){this.touch=t.touches[0]}static touchmove(t){if(!this.touch)return;let e=this.touch.clientX-t.touches[0].clientX,i=this.touch.clientY-t.touches[0].clientY;Math.abs(e)>Math.abs(i)&&(e>0?this.getNext():this.getPrev()),this.touch=null}},gt=I;var tt=class extends y{static get pluginName(){return"SelectableRows"}static disconnected(t){t.selectAll&&t.selectAll.removeEventListener("change",t.toggleSelectAll)}static getSelection(t,e=null){let i=[];return Array.from(t.querySelectorAll("tbody .dg-selectable input:checked")).forEach(s=>{if(!(s instanceof HTMLElement))return;let o=parseInt(s.dataset.id),a=t.data[o-1];a||console.warn(`Item ${o} not found`),e?i.push(a[e]):i.push(a)}),i}static clearCheckboxes(t,e){!t.options.selectVisibleOnly||e.querySelectorAll("tr[hidden] .dg-selectable input").forEach(i=>{i instanceof HTMLInputElement&&(i.checked=!1)})}static createHeaderCol(t,e){let i=document.createElement("th");i.setAttribute("scope","col"),i.setAttribute("role","columnheader button"),i.setAttribute("aria-colindex","1"),i.classList.add("dg-selectable","dg-not-resizable","dg-not-sortable"),i.tabIndex=0,t.selectAll=document.createElement("input"),t.selectAll.type="checkbox",t.selectAll.classList.add("dg-select-all"),t.toggleSelectAll=this.toggleSelectAll.bind(t),t.selectAll.addEventListener("change",t.toggleSelectAll);let s=document.createElement("label");s.appendChild(t.selectAll),i.appendChild(s),i.setAttribute("width","40"),e.appendChild(i)}static createFilterCol(t,e){let i=document.createElement("th");i.setAttribute("role","columnheader button"),i.setAttribute("aria-colindex","1"),i.classList.add("dg-selectable"),i.tabIndex=0;let s=document.createElement("label");i.appendChild(s),e.appendChild(i)}static shouldSelectAll(t,e){!t.selectAll||(e.addEventListener("change",i=>{if(i.target instanceof HTMLInputElement){if(!i.target.closest(".dg-selectable"))return;let s=t.querySelectorAll("tbody .dg-selectable input[type=checkbox]"),o=Array.from(s).filter(a=>a.checked);t.selectAll.checked=o.length==s.length,x(t,"rowsSelected",{selection:t.getSelection()})}}),e.dispatchEvent(new Event("change")))}static createDataCol(t,e){let i=document.createElement("td");i.setAttribute("role","gridcell button"),i.setAttribute("aria-colindex","1"),i.classList.add("dg-selectable");let s=document.createElement("input");s.dataset.id=e.getAttribute("aria-rowindex"),s.type="checkbox";let o=document.createElement("label");o.appendChild(s),i.appendChild(o),e.appendChild(i)}static toggleSelectAll(){let t=this.options.selectVisibleOnly;this.querySelectorAll("tbody .dg-selectable input").forEach(e=>{e instanceof HTMLInputElement&&(t&&!e.offsetWidth||(e.checked=this.selectAll.checked))}),x(this,"rowsSelected",{selection:this.getSelection()})}},mt=tt;var et=class extends y{static get pluginName(){return"FixedHeight"}static computeDefaultHeight(t){requestAnimationFrame(()=>{t.defaultHeight=t.querySelector("table").offsetHeight,t.style.height&&(t.style.overflowY="auto"),t.options.autoheight&&(t.style.height&&(t.style.height=t.defaultHeight+"px"),t.style.minHeight&&parseInt(t.style.minHeight)>t.defaultHeight&&(t.style.minHeight=t.defaultHeight+"px"))})}static createFakeRow(t){let e=t.querySelector("tbody"),i=document.createElement("tr");p(i,"role","row"),p(i,"hidden",""),i.classList.add("dg-fake-row"),i.tabIndex=0,e.appendChild(i)}static updateFakeRow(t){if(!t.style.height)return;let e=t.querySelector(".dg-fake-row");if(!!e)if(parseInt(t.style.height)>t.querySelector("tbody").offsetHeight){let i=t.options.perPage*t.rowHeight,s=t.querySelectorAll("tbody tr:not([hidden])").length,o=s>1?i-s*t.rowHeight:i;p(e,"height",o),e.removeAttribute("hidden")}else e.removeAttribute("height")}},bt=et;var it=class extends y{static get pluginName(){return"AutosizeColumn"}static autosizeColumn(t,e,i,s,o){if(N(e,"width"))return E(e,"width");if(!t.data.length)return;let a=t.data[0][i.field].toString(),d=t.data[t.data.length-1][i.field].toString();d.length>a.length&&(a=d);let l=0;return a.length<=6?l=s:a.length>50?l=o:l=D(a+"0000",e),l<s&&(l=s),p(e,"width",l),l}},vt=it;function st(r,t=300){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>{r.apply(this,i)},t)}}function St(r){return Array.from(r).sort(function(t,e){return t=parseInt(t.dataset.responsive)||1,e=parseInt(e.dataset.responsive)||1,t===e&&e++,e-t})}var Lt=st(r=>{for(let t of r){let e=t.target,i=e.table,s=Array.isArray(t.contentBoxSize)?t.contentBoxSize[0]:t.contentBoxSize,o=parseInt(s.inlineSize),a=i.offsetWidth,l=(w(e.headerRow,"th").reduce((f,g)=>f+g.offsetWidth,0)||a)-o-1,n=50,u=St(w(e.headerRow,"th[field]").reverse().filter(f=>f.dataset.responsive!=="0")),h=!1;if(l>0){let f=l,g=u.filter(b=>!b.hasAttribute("hidden")&&b.hasAttribute("data-responsive"));if(g.length===0&&(g=u.filter(b=>!b.hasAttribute("hidden")),g.length===1))return;g.forEach(b=>{if(f<0)return;let P=b.offsetWidth,R=b.getAttribute("field");!R||(b.dataset.baseWidth=b.offsetWidth,e.hideColumn(R,!1),h=!0,f-=P,f=Math.round(f))})}else{let f=u.filter(b=>!b.hasAttribute("hidden")).reduce((b,P)=>b+parseInt(P.dataset.minWidth),0)+n,g=o-f;u.slice().reverse().filter(b=>b.hasAttribute("hidden")).forEach(b=>{if(g<n)return;let P=parseInt(b.dataset.minWidth);if(o<P+f){g=-1;return}let R=b.getAttribute("field");!R||(e.showColumn(R,!1),h=!0,g-=P,g=Math.round(g))})}let m=e.table.querySelector("tfoot");m.offsetWidth>o?q(m,"dg-footer-compact"):m.offsetWidth<o+200&&V(m,"dg-footer-compact"),h&&e.renderTable(),e.table.style.visibility="visible"}},100),yt=new ResizeObserver(Lt),rt=class extends y{static get pluginName(){return"ResponsiveGrid"}static connected(t){t.options.responsive&&this.observe(t)}static disconnected(t){this.unobserve(t)}static observe(t){!t.options.responsive||(yt.observe(t),t.style.display="block",t.style.overflowX="hidden")}static unobserve(t){yt.unobserve(t),t.style.display="unset",t.style.overflowX="unset"}},xt=rt;U.registerPlugins({ColumnResizer:ut,ContextMenu:ft,DraggableHeaders:pt,TouchSupport:gt,SelectableRows:mt,FixedHeight:bt,AutosizeColumn:vt,ResponsiveGrid:xt});customElements.define("data-grid",U);var $e=U;export{$e as default};
//# sourceMappingURL=data-grid.min.js.map