diff --git a/resources/js/laravel-livewire-tables.js b/resources/js/laravel-livewire-tables.js index 2c214e492..6177ea37f 100644 --- a/resources/js/laravel-livewire-tables.js +++ b/resources/js/laravel-livewire-tables.js @@ -2,7 +2,10 @@ document.addEventListener('alpine:init', () => { - Alpine.data('laravellivewiretable', (wire, showBulkActionsAlpine, tableID, primaryKeyName) => ({ + Alpine.data('laravellivewiretable', (wire) => ({ + tableId: '', + showBulkActionsAlpine: false, + primaryKeyName: '', shouldBeDisplayed: wire.entangle('shouldBeDisplayed'), tableName: wire.entangle('tableName'), dataTableFingerprint: wire.entangle('dataTableFingerprint'), @@ -70,7 +73,7 @@ document.addEventListener('alpine:init', () => { element.classList.remove("laravel-livewire-table-dragging"); let originalPosition = element.rowIndex; let newPosition = target.rowIndex; - let table = document.getElementById(tableID); + let table = document.getElementById(this.tableId); let loopStart = originalPosition; if (event.offsetY > (target.getBoundingClientRect().height / 2)) { parent.insertBefore(element, target.nextSibling); @@ -126,17 +129,17 @@ document.addEventListener('alpine:init', () => { }, updateOrderedItems() { - let table = document.getElementById(tableID); + let table = document.getElementById(this.tableId); let orderedRows = []; for (let i = 1, row; row = table.rows[i]; i++) { - orderedRows.push({ [primaryKeyName]: row.getAttribute('rowpk'), [this.defaultReorderColumn]: i }); + orderedRows.push({ [this.primaryKeyName]: row.getAttribute('rowpk'), [this.defaultReorderColumn]: i }); } wire.storeReorder(orderedRows); }, setupEvenOddClasses() { if (this.evenNotInOdd.length === undefined || this.evenNotInOdd.length == 0 || this.oddNotInEven.length === undefined || this.oddNotInEven.length == 0) { - let tbody = document.getElementById(tableID).getElementsByTagName('tbody')[0]; + let tbody = document.getElementById(this.tableId).getElementsByTagName('tbody')[0]; let evenRowClassArray = []; let oddRowClassArray = []; @@ -152,7 +155,7 @@ document.addEventListener('alpine:init', () => { } }, toggleSelectAll() { - if (!showBulkActionsAlpine) { + if (!this.showBulkActionsAlpine) { return; } @@ -171,14 +174,14 @@ document.addEventListener('alpine:init', () => { } }, setAllItemsSelected() { - if (!showBulkActionsAlpine) { + if (!this.showBulkActionsAlpine) { return; } this.selectAllStatus = true; this.selectAllOnPage(); }, setAllSelected() { - if (!showBulkActionsAlpine) { + if (!this.showBulkActionsAlpine) { return; } if (this.delaySelectAll) @@ -192,14 +195,14 @@ document.addEventListener('alpine:init', () => { } }, clearSelected() { - if (!showBulkActionsAlpine) { + if (!this.showBulkActionsAlpine) { return; } this.selectAllStatus = false; wire.clearSelected(); }, selectAllOnPage() { - if (!showBulkActionsAlpine) { + if (!this.showBulkActionsAlpine) { return; } @@ -210,14 +213,32 @@ document.addEventListener('alpine:init', () => { } this.selectedItems = [...new Set(tempSelectedItems)]; }, - showTable(eventTableName = '', eventTableFingerpint = '') + setTableId(tableId) { - if ((eventTableName != '' && eventTableName === this.tableName) || (eventTableFingerprint != '' && eventTableFingerpint === this.dataTableFingerprint)) { + this.tableId = tableId; + }, + setAlpineBulkActions(showBulkActionsAlpine) + { + this.showBulkActionsAlpine = showBulkActionsAlpine; + }, + setPrimaryKeyName(primaryKeyName) + { + this.primaryKeyName = primaryKeyName; + }, + showTable(event) + { + let eventTableName = event.detail.tableName ?? ''; + let eventTableFingerprint = event.detail.tableFingerpint ?? ''; + + if (((eventTableName ?? '') != '' && eventTableName === this.tableName) || (eventTableFingerprint != '' && eventTableFingerpint === this.dataTableFingerprint)) { this.shouldBeDisplayed = true; } }, - hideTable(eventTableName = '', eventTableFingerpint = '') + hideTable(event) { + let eventTableName = event.detail.tableName ?? ''; + let eventTableFingerprint = event.detail.tableFingerpint ?? ''; + if ((eventTableName != '' && eventTableName === this.tableName) || (eventTableFingerprint != '' && eventTableFingerpint === this.dataTableFingerprint)) { this.shouldBeDisplayed = false; } diff --git a/resources/js/laravel-livewire-tables.min.js b/resources/js/laravel-livewire-tables.min.js index 5ab2c9730..a4fb93695 100644 --- a/resources/js/laravel-livewire-tables.min.js +++ b/resources/js/laravel-livewire-tables.min.js @@ -1 +1 @@ -document.addEventListener("alpine:init",()=>{Alpine.data("laravellivewiretable",(e,t,l,i)=>({shouldBeDisplayed:e.entangle("shouldBeDisplayed"),tableName:e.entangle("tableName"),dataTableFingerprint:e.entangle("dataTableFingerprint"),listeners:[],childElementOpen:!1,filtersOpen:e.entangle("filterSlideDownDefaultVisible"),paginationCurrentCount:e.entangle("paginationCurrentCount"),paginationTotalItemCount:e.entangle("paginationTotalItemCount"),paginationCurrentItems:e.entangle("paginationCurrentItems"),selectedItems:e.entangle("selected"),selectAllStatus:e.entangle("selectAll"),delaySelectAll:e.entangle("delaySelectAll"),hideBulkActionsWhenEmpty:e.entangle("hideBulkActionsWhenEmpty"),dragging:!1,reorderEnabled:!1,sourceID:"",targetID:"",evenRowClasses:"",oddRowClasses:"",currentlyHighlightedElement:"",evenRowClassArray:{},oddRowClassArray:{},evenNotInOdd:{},oddNotInEven:{},orderedRows:[],defaultReorderColumn:e.get("defaultReorderColumn"),reorderStatus:e.entangle("reorderStatus"),currentlyReorderingStatus:e.entangle("currentlyReorderingStatus"),hideReorderColumnUnlessReorderingStatus:e.entangle("hideReorderColumnUnlessReorderingStatus"),reorderDisplayColumn:e.entangle("reorderDisplayColumn"),dragStart(e){this.$nextTick(()=>{this.setupEvenOddClasses()}),this.sourceID=e.target.id,e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",e.target.id),e.target.classList.add("laravel-livewire-tables-dragging")},dragOverEvent(e){"object"==typeof this.currentlyHighlightedElement&&this.currentlyHighlightedElement.classList.remove("laravel-livewire-tables-highlight-bottom","laravel-livewire-tables-highlight-top");let t=e.target.closest("tr");this.currentlyHighlightedElement=t,e.offsetYt.getBoundingClientRect().height/2?i.insertBefore(s,t.nextSibling):i.insertBefore(s,t),r{this.setupEvenOddClasses()})},cancelReorder(){this.hideReorderColumnUnlessReorderingStatus&&(this.reorderDisplayColumn=!1),e.disableReordering()},updateOrderedItems(){let t=document.getElementById(l),s=[];for(let a=1,r;r=t.rows[a];a++)s.push({[i]:r.getAttribute("rowpk"),[this.defaultReorderColumn]:a});e.storeReorder(s)},setupEvenOddClasses(){if(void 0===this.evenNotInOdd.length||0==this.evenNotInOdd.length||void 0===this.oddNotInEven.length||0==this.oddNotInEven.length){let e=document.getElementById(l).getElementsByTagName("tbody")[0],t=[],i=[];void 0!==e.rows[0]&&void 0!==e.rows[1]&&(t=Array.from(e.rows[0].classList),i=Array.from(e.rows[1].classList),this.evenNotInOdd=t.filter(e=>!i.includes(e)),this.oddNotInEven=i.filter(e=>!t.includes(e)),t=[],i=[])}},toggleSelectAll(){t&&(this.paginationTotalItemCount===this.selectedItems.length?(this.clearSelected(),this.selectAllStatus=!1):this.delaySelectAll?this.setAllItemsSelected():this.setAllSelected())},setAllItemsSelected(){t&&(this.selectAllStatus=!0,this.selectAllOnPage())},setAllSelected(){t&&(this.delaySelectAll?(this.selectAllStatus=!0,this.selectAllOnPage()):e.setAllSelected())},clearSelected(){t&&(this.selectAllStatus=!1,e.clearSelected())},selectAllOnPage(){if(!t)return;let e=this.selectedItems,l=this.paginationCurrentItems.values();for(let i of l)e.push(i.toString());this.selectedItems=[...new Set(e)]},showTable(e="",t=""){(""!=e&&e===this.tableName||""!=eventTableFingerprint&&t===this.dataTableFingerprint)&&(this.shouldBeDisplayed=!0)},hideTable(e="",t=""){(""!=e&&e===this.tableName||""!=eventTableFingerprint&&t===this.dataTableFingerprint)&&(this.shouldBeDisplayed=!1)},destroy(){this.listeners.forEach(e=>{e()})}})),Alpine.data("booleanFilter",(e,t,l,i)=>({switchOn:!1,value:e.entangle("filterComponents."+t).live,init(){this.switchOn=!1,void 0!==this.value&&(this.switchOn=Boolean(Number(this.value))),this.listeners.push(Livewire.on("filter-was-set",e=>{e.tableName==l&&e.filterKey==t&&(this.switchOn=e.value??i)}))}})),Alpine.data("numberRangeFilter",(e,t,l,i,s)=>({allFilters:e.entangle("filterComponents",!1),originalMin:0,originalMax:100,filterMin:0,filterMax:100,currentMin:0,currentMax:100,hasUpdate:!1,wireValues:e.entangle("filterComponents."+t,!1),defaultMin:i.minRange,defaultMax:i.maxRange,restrictUpdates:!1,initialiseStyles(){let e=document.getElementById(l);e.style.setProperty("--value-a",this.wireValues.min??this.filterMin),e.style.setProperty("--text-value-a",JSON.stringify(this.wireValues.min??this.filterMin)),e.style.setProperty("--value-b",this.wireValues.max??this.filterMax),e.style.setProperty("--text-value-b",JSON.stringify(this.wireValues.max??this.filterMax))},updateStyles(e,t){let i=document.getElementById(l);i.style.setProperty("--value-a",e),i.style.setProperty("--text-value-a",JSON.stringify(e)),i.style.setProperty("--value-b",t),i.style.setProperty("--text-value-b",JSON.stringify(t))},setupWire(){void 0!==this.wireValues?(this.filterMin=this.originalMin=void 0!==this.wireValues.min?this.wireValues.min:this.defaultMin,this.filterMax=this.originalMax=void 0!==this.wireValues.max?this.wireValues.max:this.defaultMax):(this.filterMin=this.originalMin=this.defaultMin,this.filterMax=this.originalMax=this.defaultMax),this.updateStyles(this.filterMin,this.filterMax)},allowUpdates(){this.updateWire()},updateWire(){let e=parseInt(this.filterMin),t=parseInt(this.filterMax);(e!=this.originalMin||t!=this.originalMax)&&(tthis.setupWire())}})),Alpine.data("flatpickrFilter",(e,t,l,i,s)=>({wireValues:e.entangle("filterComponents."+t),flatpickrInstance:flatpickr(i,{mode:"range",altFormat:l.altFormat??"F j, Y",altInput:l.altInput??!1,allowInput:l.allowInput??!1,allowInvalidPreload:l.allowInvalidPreload??!0,ariaDateFormat:l.ariaDateFormat??"F j, Y",clickOpens:!0,dateFormat:l.dateFormat??"Y-m-d",defaultDate:l.defaultDate??null,defaultHour:l.defaultHour??12,defaultMinute:l.defaultMinute??0,enableTime:l.enableTime??!1,enableSeconds:l.enableSeconds??!1,hourIncrement:l.hourIncrement??1,locale:l.locale??"en",minDate:l.earliestDate??null,maxDate:l.latestDate??null,minuteIncrement:l.minuteIncrement??5,shorthandCurrentMonth:l.shorthandCurrentMonth??!1,time_24hr:l.time_24hr??!1,weekNumbers:l.weekNumbers??!1,onOpen:function(){window.childElementOpen=!0},onChange:function(l,i,s){if(l.length>1){var a=i.split(" "),r={};window.childElementOpen=!1,window.filterPopoverOpen=!1,r={minDate:a[0],maxDate:void 0===a[2]?a[0]:a[2]},e.set("filterComponents."+t,r)}}}),changedValue:function(l){l.length<5&&(this.flatpickrInstance.setDate([]),e.set("filterComponents."+t,{}))},setupWire(){if(void 0!==this.wireValues){if(void 0!==this.wireValues.minDate&&void 0!==this.wireValues.maxDate){let e=[this.wireValues.minDate,this.wireValues.maxDate];this.flatpickrInstance.setDate(e)}else this.flatpickrInstance.setDate([])}else this.flatpickrInstance.setDate([])},init(){this.setupWire(),this.$watch("wireValues",e=>this.setupWire())}})),Alpine.data("tableWrapper",(e,t)=>({shouldBeDisplayed:e.entangle("shouldBeDisplayed"),listeners:[],childElementOpen:!1,filtersOpen:e.entangle("filterSlideDownDefaultVisible"),paginationCurrentCount:e.entangle("paginationCurrentCount"),paginationTotalItemCount:e.entangle("paginationTotalItemCount"),paginationCurrentItems:e.entangle("paginationCurrentItems"),selectedItems:e.entangle("selected"),selectAllStatus:e.entangle("selectAll"),delaySelectAll:e.entangle("delaySelectAll"),hideBulkActionsWhenEmpty:e.entangle("hideBulkActionsWhenEmpty"),toggleSelectAll(){t&&(this.paginationTotalItemCount===this.selectedItems.length?(this.clearSelected(),this.selectAllStatus=!1):this.delaySelectAll?this.setAllItemsSelected():this.setAllSelected())},setAllItemsSelected(){t&&(this.selectAllStatus=!0,this.selectAllOnPage())},setAllSelected(){t&&(this.delaySelectAll?(this.selectAllStatus=!0,this.selectAllOnPage()):e.setAllSelected())},clearSelected(){t&&(this.selectAllStatus=!1,e.clearSelected())},selectAllOnPage(){if(!t)return;let e=this.selectedItems,l=this.paginationCurrentItems.values();for(let i of l)e.push(i.toString());this.selectedItems=[...new Set(e)]},destroy(){this.listeners.forEach(e=>{e()})}})),Alpine.data("reorderFunction",(e,t,l)=>({dragging:!1,reorderEnabled:!1,sourceID:"",targetID:"",evenRowClasses:"",oddRowClasses:"",currentlyHighlightedElement:"",evenRowClassArray:{},oddRowClassArray:{},evenNotInOdd:{},oddNotInEven:{},orderedRows:[],defaultReorderColumn:e.get("defaultReorderColumn"),reorderStatus:e.get("reorderStatus"),currentlyReorderingStatus:e.entangle("currentlyReorderingStatus"),hideReorderColumnUnlessReorderingStatus:e.entangle("hideReorderColumnUnlessReorderingStatus"),reorderDisplayColumn:e.entangle("reorderDisplayColumn"),dragStart(e){this.$nextTick(()=>{this.setupEvenOddClasses()}),this.sourceID=e.target.id,e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",e.target.id),e.target.classList.add("laravel-livewire-tables-dragging")},dragOverEvent(e){"object"==typeof this.currentlyHighlightedElement&&this.currentlyHighlightedElement.classList.remove("laravel-livewire-tables-highlight-bottom","laravel-livewire-tables-highlight-top");let t=e.target.closest("tr");this.currentlyHighlightedElement=t,e.offsetYl.getBoundingClientRect().height/2?i.insertBefore(s,l.nextSibling):i.insertBefore(s,l),r{this.setupEvenOddClasses()}),this.currentlyReorderingStatus?e.disableReordering():(this.setupEvenOddClasses(),this.hideReorderColumnUnlessReorderingStatus&&(this.reorderDisplayColumn=!0),e.enableReordering())},cancelReorder(){this.hideReorderColumnUnlessReorderingStatus&&(this.reorderDisplayColumn=!1),e.disableReordering()},updateOrderedItems(){let i=document.getElementById(t),s=[];for(let a=1,r;r=i.rows[a];a++)s.push({[l]:r.getAttribute("rowpk"),[this.defaultReorderColumn]:a});e.storeReorder(s)},setupEvenOddClasses(){if(void 0===this.evenNotInOdd.length||0==this.evenNotInOdd.length||void 0===this.oddNotInEven.length||0==this.oddNotInEven.length){let e=document.getElementById(t).getElementsByTagName("tbody")[0],l=[],i=[];void 0!==e.rows[0]&&void 0!==e.rows[1]&&(l=Array.from(e.rows[0].classList),i=Array.from(e.rows[1].classList),this.evenNotInOdd=l.filter(e=>!i.includes(e)),this.oddNotInEven=i.filter(e=>!l.includes(e)),l=[],i=[])}},init(){}}))}); \ No newline at end of file +document.addEventListener("alpine:init",()=>{Alpine.data("laravellivewiretable",e=>({tableId:"",showBulkActionsAlpine:!1,primaryKeyName:"",shouldBeDisplayed:e.entangle("shouldBeDisplayed"),tableName:e.entangle("tableName"),dataTableFingerprint:e.entangle("dataTableFingerprint"),listeners:[],childElementOpen:!1,filtersOpen:e.entangle("filterSlideDownDefaultVisible"),paginationCurrentCount:e.entangle("paginationCurrentCount"),paginationTotalItemCount:e.entangle("paginationTotalItemCount"),paginationCurrentItems:e.entangle("paginationCurrentItems"),selectedItems:e.entangle("selected"),selectAllStatus:e.entangle("selectAll"),delaySelectAll:e.entangle("delaySelectAll"),hideBulkActionsWhenEmpty:e.entangle("hideBulkActionsWhenEmpty"),dragging:!1,reorderEnabled:!1,sourceID:"",targetID:"",evenRowClasses:"",oddRowClasses:"",currentlyHighlightedElement:"",evenRowClassArray:{},oddRowClassArray:{},evenNotInOdd:{},oddNotInEven:{},orderedRows:[],defaultReorderColumn:e.get("defaultReorderColumn"),reorderStatus:e.entangle("reorderStatus"),currentlyReorderingStatus:e.entangle("currentlyReorderingStatus"),hideReorderColumnUnlessReorderingStatus:e.entangle("hideReorderColumnUnlessReorderingStatus"),reorderDisplayColumn:e.entangle("reorderDisplayColumn"),dragStart(e){this.$nextTick(()=>{this.setupEvenOddClasses()}),this.sourceID=e.target.id,e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",e.target.id),e.target.classList.add("laravel-livewire-tables-dragging")},dragOverEvent(e){"object"==typeof this.currentlyHighlightedElement&&this.currentlyHighlightedElement.classList.remove("laravel-livewire-tables-highlight-bottom","laravel-livewire-tables-highlight-top");let t=e.target.closest("tr");this.currentlyHighlightedElement=t,e.offsetYt.getBoundingClientRect().height/2?l.insertBefore(i,t.nextSibling):l.insertBefore(i,t),a{this.setupEvenOddClasses()})},cancelReorder(){this.hideReorderColumnUnlessReorderingStatus&&(this.reorderDisplayColumn=!1),e.disableReordering()},updateOrderedItems(){let t=document.getElementById(this.tableId),l=[];for(let i=1,s;s=t.rows[i];i++)l.push({[this.primaryKeyName]:s.getAttribute("rowpk"),[this.defaultReorderColumn]:i});e.storeReorder(l)},setupEvenOddClasses(){if(void 0===this.evenNotInOdd.length||0==this.evenNotInOdd.length||void 0===this.oddNotInEven.length||0==this.oddNotInEven.length){let e=document.getElementById(this.tableId).getElementsByTagName("tbody")[0],t=[],l=[];void 0!==e.rows[0]&&void 0!==e.rows[1]&&(t=Array.from(e.rows[0].classList),l=Array.from(e.rows[1].classList),this.evenNotInOdd=t.filter(e=>!l.includes(e)),this.oddNotInEven=l.filter(e=>!t.includes(e)),t=[],l=[])}},toggleSelectAll(){this.showBulkActionsAlpine&&(this.paginationTotalItemCount===this.selectedItems.length?(this.clearSelected(),this.selectAllStatus=!1):this.delaySelectAll?this.setAllItemsSelected():this.setAllSelected())},setAllItemsSelected(){this.showBulkActionsAlpine&&(this.selectAllStatus=!0,this.selectAllOnPage())},setAllSelected(){this.showBulkActionsAlpine&&(this.delaySelectAll?(this.selectAllStatus=!0,this.selectAllOnPage()):e.setAllSelected())},clearSelected(){this.showBulkActionsAlpine&&(this.selectAllStatus=!1,e.clearSelected())},selectAllOnPage(){if(!this.showBulkActionsAlpine)return;let e=this.selectedItems,t=this.paginationCurrentItems.values();for(let l of t)e.push(l.toString());this.selectedItems=[...new Set(e)]},setTableId(e){this.tableId=e},setAlpineBulkActions(e){this.showBulkActionsAlpine=e},setPrimaryKeyName(e){this.primaryKeyName=e},showTable(e){let t=e.detail.tableName??"",l=e.detail.tableFingerpint??"";((t??"")!=""&&t===this.tableName||""!=l&&eventTableFingerpint===this.dataTableFingerprint)&&(this.shouldBeDisplayed=!0)},hideTable(e){let t=e.detail.tableName??"",l=e.detail.tableFingerpint??"";(""!=t&&t===this.tableName||""!=l&&eventTableFingerpint===this.dataTableFingerprint)&&(this.shouldBeDisplayed=!1)},destroy(){this.listeners.forEach(e=>{e()})}})),Alpine.data("booleanFilter",(e,t,l,i)=>({switchOn:!1,value:e.entangle("filterComponents."+t).live,init(){this.switchOn=!1,void 0!==this.value&&(this.switchOn=Boolean(Number(this.value))),this.listeners.push(Livewire.on("filter-was-set",e=>{e.tableName==l&&e.filterKey==t&&(this.switchOn=e.value??i)}))}})),Alpine.data("numberRangeFilter",(e,t,l,i,s)=>({allFilters:e.entangle("filterComponents",!1),originalMin:0,originalMax:100,filterMin:0,filterMax:100,currentMin:0,currentMax:100,hasUpdate:!1,wireValues:e.entangle("filterComponents."+t,!1),defaultMin:i.minRange,defaultMax:i.maxRange,restrictUpdates:!1,initialiseStyles(){let e=document.getElementById(l);e.style.setProperty("--value-a",this.wireValues.min??this.filterMin),e.style.setProperty("--text-value-a",JSON.stringify(this.wireValues.min??this.filterMin)),e.style.setProperty("--value-b",this.wireValues.max??this.filterMax),e.style.setProperty("--text-value-b",JSON.stringify(this.wireValues.max??this.filterMax))},updateStyles(e,t){let i=document.getElementById(l);i.style.setProperty("--value-a",e),i.style.setProperty("--text-value-a",JSON.stringify(e)),i.style.setProperty("--value-b",t),i.style.setProperty("--text-value-b",JSON.stringify(t))},setupWire(){void 0!==this.wireValues?(this.filterMin=this.originalMin=void 0!==this.wireValues.min?this.wireValues.min:this.defaultMin,this.filterMax=this.originalMax=void 0!==this.wireValues.max?this.wireValues.max:this.defaultMax):(this.filterMin=this.originalMin=this.defaultMin,this.filterMax=this.originalMax=this.defaultMax),this.updateStyles(this.filterMin,this.filterMax)},allowUpdates(){this.updateWire()},updateWire(){let e=parseInt(this.filterMin),t=parseInt(this.filterMax);(e!=this.originalMin||t!=this.originalMax)&&(tthis.setupWire())}})),Alpine.data("flatpickrFilter",(e,t,l,i,s)=>({wireValues:e.entangle("filterComponents."+t),flatpickrInstance:flatpickr(i,{mode:"range",altFormat:l.altFormat??"F j, Y",altInput:l.altInput??!1,allowInput:l.allowInput??!1,allowInvalidPreload:l.allowInvalidPreload??!0,ariaDateFormat:l.ariaDateFormat??"F j, Y",clickOpens:!0,dateFormat:l.dateFormat??"Y-m-d",defaultDate:l.defaultDate??null,defaultHour:l.defaultHour??12,defaultMinute:l.defaultMinute??0,enableTime:l.enableTime??!1,enableSeconds:l.enableSeconds??!1,hourIncrement:l.hourIncrement??1,locale:l.locale??"en",minDate:l.earliestDate??null,maxDate:l.latestDate??null,minuteIncrement:l.minuteIncrement??5,shorthandCurrentMonth:l.shorthandCurrentMonth??!1,time_24hr:l.time_24hr??!1,weekNumbers:l.weekNumbers??!1,onOpen:function(){window.childElementOpen=!0},onChange:function(l,i,s){if(l.length>1){var a=i.split(" "),n={};window.childElementOpen=!1,window.filterPopoverOpen=!1,n={minDate:a[0],maxDate:void 0===a[2]?a[0]:a[2]},e.set("filterComponents."+t,n)}}}),changedValue:function(l){l.length<5&&(this.flatpickrInstance.setDate([]),e.set("filterComponents."+t,{}))},setupWire(){if(void 0!==this.wireValues){if(void 0!==this.wireValues.minDate&&void 0!==this.wireValues.maxDate){let e=[this.wireValues.minDate,this.wireValues.maxDate];this.flatpickrInstance.setDate(e)}else this.flatpickrInstance.setDate([])}else this.flatpickrInstance.setDate([])},init(){this.setupWire(),this.$watch("wireValues",e=>this.setupWire())}})),Alpine.data("tableWrapper",(e,t)=>({shouldBeDisplayed:e.entangle("shouldBeDisplayed"),listeners:[],childElementOpen:!1,filtersOpen:e.entangle("filterSlideDownDefaultVisible"),paginationCurrentCount:e.entangle("paginationCurrentCount"),paginationTotalItemCount:e.entangle("paginationTotalItemCount"),paginationCurrentItems:e.entangle("paginationCurrentItems"),selectedItems:e.entangle("selected"),selectAllStatus:e.entangle("selectAll"),delaySelectAll:e.entangle("delaySelectAll"),hideBulkActionsWhenEmpty:e.entangle("hideBulkActionsWhenEmpty"),toggleSelectAll(){t&&(this.paginationTotalItemCount===this.selectedItems.length?(this.clearSelected(),this.selectAllStatus=!1):this.delaySelectAll?this.setAllItemsSelected():this.setAllSelected())},setAllItemsSelected(){t&&(this.selectAllStatus=!0,this.selectAllOnPage())},setAllSelected(){t&&(this.delaySelectAll?(this.selectAllStatus=!0,this.selectAllOnPage()):e.setAllSelected())},clearSelected(){t&&(this.selectAllStatus=!1,e.clearSelected())},selectAllOnPage(){if(!t)return;let e=this.selectedItems,l=this.paginationCurrentItems.values();for(let i of l)e.push(i.toString());this.selectedItems=[...new Set(e)]},destroy(){this.listeners.forEach(e=>{e()})}})),Alpine.data("reorderFunction",(e,t,l)=>({dragging:!1,reorderEnabled:!1,sourceID:"",targetID:"",evenRowClasses:"",oddRowClasses:"",currentlyHighlightedElement:"",evenRowClassArray:{},oddRowClassArray:{},evenNotInOdd:{},oddNotInEven:{},orderedRows:[],defaultReorderColumn:e.get("defaultReorderColumn"),reorderStatus:e.get("reorderStatus"),currentlyReorderingStatus:e.entangle("currentlyReorderingStatus"),hideReorderColumnUnlessReorderingStatus:e.entangle("hideReorderColumnUnlessReorderingStatus"),reorderDisplayColumn:e.entangle("reorderDisplayColumn"),dragStart(e){this.$nextTick(()=>{this.setupEvenOddClasses()}),this.sourceID=e.target.id,e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",e.target.id),e.target.classList.add("laravel-livewire-tables-dragging")},dragOverEvent(e){"object"==typeof this.currentlyHighlightedElement&&this.currentlyHighlightedElement.classList.remove("laravel-livewire-tables-highlight-bottom","laravel-livewire-tables-highlight-top");let t=e.target.closest("tr");this.currentlyHighlightedElement=t,e.offsetYl.getBoundingClientRect().height/2?i.insertBefore(s,l.nextSibling):i.insertBefore(s,l),n{this.setupEvenOddClasses()}),this.currentlyReorderingStatus?e.disableReordering():(this.setupEvenOddClasses(),this.hideReorderColumnUnlessReorderingStatus&&(this.reorderDisplayColumn=!0),e.enableReordering())},cancelReorder(){this.hideReorderColumnUnlessReorderingStatus&&(this.reorderDisplayColumn=!1),e.disableReordering()},updateOrderedItems(){let i=document.getElementById(t),s=[];for(let a=1,n;n=i.rows[a];a++)s.push({[l]:n.getAttribute("rowpk"),[this.defaultReorderColumn]:a});e.storeReorder(s)},setupEvenOddClasses(){if(void 0===this.evenNotInOdd.length||0==this.evenNotInOdd.length||void 0===this.oddNotInEven.length||0==this.oddNotInEven.length){let e=document.getElementById(t).getElementsByTagName("tbody")[0],l=[],i=[];void 0!==e.rows[0]&&void 0!==e.rows[1]&&(l=Array.from(e.rows[0].classList),i=Array.from(e.rows[1].classList),this.evenNotInOdd=l.filter(e=>!i.includes(e)),this.oddNotInEven=i.filter(e=>!l.includes(e)),l=[],i=[])}},init(){}}))}); \ No newline at end of file diff --git a/resources/views/components/table.blade.php b/resources/views/components/table.blade.php index 0b92e6f39..4a8f14985 100644 --- a/resources/views/components/table.blade.php +++ b/resources/views/components/table.blade.php @@ -21,6 +21,7 @@ {{ $attributes->merge($customAttributes['table']) ->class(['min-w-full divide-y divide-gray-200 dark:divide-none' => $customAttributes['table']['default'] ?? true]) ->except('default') }} + > merge($customAttributes['thead']) diff --git a/resources/views/datatable.blade.php b/resources/views/datatable.blade.php index d8105236a..594272a70 100644 --- a/resources/views/datatable.blade.php +++ b/resources/views/datatable.blade.php @@ -6,7 +6,7 @@ @php($isBootstrap4 = $this->isBootstrap4) @php($isBootstrap5 = $this->isBootstrap5) -
+
getTopLevelAttributes() }}> @if($this->hasActions && !$this->showActionsInToolbar) diff --git a/src/Traits/Helpers/ComponentHelpers.php b/src/Traits/Helpers/ComponentHelpers.php index b027be813..980d8d28e 100644 --- a/src/Traits/Helpers/ComponentHelpers.php +++ b/src/Traits/Helpers/ComponentHelpers.php @@ -94,7 +94,7 @@ public function getTableName(): string #[Computed] public function getTableId(): string { - return $this->getTableAttributes()['id']; + return $this->getTableAttributes()['id'] ?? 'table-'.$this->getTableName(); } public function isTableNamed(string $name): bool diff --git a/src/Traits/Helpers/TableAttributeHelpers.php b/src/Traits/Helpers/TableAttributeHelpers.php index d5f57f03e..4d82a5393 100644 --- a/src/Traits/Helpers/TableAttributeHelpers.php +++ b/src/Traits/Helpers/TableAttributeHelpers.php @@ -3,6 +3,7 @@ namespace Rappasoft\LaravelLivewireTables\Traits\Helpers; use Illuminate\Database\Eloquent\Model; +use Illuminate\View\ComponentAttributeBag; use Livewire\Attributes\Computed; use Rappasoft\LaravelLivewireTables\Views\Column; @@ -82,4 +83,22 @@ public function getShouldBeDisplayed(): bool { return $this->shouldBeDisplayed; } + + public function getTopLevelAttributesArray(): array + { + return [ + 'x-data' => 'laravellivewiretable($wire)', + 'x-init' => "setTableId('".$this->getTableAttributes()['id']."'); setAlpineBulkActions('".$this->showBulkActionsDropdownAlpine()."'); setPrimaryKeyName('".$this->getPrimaryKey()."');", + 'x-cloak', + 'x-show' => 'shouldBeDisplayed', + 'x-on:show-table.window' => 'showTable(event)', + 'x-on:hide-table.window' => 'hideTable(event)', + ]; + } + + #[Computed] + public function getTopLevelAttributes(): ComponentAttributeBag + { + return new ComponentAttributeBag($this->getTopLevelAttributesArray()); + } } diff --git a/tests/Traits/Helpers/TableAttributeHelpersTest.php b/tests/Traits/Helpers/TableAttributeHelpersTest.php new file mode 100644 index 000000000..ec62d40c2 --- /dev/null +++ b/tests/Traits/Helpers/TableAttributeHelpersTest.php @@ -0,0 +1,29 @@ +basicTable->getTopLevelAttributesArray(); + $this->assertSame('shouldBeDisplayed', $topLevelAttributesArray['x-show']); + $this->assertSame('showTable(event)', $topLevelAttributesArray['x-on:show-table.window']); + $this->assertSame('hideTable(event)', $topLevelAttributesArray['x-on:hide-table.window']); + $this->assertSame('laravellivewiretable($wire)', $topLevelAttributesArray['x-data']); + } + + public function test_top_level_attribute_bag_matches(): void + { + $topLevelAttributeBag = $this->basicTable->getTopLevelAttributes(); + + $topLevelAttributesArray = $topLevelAttributeBag->getAttributes(); + + $this->assertSame('shouldBeDisplayed', $topLevelAttributesArray['x-show']); + $this->assertSame('showTable(event)', $topLevelAttributesArray['x-on:show-table.window']); + $this->assertSame('hideTable(event)', $topLevelAttributesArray['x-on:hide-table.window']); + $this->assertSame('laravellivewiretable($wire)', $topLevelAttributesArray['x-data']); + } +} diff --git a/tests/Traits/Visuals/SortingVisualsTest.php b/tests/Traits/Visuals/SortingVisualsTest.php index 4b2d44275..6419f2643 100644 --- a/tests/Traits/Visuals/SortingVisualsTest.php +++ b/tests/Traits/Visuals/SortingVisualsTest.php @@ -121,7 +121,6 @@ public function test_multiple_sorting_pill_shows_with_single_column_off(): void public function test_sorting_pill_shows_correct_name_and_direction(): void { Livewire::test(PetsTable::class) - ->assertDontSee('Key') ->call('sortBy', 'id') ->assertSee('Key') ->assertSee('0-9')