pagindata-js
Version:
A lightweight and modern pagination library written in vanilla JavaScript with no external dependencies
1 lines • 17.5 kB
JavaScript
(function(t){function e(t){throw new Error("Pagination: "+t)}function a(t){var e=typeof t;return("object"==e?null==t?"null":Object.prototype.toString.call(t).slice(8,-1):e).toLowerCase()}function i(t,e,a){var i=document.createElement(t);return e&&(i.className=e),a&&(i.innerHTML=a),i}function n(t,e,a){t.addEventListener?t.addEventListener(e,a):t.attachEvent&&t.attachEvent("on"+e,a)}function r(t,e,a){var i=new CustomEvent(e,{detail:a});t.dispatchEvent(i)}function o(t,e){for(var a in e)e.hasOwnProperty(a)&&(t[a]=e[a]);return t}function s(t,e){for(var a in e)e.hasOwnProperty(a)&&("object"!=typeof e[a]||null===e[a]||Array.isArray(e[a])?t[a]=e[a]:(t[a]=t[a]||{},s(t[a],e[a])));return t}function u(t,e){this.container=t,this.attributes=s({},u.defaults),o(this.attributes,e),this.model={pageRange:this.attributes.pageRange,pageSize:this.attributes.pageSize},this.disabled=!!this.attributes.disabled,this.isAsync=!1,this.isDynamicTotalNumber=!1,this.breakpoints=this.attributes.breakpoints||{},this.currentBreakpoint=null,this.resizeTimeout=null,this.initialize(),Object.keys(this.breakpoints).length>0&&this.initializeBreakpoints()}var l="__pagination-";t.PaginDataJS&&e('plugin conflicted, the name "PaginDataJS" has been taken by another plugin.');var c={};["Object","Array","String"].forEach(function(t){c["is"+t]=function(e){return a(e)===t.toLowerCase()}}),u.prototype={initialize:function(){var t=this;if(t.container.paginationData||(t.container.paginationData={}),!1!==t.callHook("beforeInit")){if(t.container.paginationData.initialized){var e=t.container.querySelector(".paginationjs");e&&e.remove()}t.parseDataSource(t.attributes.dataSource,function(e){t.isAsync=c.isString(e),c.isArray(e)&&(t.model.totalNumber=t.attributes.totalNumber=e.length),t.isDynamicTotalNumber=t.isAsync&&t.attributes.totalNumberLocator;var a=t.render(!0);t.attributes.className&&a.classList.add(t.attributes.className),t.model.el=a,"bottom"===t.attributes.position?t.container.appendChild(a):t.container.insertBefore(a,t.container.firstChild),t.observer(),t.container.paginationData.initialized=!0,t.callHook("afterInit",a)})}},render:function(t){var e=this,a=e.model,n=a.el||i("div","paginationjs"),r=!0!==t;e.callHook("beforeRender",r);var o=a.pageNumber||e.attributes.pageNumber,s=e.attributes.pageRange||0,u=e.getTotalPage(),l=o-s,c=o+s;return c>u&&(c=u,l=u-2*s,l=l<1?1:l),l<=1&&(l=1,c=Math.min(2*s+1,u)),n.innerHTML=e.generateHTML({currentPage:o,pageRange:s,rangeStart:l,rangeEnd:c}),e.attributes.hideOnlyOnePage&&(n.style.display=u<=1?"none":"block"),e.callHook("afterRender",r),n},getPageLinkTag:function(t){var e=this.attributes.pageLink;return e?`<a href="${e}">${t}</a>`:`<a>${t}</a>`},generatePageNumbersHTML:function(t){var e,a=this,i=t.currentPage,n=a.getTotalPage(),r=t.rangeStart,o=t.rangeEnd,s="",u=a.attributes.ellipsisText,l=a.attributes.classPrefix,c=a.attributes.pageClassName||"",g=a.attributes.activeClassName||"",p=a.attributes.disableClassName||"";if(null===a.attributes.pageRange){for(e=1;e<=n;e++)s+=e==i?`<li class="${l}-page J-paginationjs-page ${c} ${g}" data-num="${e}"><a>${e}</a></li>`:`<li class="${l}-page J-paginationjs-page ${c}" data-num="${e}">${a.getPageLinkTag(e)}</li>`;return s}if(r<=3)for(e=1;e<r;e++)s+=e==i?`<li class="${l}-page J-paginationjs-page ${c} ${g}" data-num="${e}"><a>${e}</a></li>`:`<li class="${l}-page J-paginationjs-page ${c}" data-num="${e}">${a.getPageLinkTag(e)}</li>`;else a.attributes.hideFirstOnEllipsisShow||(s+=`<li class="${l}-page ${l}-first J-paginationjs-page ${c}" data-num="1">${a.getPageLinkTag(1)}</li>`),s+=`<li class="${l}-ellipsis ${p}"><a>${u}</a></li>`;for(e=r;e<=o;e++)s+=e==i?`<li class="${l}-page J-paginationjs-page ${c} ${g}" data-num="${e}"><a>${e}</a></li>`:`<li class="${l}-page J-paginationjs-page ${c}" data-num="${e}">${a.getPageLinkTag(e)}</li>`;if(o>=n-2)for(e=o+1;e<=n;e++)s+=`<li class="${l}-page J-paginationjs-page ${c}" data-num="${e}">${a.getPageLinkTag(e)}</li>`;else s+=`<li class="${l}-ellipsis ${p}"><a>${u}</a></li>`,a.attributes.hideLastOnEllipsisShow||(s+=`<li class="${l}-page ${l}-last J-paginationjs-page ${c}" data-num="${n}">${a.getPageLinkTag(n)}</li>`);return s},generateHTML:function(t){var e,a=this,i=t.currentPage,n=a.getTotalPage(),r=a.getTotalNumber(),o=a.attributes.pageSize,s=a.attributes.showPrevious,u=a.attributes.showNext,l=a.attributes.showPageNumbers,g=a.attributes.showNavigator,p=a.attributes.showSizeChanger,b=a.attributes.sizeChangerOptions,f=a.attributes.showGoInput,d=a.attributes.showGoButton,m=a.attributes.prevText,h=a.attributes.nextText,v=a.attributes.goButtonText,y=a.attributes.classPrefix,k=a.attributes.disableClassName||"",N=a.attributes.ulClassName||"",$=a.attributes.prevClassName||"",P=a.attributes.nextClassName||"",S="",T='<select class="J-paginationjs-size-select">',x='<input type="text" class="J-paginationjs-go-pagenumber">',C=`<input type="button" class="J-paginationjs-go-button" value="${v}">`,j="function"==typeof a.attributes.formatSizeChanger?a.attributes.formatSizeChanger(i,n,r):a.attributes.formatSizeChanger,H="function"==typeof a.attributes.formatNavigator?a.attributes.formatNavigator(i,n,r):a.attributes.formatNavigator,L="function"==typeof a.attributes.formatGoInput?a.attributes.formatGoInput(x,i,n,r):a.attributes.formatGoInput,w="function"==typeof a.attributes.formatGoButton?a.attributes.formatGoButton(C,i,n,r):a.attributes.formatGoButton,O="function"==typeof a.attributes.autoHidePrevious?a.attributes.autoHidePrevious():a.attributes.autoHidePrevious,z="function"==typeof a.attributes.autoHideNext?a.attributes.autoHideNext():a.attributes.autoHideNext,D="function"==typeof a.attributes.header?a.attributes.header(i,n,r):a.attributes.header,E="function"==typeof a.attributes.footer?a.attributes.footer(i,n,r):a.attributes.footer;if(D&&(e=a.replaceVariables(D,{currentPage:i,totalPage:n,totalNumber:r}),S+=e),g&&H&&(e=a.replaceVariables(H,{currentPage:i,totalPage:n,totalNumber:r,rangeStart:(i-1)*o+1,rangeEnd:Math.min(i*o,r)}),S+=`<div class="${y}-nav J-paginationjs-nav">${e}</div>`),(s||l||u)&&(S+='<div class="paginationjs-pages">',S+=N?`<ul class="${N}">`:"<ul>",s&&(i<=1?O||(S+=`<li class="${y}-prev ${k} ${$}"><a>${m}</a></li>`):S+=`<li class="${y}-prev J-paginationjs-previous ${$}" data-num="${i-1}" title="Previous page">${a.getPageLinkTag(m)}</li>`),l&&(S+=a.generatePageNumbersHTML(t)),u&&(i>=n?z||(S+=`<li class="${y}-next ${k} ${P}"><a>${h}</a></li>`):S+=`<li class="${y}-next J-paginationjs-next ${P}" data-num="${i+1}" title="Next page">${a.getPageLinkTag(h)}</li>`),S+="</ul></div>"),p&&c.isArray(b)){-1===b.indexOf(o)&&(b.unshift(o),b.sort((t,e)=>t-e));for(let t=0;t<b.length;t++)T+=`<option value="${b[t]}"${b[t]===o?" selected":""}>${b[t]} / page</option>`;T+="</select>",e=T,j&&(e=a.replaceVariables(j,{length:T,total:r})),S+=`<div class="paginationjs-size-changer">${e}</div>`}return f&&L&&(e=a.replaceVariables(L,{currentPage:i,totalPage:n,totalNumber:r,input:x}),S+=`<div class="${y}-go-input">${e}</div>`),d&&w&&(e=a.replaceVariables(w,{currentPage:i,totalPage:n,totalNumber:r,button:C}),S+=`<div class="${y}-go-button">${e}</div>`),E&&(e=a.replaceVariables(E,{currentPage:i,totalPage:n,totalNumber:r}),S+=e),S},findTotalNumberFromRemoteResponse:function(t){this.model.totalNumber=this.attributes.totalNumberLocator(t)},go:function(t,e){function a(t){if(!1===i.callHook("beforePaging",r))return!1;var a;(n.direction=void 0===n.pageNumber?0:r>n.pageNumber?1:-1,n.pageNumber=r,i.render(),i.disabled&&i.isAsync&&i.enable(),i.container.paginationData.model=n,i.attributes.formatResult)&&(a=t.length>0&&t[0]instanceof Element?Array.from(t):JSON.parse(JSON.stringify(t)),c.isArray(t=i.attributes.formatResult(a))||(t=a));i.container.paginationData.currentPageData=t,i.doCallback(t,e),i.callHook("afterPaging",r),1==r?i.callHook("afterIsFirstPage"):r==i.getTotalPage()&&i.callHook("afterIsLastPage")}var i=this,n=i.model;if(!i.disabled){var r=t;if(r=parseInt(r),r&&!(r<1)){var u=i.attributes.pageSize,l=i.getTotalNumber(),g=i.getTotalPage();if(!(l>0&&r>g))if(i.isAsync){var p={},b=i.attributes.alias||{},f=b.pageSize?b.pageSize:"pageSize",d=b.pageNumber?b.pageNumber:"pageNumber";p[f]=u,p[d]=r;var m="function"==typeof i.attributes.ajax?i.attributes.ajax():i.attributes.ajax;m&&m.pageNumberStartWithZero&&(p[d]=r-1);var h={type:"get",cache:!1,data:{},contentType:"application/x-www-form-urlencoded; charset=UTF-8",dataType:"json",async:!0};if(s(h,m),o(h.data,p),h.url=i.attributes.dataSource,h.success=function(t){try{i.model.originalResponse=t,i.isDynamicTotalNumber?i.findTotalNumberFromRemoteResponse(t):i.model.totalNumber=i.attributes.totalNumber;var e=i.filterDataWithLocator(t);a(e)}catch(t){if("function"!=typeof i.attributes.onError)throw t;i.attributes.onError(t,"ajaxSuccessHandlerError")}},h.error=function(t,e,a){i.attributes.formatAjaxError&&i.attributes.formatAjaxError(t,e,a),i.enable()},i.disable(),i.attributes.ajaxFunction)i.attributes.ajaxFunction(h);else{var v=new XMLHttpRequest,y=h.url,k=h.type.toUpperCase();if("GET"===k){var N=[];for(var $ in h.data)N.push(encodeURIComponent($)+"="+encodeURIComponent(h.data[$]));N.length>0&&(y+=(-1===y.indexOf("?")?"?":"&")+N.join("&"))}if(v.open(k,y,h.async),v.setRequestHeader("Content-Type",h.contentType),v.onreadystatechange=function(){if(4===v.readyState)if(v.status>=200&&v.status<300){var t=JSON.parse(v.responseText);h.success(t)}else h.error(v,"error",v.statusText)},"POST"===k){var P=[];for(var $ in h.data)P.push(encodeURIComponent($)+"="+encodeURIComponent(h.data[$]));v.send(P.join("&"))}else v.send()}}else a(i.getPagingData(r))}}},doCallback:function(t,e){var a=this,i=a.model;"function"==typeof e?e(t,i):"function"==typeof a.attributes.callback&&a.attributes.callback(t,i)},destroy:function(){if(!1!==this.callHook("beforeDestroy")){this.resizeTimeout&&clearTimeout(this.resizeTimeout),this.model.el.remove(),this.container.paginationData={};var t=document.getElementById("paginationjs-style");t&&t.remove(),this.callHook("afterDestroy")}},previous:function(t){this.go(this.model.pageNumber-1,t)},next:function(t){this.go(this.model.pageNumber+1,t)},disable:function(){var t=this,e=t.isAsync?"async":"sync";!1!==t.callHook("beforeDisable",e)&&(t.disabled=!0,t.model.disabled=!0,t.callHook("afterDisable",e))},enable:function(){var t=this,e=t.isAsync?"async":"sync";!1!==t.callHook("beforeEnable",e)&&(t.disabled=!1,t.model.disabled=!1,t.callHook("afterEnable",e))},refresh:function(t){this.go(this.model.pageNumber,t)},show:function(){var t=this;"none"===t.model.el.style.display&&(t.model.el.style.display="block")},hide:function(){var t=this;"none"!==t.model.el.style.display&&(t.model.el.style.display="none")},replaceVariables:function(t,e){var a;for(var i in e){var n=e[i],r=new RegExp("<%=\\s*"+i+"\\s*%>","img");a=(a||t).replace(r,n)}return a},getPagingData:function(t){var e=this.attributes.pageSize,a=this.attributes.dataSource,i=this.getTotalNumber(),n=e*(t-1)+1,r=Math.min(t*e,i);return a.length>0&&(a[0],Element),a.slice(n-1,r)},getTotalNumber:function(){return this.model.totalNumber||this.attributes.totalNumber||0},getTotalPage:function(){return Math.ceil(this.getTotalNumber()/this.attributes.pageSize)},getLocator:function(t){var a;return"string"==typeof t?a=t:"function"==typeof t?a=t():e('"locator" is incorrect. Expect string or function type.'),a},filterDataWithLocator:function(t){var a,i=this.getLocator(this.attributes.locator);if(c.isObject(t)){try{for(var n=i.split("."),r=0;r<n.length;r++)a=(a||t)[n[r]]}catch(t){}a?c.isArray(a)||e("dataSource."+i+" should be an Array."):e("dataSource."+i+" is undefined.")}return a||t},parseDataSource:function(t,a){var i=this;c.isObject(t)?a(i.attributes.dataSource=i.filterDataWithLocator(t)):c.isArray(t)?a(i.attributes.dataSource=t):"function"==typeof t?t(function(t){c.isArray(t)||e('The parameter of "done" Function should be an Array.'),i.parseDataSource.call(i,t,a)}):"string"==typeof t?(/^https?|file:/.test(t)&&(i.attributes.ajaxDataType="jsonp"),a(t)):e("Unexpected dataSource type")},callHook:function(e){var a,i=this.container.paginationData||{},n=Array.prototype.slice.apply(arguments);return n.shift(),this.attributes[e]&&"function"==typeof this.attributes[e]&&!1===this.attributes[e].apply(t,n)&&(a=!1),i.hooks&&i.hooks[e]&&i.hooks[e].forEach(function(e){!1===e.apply(t,n)&&(a=!1)}),!1!==a},initializeBreakpoints:function(){var t=this,e=t.getCurrentBreakpointConfig();t.applyBreakpointConfig(e),n(window,"resize",function(){t.handleResize()})},getCurrentBreakpointConfig:function(){for(var t=this,e=window.innerWidth,a=Object.keys(t.breakpoints).map(Number).sort(function(t,e){return e-t}),i=0;i<a.length;i++){var n=a[i];if(e>=n){var r={breakpoint:n,config:t.breakpoints[n]};return r}}return null},applyBreakpointConfig:function(t){var e=this;if(t){var a=t.config,i=t.breakpoint;if(e.currentBreakpoint!==i){for(var n in e.currentBreakpoint=i,a)a.hasOwnProperty(n)&&(e.attributes[n]=a[n],"pageSize"===n?e.model.pageSize=a[n]:"pageRange"===n&&(e.model.pageRange=a[n]));if(e.render(),"function"==typeof e.attributes.callback){var r=e.getPagingData(e.model.pageNumber||e.attributes.pageNumber);e.attributes.callback(r,e.model)}}}},handleResize:function(){var t=this,e=t.getCurrentBreakpointConfig();e&&e.breakpoint!==t.currentBreakpoint&&t.applyBreakpointConfig(e)},observer:function(){var t=this,a=t.model.el;n(t.container,l+"go",function(a){var i=a.detail;"string"==typeof i&&(i=parseInt(i.trim())),i&&("number"!=typeof i&&e('"pageNumber" is incorrect. (Number)'),t.go(i))}),n(a,"click",function(e){var a=e.target.closest(".J-paginationjs-page");if(a){var i=a.getAttribute("data-num");if(i&&(i=i.trim()),i&&!a.classList.contains(t.attributes.disableClassName)&&!a.classList.contains(t.attributes.activeClassName))return!1!==t.callHook("beforePageOnClick",e,i)&&(t.go(i),t.callHook("afterPageOnClick",e,i),t.attributes.pageLink?void 0:(e.preventDefault(),!1))}}),n(a,"click",function(e){var a=e.target.closest(".J-paginationjs-previous");if(a){var i=a.getAttribute("data-num");if(i&&(i=i.trim()),i&&!a.classList.contains(t.attributes.disableClassName))return!1!==t.callHook("beforePreviousOnClick",e,i)&&(t.go(i),t.callHook("afterPreviousOnClick",e,i),t.attributes.pageLink?void 0:(e.preventDefault(),!1))}}),n(a,"click",function(e){var a=e.target.closest(".J-paginationjs-next");if(a){var i=a.getAttribute("data-num");if(i&&(i=i.trim()),i&&!a.classList.contains(t.attributes.disableClassName))return!1!==t.callHook("beforeNextOnClick",e,i)&&(t.go(i),t.callHook("afterNextOnClick",e,i),t.attributes.pageLink?void 0:(e.preventDefault(),!1))}}),n(a,"click",function(e){var i=e.target.closest(".J-paginationjs-go-button");if(i){var n=a.querySelector(".J-paginationjs-go-pagenumber").value;if(!1===t.callHook("beforeGoButtonOnClick",e,n))return!1;r(t.container,l+"go",n),t.callHook("afterGoButtonOnClick",e,n)}}),n(a,"keyup",function(e){if(e.target.classList.contains("J-paginationjs-go-pagenumber")&&13===e.which){var i=e.target.value;if(!1===t.callHook("beforeGoInputOnEnter",e,i))return!1;r(t.container,l+"go",i),a.querySelector(".J-paginationjs-go-pagenumber").focus(),t.callHook("afterGoInputOnEnter",e,i)}}),n(a,"change",function(e){if(e.target.classList.contains("J-paginationjs-size-select")){var a=parseInt(e.target.value),i=t.model.pageNumber||t.attributes.pageNumber;if("number"==typeof a)return!1!==t.callHook("beforeSizeSelectorChange",e,a)&&(t.attributes.pageSize=a,t.model.pageSize=a,t.model.totalPage=t.getTotalPage(),i>t.model.totalPage&&(i=t.model.totalPage),t.go(i),t.callHook("afterSizeSelectorChange",e,a),t.attributes.pageLink?void 0:(e.preventDefault(),!1))}}),n(t.container,l+"previous",function(e){t.previous()}),n(t.container,l+"next",function(e){t.next()}),n(t.container,l+"disable",function(e){t.disable()}),n(t.container,l+"enable",function(e){t.enable()}),n(t.container,l+"refresh",function(e){t.refresh()}),n(t.container,l+"show",function(e){t.show()}),n(t.container,l+"hide",function(e){t.hide()}),n(t.container,l+"destroy",function(e){t.destroy()});var i=Math.max(t.getTotalPage(),1),o=t.attributes.pageNumber;t.isDynamicTotalNumber&&t.attributes.resetPageNumberOnInit&&(o=1),t.attributes.triggerPagingOnInit&&r(t.container,l+"go",Math.min(o,i))}},u.defaults={totalNumber:0,pageNumber:1,pageSize:10,pageRange:2,showPrevious:!0,showNext:!0,showPageNumbers:!0,showNavigator:!1,showGoInput:!1,showGoButton:!1,showSizeChanger:!1,sizeChangerOptions:[10,20,50,100],pageLink:"",prevText:"‹",nextText:"›",ellipsisText:"...",goButtonText:"Go",classPrefix:"paginationjs",activeClassName:"active",disableClassName:"disabled",formatNavigator:"Total <%= totalNumber %> items",formatGoInput:"<%= input %>",formatGoButton:"<%= button %>",position:"bottom",autoHidePrevious:!1,autoHideNext:!1,triggerPagingOnInit:!0,resetPageNumberOnInit:!0,hideOnlyOnePage:!1,hideFirstOnEllipsisShow:!1,hideLastOnEllipsisShow:!1,callback:function(){}},u.prototype.addHook=function(t,a){arguments.length<2&&e("Expect 2 arguments at least."),"function"!=typeof a&&e("callback should be a function.");var i=this.container.paginationData;i||(this.container.paginationData={},i=this.container.paginationData),i.hooks||(i.hooks={}),i.hooks[t]||(i.hooks[t]=[]),i.hooks[t].push(a)},u.create=function(t,a){var i;if(arguments.length<2&&e("Requires two parameters."),i="string"!=typeof t&&t instanceof Element?t:document.querySelector(t),i)return new u(i,a)},t.PaginDataJS=u,"function"==typeof define&&define.amd&&define(function(){return u}),"undefined"!=typeof module&&module.exports&&(module.exports=u)})(this);