UNPKG

123 kBJavaScriptView Raw
1/*! *****************************************************************************
2Copyright (c) Microsoft Corporation.
3
4Permission to use, copy, modify, and/or distribute this software for any
5purpose with or without fee is hereby granted.
6
7THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13PERFORMANCE OF THIS SOFTWARE.
14***************************************************************************** */
15/* global Reflect, Promise */
16
17var extendStatics = function(d, b) {
18 extendStatics = Object.setPrototypeOf ||
19 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
21 return extendStatics(d, b);
22};
23
24function __extends(d, b) {
25 extendStatics(d, b);
26 function __() { this.constructor = d; }
27 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28}
29
30var __assign = function() {
31 __assign = Object.assign || function __assign(t) {
32 for (var s, i = 1, n = arguments.length; i < n; i++) {
33 s = arguments[i];
34 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
35 }
36 return t;
37 };
38 return __assign.apply(this, arguments);
39};
40
41function __awaiter(thisArg, _arguments, P, generator) {
42 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
43 return new (P || (P = Promise))(function (resolve, reject) {
44 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
45 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
46 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
47 step((generator = generator.apply(thisArg, _arguments || [])).next());
48 });
49}
50
51function __generator(thisArg, body) {
52 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
53 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
54 function verb(n) { return function (v) { return step([n, v]); }; }
55 function step(op) {
56 if (f) throw new TypeError("Generator is already executing.");
57 while (_) try {
58 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
59 if (y = 0, t) op = [op[0] & 2, t.value];
60 switch (op[0]) {
61 case 0: case 1: t = op; break;
62 case 4: _.label++; return { value: op[1], done: false };
63 case 5: _.label++; y = op[1]; op = [0]; continue;
64 case 7: op = _.ops.pop(); _.trys.pop(); continue;
65 default:
66 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
67 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
68 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
69 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
70 if (t[2]) _.ops.pop();
71 _.trys.pop(); continue;
72 }
73 op = body.call(thisArg, _);
74 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
75 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
76 }
77}
78
79function __spreadArrays() {
80 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
81 for (var r = Array(s), k = 0, i = 0; i < il; i++)
82 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
83 r[k] = a[j];
84 return r;
85}
86
87var n,l,u,i,t,o,r,f={},e=[],c=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function s(n,l){for(var u in l)n[u]=l[u];return n}function a(n){var l=n.parentNode;l&&l.removeChild(n);}function v(n,l,u){var i,t,o,r=arguments,f={};for(o in l)"key"==o?i=l[o]:"ref"==o?t=l[o]:f[o]=l[o];if(arguments.length>3)for(u=[u],o=3;o<arguments.length;o++)u.push(r[o]);if(null!=u&&(f.children=u),"function"==typeof n&&null!=n.defaultProps)for(o in n.defaultProps)void 0===f[o]&&(f[o]=n.defaultProps[o]);return h(n,f,i,t,null)}function h(l,u,i,t,o){var r={type:l,props:u,key:i,ref:t,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==o?++n.__v:o};return null!=n.vnode&&n.vnode(r),r}function y(){return {current:null}}function p(n){return n.children}function d(n,l){this.props=n,this.context=l;}function _(n,l){if(null==l)return n.__?_(n.__,n.__.__k.indexOf(n)+1):null;for(var u;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e)return u.__e;return "function"==typeof n.type?_(n):null}function w(n){var l,u;if(null!=(n=n.__)&&null!=n.__c){for(n.__e=n.__c.base=null,l=0;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e){n.__e=n.__c.base=u.__e;break}return w(n)}}function k(l){(!l.__d&&(l.__d=!0)&&u.push(l)&&!g.__r++||t!==n.debounceRendering)&&((t=n.debounceRendering)||i)(g);}function g(){for(var n;g.__r=u.length;)n=u.sort(function(n,l){return n.__v.__b-l.__v.__b}),u=[],n.some(function(n){var l,u,i,t,o,r;n.__d&&(o=(t=(l=n).__v).__e,(r=l.__P)&&(u=[],(i=s({},t)).__v=t.__v+1,$(r,t,i,l.__n,void 0!==r.ownerSVGElement,null!=t.__h?[o]:null,u,null==o?_(t):o,t.__h),j(u,t),t.__e!=o&&w(t)));});}function m(n,l,u,i,t,o,r,c,s,v){var y,d,w,k,g,m,x,P=i&&i.__k||e,C=P.length;for(s==f&&(s=null!=r?r[0]:C?_(i,0):null),u.__k=[],y=0;y<l.length;y++)if(null!=(k=u.__k[y]=null==(k=l[y])||"boolean"==typeof k?null:"string"==typeof k||"number"==typeof k?h(null,k,null,null,k):Array.isArray(k)?h(p,{children:k},null,null,null):k.__b>0?h(k.type,k.props,k.key,null,k.__v):k)){if(k.__=u,k.__b=u.__b+1,null===(w=P[y])||w&&k.key==w.key&&k.type===w.type)P[y]=void 0;else for(d=0;d<C;d++){if((w=P[d])&&k.key==w.key&&k.type===w.type){P[d]=void 0;break}w=null;}$(n,k,w=w||f,t,o,r,c,s,v),g=k.__e,(d=k.ref)&&w.ref!=d&&(x||(x=[]),w.ref&&x.push(w.ref,null,k),x.push(d,k.__c||g,k)),null!=g?(null==m&&(m=g),"function"==typeof k.type&&k.__k===w.__k?k.__d=s=b(k,s,n):s=A(n,k,w,P,r,g,s),v||"option"!==u.type?"function"==typeof u.type&&(u.__d=s):n.value=""):s&&w.__e==s&&s.parentNode!=n&&(s=_(w));}if(u.__e=m,null!=r&&"function"!=typeof u.type)for(y=r.length;y--;)null!=r[y]&&a(r[y]);for(y=C;y--;)null!=P[y]&&("function"==typeof u.type&&null!=P[y].__e&&P[y].__e==u.__d&&(u.__d=_(i,y+1)),L(P[y],P[y]));if(x)for(y=0;y<x.length;y++)I(x[y],x[++y],x[++y]);}function b(n,l,u){var i,t;for(i=0;i<n.__k.length;i++)(t=n.__k[i])&&(t.__=n,"function"==typeof t.type?b(t,l,u):l=A(u,t,t,n.__k,null,t.__e,l));return l}function A(n,l,u,i,t,o,r){var f,e,c;if(void 0!==l.__d)f=l.__d,l.__d=void 0;else if(t==u||o!=r||null==o.parentNode)n:if(null==r||r.parentNode!==n)n.appendChild(o),f=null;else {for(e=r,c=0;(e=e.nextSibling)&&c<i.length;c+=2)if(e==o)break n;n.insertBefore(o,r),f=r;}return void 0!==f?f:o.nextSibling}function P(n,l,u,i,t){var o;for(o in u)"children"===o||"key"===o||o in l||z(n,o,null,u[o],i);for(o in l)t&&"function"!=typeof l[o]||"children"===o||"key"===o||"value"===o||"checked"===o||u[o]===l[o]||z(n,o,l[o],u[o],i);}function C(n,l,u){"-"===l[0]?n.setProperty(l,u):n[l]=null==u?"":"number"!=typeof u||c.test(l)?u:u+"px";}function z(n,l,u,i,t){var o,r,f;if(t&&"className"==l&&(l="class"),"style"===l)if("string"==typeof u)n.style.cssText=u;else {if("string"==typeof i&&(n.style.cssText=i=""),i)for(l in i)u&&l in u||C(n.style,l,"");if(u)for(l in u)i&&u[l]===i[l]||C(n.style,l,u[l]);}else "o"===l[0]&&"n"===l[1]?(o=l!==(l=l.replace(/Capture$/,"")),(r=l.toLowerCase())in n&&(l=r),l=l.slice(2),n.l||(n.l={}),n.l[l+o]=u,f=o?T:N,u?i||n.addEventListener(l,f,o):n.removeEventListener(l,f,o)):"list"!==l&&"tagName"!==l&&"form"!==l&&"type"!==l&&"size"!==l&&"download"!==l&&"href"!==l&&!t&&l in n?n[l]=null==u?"":u:"function"!=typeof u&&"dangerouslySetInnerHTML"!==l&&(l!==(l=l.replace(/xlink:?/,""))?null==u||!1===u?n.removeAttributeNS("http://www.w3.org/1999/xlink",l.toLowerCase()):n.setAttributeNS("http://www.w3.org/1999/xlink",l.toLowerCase(),u):null==u||!1===u&&!/^ar/.test(l)?n.removeAttribute(l):n.setAttribute(l,u));}function N(l){this.l[l.type+!1](n.event?n.event(l):l);}function T(l){this.l[l.type+!0](n.event?n.event(l):l);}function $(l,u,i,t,o,r,f,e,c){var a,v,h,y,_,w,k,g,b,x,A,P=u.type;if(void 0!==u.constructor)return null;null!=i.__h&&(c=i.__h,e=u.__e=i.__e,u.__h=null,r=[e]),(a=n.__b)&&a(u);try{n:if("function"==typeof P){if(g=u.props,b=(a=P.contextType)&&t[a.__c],x=a?b?b.props.value:a.__:t,i.__c?k=(v=u.__c=i.__c).__=v.__E:("prototype"in P&&P.prototype.render?u.__c=v=new P(g,x):(u.__c=v=new d(g,x),v.constructor=P,v.render=M),b&&b.sub(v),v.props=g,v.state||(v.state={}),v.context=x,v.__n=t,h=v.__d=!0,v.__h=[]),null==v.__s&&(v.__s=v.state),null!=P.getDerivedStateFromProps&&(v.__s==v.state&&(v.__s=s({},v.__s)),s(v.__s,P.getDerivedStateFromProps(g,v.__s))),y=v.props,_=v.state,h)null==P.getDerivedStateFromProps&&null!=v.componentWillMount&&v.componentWillMount(),null!=v.componentDidMount&&v.__h.push(v.componentDidMount);else {if(null==P.getDerivedStateFromProps&&g!==y&&null!=v.componentWillReceiveProps&&v.componentWillReceiveProps(g,x),!v.__e&&null!=v.shouldComponentUpdate&&!1===v.shouldComponentUpdate(g,v.__s,x)||u.__v===i.__v){v.props=g,v.state=v.__s,u.__v!==i.__v&&(v.__d=!1),v.__v=u,u.__e=i.__e,u.__k=i.__k,v.__h.length&&f.push(v);break n}null!=v.componentWillUpdate&&v.componentWillUpdate(g,v.__s,x),null!=v.componentDidUpdate&&v.__h.push(function(){v.componentDidUpdate(y,_,w);});}v.context=x,v.props=g,v.state=v.__s,(a=n.__r)&&a(u),v.__d=!1,v.__v=u,v.__P=l,a=v.render(v.props,v.state,v.context),v.state=v.__s,null!=v.getChildContext&&(t=s(s({},t),v.getChildContext())),h||null==v.getSnapshotBeforeUpdate||(w=v.getSnapshotBeforeUpdate(y,_)),A=null!=a&&a.type===p&&null==a.key?a.props.children:a,m(l,Array.isArray(A)?A:[A],u,i,t,o,r,f,e,c),v.base=u.__e,u.__h=null,v.__h.length&&f.push(v),k&&(v.__E=v.__=null),v.__e=!1;}else null==r&&u.__v===i.__v?(u.__k=i.__k,u.__e=i.__e):u.__e=H(i.__e,u,i,t,o,r,f,c);(a=n.diffed)&&a(u);}catch(l){u.__v=null,(c||null!=r)&&(u.__e=e,u.__h=!!c,r[r.indexOf(e)]=null),n.__e(l,u,i);}}function j(l,u){n.__c&&n.__c(u,l),l.some(function(u){try{l=u.__h,u.__h=[],l.some(function(n){n.call(u);});}catch(l){n.__e(l,u.__v);}});}function H(n,l,u,i,t,o,r,c){var s,a,v,h,y,p=u.props,d=l.props;if(t="svg"===l.type||t,null!=o)for(s=0;s<o.length;s++)if(null!=(a=o[s])&&((null===l.type?3===a.nodeType:a.localName===l.type)||n==a)){n=a,o[s]=null;break}if(null==n){if(null===l.type)return document.createTextNode(d);n=t?document.createElementNS("http://www.w3.org/2000/svg",l.type):document.createElement(l.type,d.is&&{is:d.is}),o=null,c=!1;}if(null===l.type)p===d||c&&n.data===d||(n.data=d);else {if(null!=o&&(o=e.slice.call(n.childNodes)),v=(p=u.props||f).dangerouslySetInnerHTML,h=d.dangerouslySetInnerHTML,!c){if(null!=o)for(p={},y=0;y<n.attributes.length;y++)p[n.attributes[y].name]=n.attributes[y].value;(h||v)&&(h&&(v&&h.__html==v.__html||h.__html===n.innerHTML)||(n.innerHTML=h&&h.__html||""));}P(n,d,p,t,c),h?l.__k=[]:(s=l.props.children,m(n,Array.isArray(s)?s:[s],l,u,i,"foreignObject"!==l.type&&t,o,r,f,c)),c||("value"in d&&void 0!==(s=d.value)&&(s!==n.value||"progress"===l.type&&!s)&&z(n,"value",s,p.value,!1),"checked"in d&&void 0!==(s=d.checked)&&s!==n.checked&&z(n,"checked",s,p.checked,!1));}return n}function I(l,u,i){try{"function"==typeof l?l(u):l.current=u;}catch(l){n.__e(l,i);}}function L(l,u,i){var t,o,r;if(n.unmount&&n.unmount(l),(t=l.ref)&&(t.current&&t.current!==l.__e||I(t,null,u)),i||"function"==typeof l.type||(i=null!=(o=l.__e)),l.__e=l.__d=void 0,null!=(t=l.__c)){if(t.componentWillUnmount)try{t.componentWillUnmount();}catch(l){n.__e(l,u);}t.base=t.__P=null;}if(t=l.__k)for(r=0;r<t.length;r++)t[r]&&L(t[r],u,i);null!=o&&a(o);}function M(n,l,u){return this.constructor(n,u)}function O(l,u,i){var t,r,c;n.__&&n.__(l,u),r=(t=i===o)?null:i&&i.__k||u.__k,l=v(p,null,[l]),c=[],$(u,(t?u:i||u).__k=l,r||f,f,void 0!==u.ownerSVGElement,i&&!t?[i]:r?null:u.childNodes.length?e.slice.call(u.childNodes):null,c,i||f,t),j(c,l);}function B(n,l){var u={__c:l="__cC"+r++,__:n,Consumer:function(n,l){return n.children(l)},Provider:function(n){var u,i;return this.getChildContext||(u=[],(i={})[l]=this,this.getChildContext=function(){return i},this.shouldComponentUpdate=function(n){this.props.value!==n.value&&u.some(k);},this.sub=function(n){u.push(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u.splice(u.indexOf(n),1),l&&l.call(n);};}),n.children}};return u.Provider.__=u.Consumer.contextType=u}n={__e:function(n,l){for(var u,i,t,o=l.__h;l=l.__;)if((u=l.__c)&&!u.__)try{if((i=u.constructor)&&null!=i.getDerivedStateFromError&&(u.setState(i.getDerivedStateFromError(n)),t=u.__d),null!=u.componentDidCatch&&(u.componentDidCatch(n),t=u.__d),t)return l.__h=o,u.__E=u}catch(l){n=l;}throw n},__v:0},l=function(n){return null!=n&&void 0===n.constructor},d.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=s({},this.state),"function"==typeof n&&(n=n(s({},u),this.props)),n&&s(u,n),null!=n&&this.__v&&(l&&this.__h.push(l),k(this));},d.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),k(this));},d.prototype.render=p,u=[],i="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,g.__r=0,o=f,r=0;
88
89function generateUUID() {
90 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
91 var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
92 return v.toString(16);
93 });
94}
95
96var Base = /** @class */ (function () {
97 function Base(id) {
98 this._id = id || generateUUID();
99 }
100 Object.defineProperty(Base.prototype, "id", {
101 get: function () {
102 return this._id;
103 },
104 enumerable: false,
105 configurable: true
106 });
107 return Base;
108}());
109
110/**
111 * This is a hack to get the current global config from Preact context.
112 * My assumption is that we only need one global context which is the ConfigContext
113 *
114 * @param context
115 */
116function getConfig(context) {
117 if (!context)
118 return null;
119 var keys = Object.keys(context);
120 if (keys.length) {
121 // TODO: can we use a better way to capture and return the Config context?
122 var ctx = context[keys[0]];
123 return ctx.props.value;
124 }
125 return null;
126}
127
128var enUS = {
129 search: {
130 placeholder: 'Type a keyword...',
131 },
132 sort: {
133 sortAsc: 'Sort column ascending',
134 sortDesc: 'Sort column descending',
135 },
136 pagination: {
137 previous: 'Previous',
138 next: 'Next',
139 navigate: function (page, pages) { return "Page " + page + " of " + pages; },
140 page: function (page) { return "Page " + page; },
141 showing: 'Showing',
142 of: 'of',
143 to: 'to',
144 results: 'results',
145 },
146 loading: 'Loading...',
147 noRecordsFound: 'No matching records found',
148 error: 'An error happened while fetching the data',
149};
150
151var Translator = /** @class */ (function () {
152 function Translator(language) {
153 this._language = language;
154 this._defaultLanguage = enUS;
155 }
156 /**
157 * Tries to split the message with "." and find
158 * the key in the given language
159 *
160 * @param message
161 * @param lang
162 */
163 Translator.prototype.getString = function (message, lang) {
164 if (!lang || !message)
165 return null;
166 var splitted = message.split('.');
167 var key = splitted[0];
168 if (lang[key]) {
169 var val_1 = lang[key];
170 if (typeof val_1 === 'string') {
171 return function () { return val_1; };
172 }
173 else if (typeof val_1 === 'function') {
174 return val_1;
175 }
176 else {
177 return this.getString(splitted.slice(1).join('.'), val_1);
178 }
179 }
180 return null;
181 };
182 Translator.prototype.translate = function (message) {
183 var args = [];
184 for (var _i = 1; _i < arguments.length; _i++) {
185 args[_i - 1] = arguments[_i];
186 }
187 var translated = this.getString(message, this._language);
188 var messageFormat;
189 if (translated) {
190 messageFormat = translated;
191 }
192 else {
193 messageFormat = this.getString(message, this._defaultLanguage);
194 }
195 if (messageFormat) {
196 return messageFormat.apply(void 0, args);
197 }
198 return message;
199 };
200 return Translator;
201}());
202function useTranslator(translator) {
203 return function (message) {
204 var args = [];
205 for (var _i = 1; _i < arguments.length; _i++) {
206 args[_i - 1] = arguments[_i];
207 }
208 return translator.translate.apply(translator, __spreadArrays([message], args));
209 };
210}
211
212var BaseComponent = /** @class */ (function (_super) {
213 __extends(BaseComponent, _super);
214 function BaseComponent(props, context) {
215 var _this = _super.call(this, props, context) || this;
216 _this.config = getConfig(context);
217 if (_this.config) {
218 _this._ = useTranslator(_this.config.translator);
219 }
220 return _this;
221 }
222 return BaseComponent;
223}(d));
224
225var HTMLElement$1 = /** @class */ (function (_super) {
226 __extends(HTMLElement, _super);
227 function HTMLElement() {
228 return _super !== null && _super.apply(this, arguments) || this;
229 }
230 HTMLElement.prototype.render = function () {
231 return v(this.props.parentElement, {
232 dangerouslySetInnerHTML: { __html: this.props.content },
233 });
234 };
235 HTMLElement.defaultProps = {
236 parentElement: 'span',
237 };
238 return HTMLElement;
239}(BaseComponent));
240
241function decode(content) {
242 var value = new DOMParser().parseFromString(content, 'text/html');
243 return value.documentElement.textContent;
244}
245function html(content, parentElement) {
246 return v(HTMLElement$1, { content: content, parentElement: parentElement });
247}
248
249var Cell = /** @class */ (function (_super) {
250 __extends(Cell, _super);
251 function Cell(data) {
252 var _this = _super.call(this) || this;
253 _this.update(data);
254 return _this;
255 }
256 Cell.prototype.cast = function (data) {
257 if (data instanceof HTMLElement) {
258 return html(data.outerHTML);
259 }
260 return data;
261 };
262 /**
263 * Updates the Cell's data
264 *
265 * @param data
266 */
267 Cell.prototype.update = function (data) {
268 this.data = this.cast(data);
269 return this;
270 };
271 return Cell;
272}(Base));
273
274var Row = /** @class */ (function (_super) {
275 __extends(Row, _super);
276 function Row(cells) {
277 var _this = _super.call(this) || this;
278 _this.cells = cells || [];
279 return _this;
280 }
281 Row.prototype.cell = function (index) {
282 return this._cells[index];
283 };
284 Object.defineProperty(Row.prototype, "cells", {
285 get: function () {
286 return this._cells;
287 },
288 set: function (cells) {
289 this._cells = cells;
290 },
291 enumerable: false,
292 configurable: true
293 });
294 Row.prototype.toArray = function () {
295 return this.cells.map(function (cell) { return cell.data; });
296 };
297 /**
298 * Creates a new Row from an array of Cell(s)
299 * This method generates a new ID for the Row and all nested elements
300 *
301 * @param cells
302 * @returns Row
303 */
304 Row.fromCells = function (cells) {
305 return new Row(cells.map(function (cell) { return new Cell(cell.data); }));
306 };
307 Object.defineProperty(Row.prototype, "length", {
308 get: function () {
309 return this.cells.length;
310 },
311 enumerable: false,
312 configurable: true
313 });
314 return Row;
315}(Base));
316
317function oneDtoTwoD(data) {
318 if (data[0] && !(data[0] instanceof Array)) {
319 return [data];
320 }
321 return data;
322}
323function flatten(arrays) {
324 return arrays.reduce(function (prev, x) { return prev.concat(x); }, []);
325}
326
327var Tabular = /** @class */ (function (_super) {
328 __extends(Tabular, _super);
329 function Tabular(rows) {
330 var _this = _super.call(this) || this;
331 if (rows instanceof Array) {
332 _this.rows = rows;
333 }
334 else if (rows instanceof Row) {
335 _this.rows = [rows];
336 }
337 else {
338 _this.rows = [];
339 }
340 return _this;
341 }
342 Object.defineProperty(Tabular.prototype, "rows", {
343 get: function () {
344 return this._rows;
345 },
346 set: function (rows) {
347 this._rows = rows;
348 },
349 enumerable: false,
350 configurable: true
351 });
352 Object.defineProperty(Tabular.prototype, "length", {
353 get: function () {
354 return this._length || this.rows.length;
355 },
356 // we want to sent the length when storage is ServerStorage
357 set: function (len) {
358 this._length = len;
359 },
360 enumerable: false,
361 configurable: true
362 });
363 Tabular.prototype.toArray = function () {
364 return this.rows.map(function (row) { return row.toArray(); });
365 };
366 /**
367 * Creates a new Tabular from an array of Row(s)
368 * This method generates a new ID for the Tabular and all nested elements
369 *
370 * @param rows
371 * @returns Tabular
372 */
373 Tabular.fromRows = function (rows) {
374 return new Tabular(rows.map(function (row) { return Row.fromCells(row.cells); }));
375 };
376 /**
377 * Creates a new Tabular from a 2D array
378 * This method generates a new ID for the Tabular and all nested elements
379 *
380 * @param data
381 * @returns Tabular
382 */
383 Tabular.fromArray = function (data) {
384 data = oneDtoTwoD(data);
385 return new Tabular(data.map(function (row) { return new Row(row.map(function (cell) { return new Cell(cell); })); }));
386 };
387 return Tabular;
388}(Base));
389
390function search (keyword, tabular, selector) {
391 // escape special regex chars
392 keyword = keyword.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
393 return new Tabular(tabular.rows.filter(function (row, rowIndex) {
394 return row.cells.some(function (cell, cellIndex) {
395 if (!cell) {
396 return false;
397 }
398 var data = '';
399 if (typeof selector === 'function') {
400 data = selector(cell.data, rowIndex, cellIndex);
401 }
402 else if (typeof cell.data === 'object') {
403 // HTMLContent element
404 var element = cell.data;
405 if (element && element.props && element.props.content) {
406 // TODO: we should only search in the content of the element. props.content is the entire HTML element
407 data = element.props.content;
408 }
409 }
410 else {
411 // primitive types
412 data = String(cell.data);
413 }
414 return new RegExp(keyword, 'gi').test(data);
415 });
416 }));
417}
418
419var EventEmitter = /** @class */ (function () {
420 function EventEmitter() {
421 }
422 // because we are using EventEmitter as a mixin and the
423 // constructor won't be called by the applyMixins function
424 // see src/base.ts and src/util/applyMixin.ts
425 EventEmitter.prototype.init = function (event) {
426 if (!this.callbacks) {
427 this.callbacks = {};
428 }
429 if (event && !this.callbacks[event]) {
430 this.callbacks[event] = [];
431 }
432 };
433 EventEmitter.prototype.on = function (event, listener) {
434 this.init(event);
435 this.callbacks[event].push(listener);
436 return this;
437 };
438 EventEmitter.prototype.off = function (event, listener) {
439 var eventName = event;
440 this.init();
441 if (!this.callbacks[eventName] || this.callbacks[eventName].length === 0) {
442 // there is no callbacks with this key
443 return this;
444 }
445 this.callbacks[eventName] = this.callbacks[eventName].filter(function (value) { return value != listener; });
446 return this;
447 };
448 EventEmitter.prototype.emit = function (event) {
449 var args = [];
450 for (var _i = 1; _i < arguments.length; _i++) {
451 args[_i - 1] = arguments[_i];
452 }
453 var eventName = event;
454 this.init(eventName);
455 if (this.callbacks[eventName].length > 0) {
456 this.callbacks[eventName].forEach(function (value) { return value.apply(void 0, args); });
457 return true;
458 }
459 return false;
460 };
461 return EventEmitter;
462}());
463
464var ProcessorType;
465(function (ProcessorType) {
466 ProcessorType[ProcessorType["Initiator"] = 0] = "Initiator";
467 ProcessorType[ProcessorType["ServerFilter"] = 1] = "ServerFilter";
468 ProcessorType[ProcessorType["ServerSort"] = 2] = "ServerSort";
469 ProcessorType[ProcessorType["ServerLimit"] = 3] = "ServerLimit";
470 ProcessorType[ProcessorType["Extractor"] = 4] = "Extractor";
471 ProcessorType[ProcessorType["Transformer"] = 5] = "Transformer";
472 ProcessorType[ProcessorType["Filter"] = 6] = "Filter";
473 ProcessorType[ProcessorType["Sort"] = 7] = "Sort";
474 ProcessorType[ProcessorType["Limit"] = 8] = "Limit";
475})(ProcessorType || (ProcessorType = {}));
476var PipelineProcessor = /** @class */ (function (_super) {
477 __extends(PipelineProcessor, _super);
478 function PipelineProcessor(props) {
479 var _this = _super.call(this) || this;
480 _this._props = {};
481 _this.id = generateUUID();
482 if (props)
483 _this.setProps(props);
484 return _this;
485 }
486 /**
487 * process is used to call beforeProcess and afterProcess callbacks
488 * This function is just a wrapper that calls _process()
489 *
490 * @param args
491 */
492 PipelineProcessor.prototype.process = function () {
493 var args = [];
494 for (var _i = 0; _i < arguments.length; _i++) {
495 args[_i] = arguments[_i];
496 }
497 if (this.validateProps instanceof Function) {
498 this.validateProps.apply(this, args);
499 }
500 this.emit.apply(this, __spreadArrays(['beforeProcess'], args));
501 var result = this._process.apply(this, args);
502 this.emit.apply(this, __spreadArrays(['afterProcess'], args));
503 return result;
504 };
505 PipelineProcessor.prototype.setProps = function (props) {
506 Object.assign(this._props, props);
507 this.emit('propsUpdated', this);
508 return this;
509 };
510 Object.defineProperty(PipelineProcessor.prototype, "props", {
511 get: function () {
512 return this._props;
513 },
514 enumerable: false,
515 configurable: true
516 });
517 return PipelineProcessor;
518}(EventEmitter));
519
520var GlobalSearchFilter = /** @class */ (function (_super) {
521 __extends(GlobalSearchFilter, _super);
522 function GlobalSearchFilter() {
523 return _super !== null && _super.apply(this, arguments) || this;
524 }
525 Object.defineProperty(GlobalSearchFilter.prototype, "type", {
526 get: function () {
527 return ProcessorType.Filter;
528 },
529 enumerable: false,
530 configurable: true
531 });
532 GlobalSearchFilter.prototype._process = function (data) {
533 if (this.props.keyword) {
534 return search(String(this.props.keyword).trim(), data, this.props.selector);
535 }
536 return data;
537 };
538 return GlobalSearchFilter;
539}(PipelineProcessor));
540
541function className() {
542 var args = [];
543 for (var _i = 0; _i < arguments.length; _i++) {
544 args[_i] = arguments[_i];
545 }
546 var prefix = 'gridjs';
547 return "" + prefix + args.reduce(function (prev, cur) { return prev + "-" + cur; }, '');
548}
549function classJoin() {
550 var classNames = [];
551 for (var _i = 0; _i < arguments.length; _i++) {
552 classNames[_i] = arguments[_i];
553 }
554 return (classNames
555 .filter(function (x) { return x; })
556 .reduce(function (className, prev) { return (className || '') + " " + prev; }, '')
557 .trim() || null);
558}
559
560var BaseStore = /** @class */ (function (_super) {
561 __extends(BaseStore, _super);
562 function BaseStore(dispatcher) {
563 var _this = _super.call(this) || this;
564 _this.dispatcher = dispatcher;
565 _this._state = _this.getInitialState();
566 dispatcher.register(_this._handle.bind(_this));
567 return _this;
568 }
569 BaseStore.prototype._handle = function (action) {
570 this.handle(action.type, action.payload);
571 };
572 BaseStore.prototype.setState = function (newState) {
573 var prevState = this._state;
574 this._state = newState;
575 this.emit('updated', newState, prevState);
576 };
577 Object.defineProperty(BaseStore.prototype, "state", {
578 get: function () {
579 return this._state;
580 },
581 enumerable: false,
582 configurable: true
583 });
584 return BaseStore;
585}(EventEmitter));
586
587var SearchStore = /** @class */ (function (_super) {
588 __extends(SearchStore, _super);
589 function SearchStore() {
590 return _super !== null && _super.apply(this, arguments) || this;
591 }
592 SearchStore.prototype.getInitialState = function () {
593 return { keyword: null };
594 };
595 SearchStore.prototype.handle = function (type, payload) {
596 if (type === 'SEARCH_KEYWORD') {
597 var keyword = payload.keyword;
598 this.search(keyword);
599 }
600 };
601 SearchStore.prototype.search = function (keyword) {
602 this.setState({ keyword: keyword });
603 };
604 return SearchStore;
605}(BaseStore));
606
607var BaseActions = /** @class */ (function () {
608 function BaseActions(dispatcher) {
609 this.dispatcher = dispatcher;
610 }
611 BaseActions.prototype.dispatch = function (type, payload) {
612 this.dispatcher.dispatch({
613 type: type,
614 payload: payload,
615 });
616 };
617 return BaseActions;
618}());
619
620var SearchActions = /** @class */ (function (_super) {
621 __extends(SearchActions, _super);
622 function SearchActions() {
623 return _super !== null && _super.apply(this, arguments) || this;
624 }
625 SearchActions.prototype.search = function (keyword) {
626 this.dispatch('SEARCH_KEYWORD', {
627 keyword: keyword,
628 });
629 };
630 return SearchActions;
631}(BaseActions));
632
633var ServerGlobalSearchFilter = /** @class */ (function (_super) {
634 __extends(ServerGlobalSearchFilter, _super);
635 function ServerGlobalSearchFilter() {
636 return _super !== null && _super.apply(this, arguments) || this;
637 }
638 Object.defineProperty(ServerGlobalSearchFilter.prototype, "type", {
639 get: function () {
640 return ProcessorType.ServerFilter;
641 },
642 enumerable: false,
643 configurable: true
644 });
645 ServerGlobalSearchFilter.prototype._process = function (options) {
646 if (!this.props.keyword)
647 return options;
648 var updates = {};
649 if (this.props.url) {
650 updates['url'] = this.props.url(options.url, this.props.keyword);
651 }
652 if (this.props.body) {
653 updates['body'] = this.props.body(options.body, this.props.keyword);
654 }
655 return __assign(__assign({}, options), updates);
656 };
657 return ServerGlobalSearchFilter;
658}(PipelineProcessor));
659
660var debounce = function (func, waitFor) {
661 var timeout;
662 return function () {
663 var args = [];
664 for (var _i = 0; _i < arguments.length; _i++) {
665 args[_i] = arguments[_i];
666 }
667 return new Promise(function (resolve) {
668 if (timeout) {
669 clearTimeout(timeout);
670 }
671 timeout = setTimeout(function () { return resolve(func.apply(void 0, args)); }, waitFor);
672 });
673 };
674};
675
676/**
677 * Centralized logging lib
678 *
679 * This class needs some improvements but so far it has been used to have a coherent way to log
680 */
681var Logger = /** @class */ (function () {
682 function Logger() {
683 }
684 Logger.prototype.format = function (message, type) {
685 return "[Grid.js] [" + type.toUpperCase() + "]: " + message;
686 };
687 Logger.prototype.error = function (message, throwException) {
688 if (throwException === void 0) { throwException = false; }
689 var msg = this.format(message, 'error');
690 if (throwException) {
691 throw Error(msg);
692 }
693 else {
694 console.error(msg);
695 }
696 };
697 Logger.prototype.warn = function (message) {
698 console.warn(this.format(message, 'warn'));
699 };
700 Logger.prototype.info = function (message) {
701 console.info(this.format(message, 'info'));
702 };
703 return Logger;
704}());
705var log = new Logger();
706
707/**
708 * BaseComponent for all plugins
709 */
710var PluginBaseComponent = /** @class */ (function (_super) {
711 __extends(PluginBaseComponent, _super);
712 function PluginBaseComponent() {
713 return _super !== null && _super.apply(this, arguments) || this;
714 }
715 return PluginBaseComponent;
716}(BaseComponent));
717var PluginPosition;
718(function (PluginPosition) {
719 PluginPosition[PluginPosition["Header"] = 0] = "Header";
720 PluginPosition[PluginPosition["Footer"] = 1] = "Footer";
721 PluginPosition[PluginPosition["Cell"] = 2] = "Cell";
722})(PluginPosition || (PluginPosition = {}));
723var PluginManager = /** @class */ (function () {
724 function PluginManager() {
725 this.plugins = [];
726 }
727 PluginManager.prototype.get = function (id) {
728 var plugins = this.plugins.filter(function (p) { return p.id === id; });
729 if (plugins.length > 0) {
730 return plugins[0];
731 }
732 return null;
733 };
734 PluginManager.prototype.add = function (plugin) {
735 if (!plugin.id) {
736 log.error('Plugin ID cannot be empty');
737 return this;
738 }
739 if (this.get(plugin.id) !== null) {
740 log.error("Duplicate plugin ID: " + plugin.id);
741 return this;
742 }
743 this.plugins.push(plugin);
744 return this;
745 };
746 PluginManager.prototype.remove = function (id) {
747 this.plugins.splice(this.plugins.indexOf(this.get(id)), 1);
748 return this;
749 };
750 PluginManager.prototype.list = function (position) {
751 var plugins;
752 if (position != null || position != undefined) {
753 plugins = this.plugins.filter(function (p) { return p.position === position; });
754 }
755 else {
756 plugins = this.plugins;
757 }
758 return plugins.sort(function (a, b) { return a.order - b.order; });
759 };
760 return PluginManager;
761}());
762var PluginRenderer = /** @class */ (function (_super) {
763 __extends(PluginRenderer, _super);
764 function PluginRenderer() {
765 return _super !== null && _super.apply(this, arguments) || this;
766 }
767 PluginRenderer.prototype.render = function () {
768 var _this = this;
769 if (this.props.pluginId) {
770 // render a single plugin
771 var plugin = this.config.plugin.get(this.props.pluginId);
772 if (!plugin)
773 return null;
774 return v(p, {}, v(plugin.component, __assign(__assign({ plugin: plugin }, plugin.props), this.props.props)));
775 }
776 else if (this.props.position !== undefined) {
777 // render using a specific plugin position
778 return v(p, {}, this.config.plugin
779 .list(this.props.position)
780 .map(function (p) {
781 return v(p.component, __assign(__assign({ plugin: p }, p.props), _this.props.props));
782 }));
783 }
784 return null;
785 };
786 return PluginRenderer;
787}(BaseComponent));
788
789var Search = /** @class */ (function (_super) {
790 __extends(Search, _super);
791 function Search(props, context) {
792 var _this = _super.call(this, props, context) || this;
793 _this.actions = new SearchActions(_this.config.dispatcher);
794 _this.store = new SearchStore(_this.config.dispatcher);
795 var enabled = props.enabled, keyword = props.keyword;
796 if (enabled) {
797 // initial search
798 if (keyword)
799 _this.actions.search(keyword);
800 _this.storeUpdatedFn = _this.storeUpdated.bind(_this);
801 _this.store.on('updated', _this.storeUpdatedFn);
802 var searchProcessor = void 0;
803 if (props.server) {
804 searchProcessor = new ServerGlobalSearchFilter({
805 keyword: props.keyword,
806 url: props.server.url,
807 body: props.server.body,
808 });
809 }
810 else {
811 searchProcessor = new GlobalSearchFilter({
812 keyword: props.keyword,
813 selector: props.selector,
814 });
815 }
816 _this.searchProcessor = searchProcessor;
817 // adds a new processor to the pipeline
818 _this.config.pipeline.register(searchProcessor);
819 }
820 return _this;
821 }
822 Search.prototype.componentWillUnmount = function () {
823 this.config.pipeline.unregister(this.searchProcessor);
824 this.store.off('updated', this.storeUpdatedFn);
825 };
826 Search.prototype.storeUpdated = function (state) {
827 // updates the processor state
828 this.searchProcessor.setProps({
829 keyword: state.keyword,
830 });
831 };
832 Search.prototype.onChange = function (event) {
833 var keyword = event.target.value;
834 this.actions.search(keyword);
835 };
836 Search.prototype.render = function () {
837 if (!this.props.enabled)
838 return null;
839 var onInput = this.onChange.bind(this);
840 // add debounce to input only if it's a server-side search
841 if (this.searchProcessor instanceof ServerGlobalSearchFilter) {
842 onInput = debounce(onInput, this.props.debounceTimeout);
843 }
844 return (v("div", { className: className(classJoin('search', this.config.className.search)) },
845 v("input", { type: "search", placeholder: this._('search.placeholder'), "aria-label": this._('search.placeholder'), onInput: onInput, className: classJoin(className('input'), className('search', 'input')), value: this.store.state.keyword })));
846 };
847 Search.defaultProps = {
848 debounceTimeout: 250,
849 };
850 return Search;
851}(PluginBaseComponent));
852
853var PaginationLimit = /** @class */ (function (_super) {
854 __extends(PaginationLimit, _super);
855 function PaginationLimit() {
856 return _super !== null && _super.apply(this, arguments) || this;
857 }
858 PaginationLimit.prototype.validateProps = function () {
859 if (isNaN(Number(this.props.limit)) || isNaN(Number(this.props.page))) {
860 throw Error('Invalid parameters passed');
861 }
862 };
863 Object.defineProperty(PaginationLimit.prototype, "type", {
864 get: function () {
865 return ProcessorType.Limit;
866 },
867 enumerable: false,
868 configurable: true
869 });
870 PaginationLimit.prototype._process = function (data) {
871 var page = this.props.page;
872 var start = page * this.props.limit;
873 var end = (page + 1) * this.props.limit;
874 return new Tabular(data.rows.slice(start, end));
875 };
876 return PaginationLimit;
877}(PipelineProcessor));
878
879var ServerPaginationLimit = /** @class */ (function (_super) {
880 __extends(ServerPaginationLimit, _super);
881 function ServerPaginationLimit() {
882 return _super !== null && _super.apply(this, arguments) || this;
883 }
884 Object.defineProperty(ServerPaginationLimit.prototype, "type", {
885 get: function () {
886 return ProcessorType.ServerLimit;
887 },
888 enumerable: false,
889 configurable: true
890 });
891 ServerPaginationLimit.prototype._process = function (options) {
892 var updates = {};
893 if (this.props.url) {
894 updates['url'] = this.props.url(options.url, this.props.page, this.props.limit);
895 }
896 if (this.props.body) {
897 updates['body'] = this.props.body(options.body, this.props.page, this.props.limit);
898 }
899 return __assign(__assign({}, options), updates);
900 };
901 return ServerPaginationLimit;
902}(PipelineProcessor));
903
904var Pagination = /** @class */ (function (_super) {
905 __extends(Pagination, _super);
906 function Pagination(props, context) {
907 var _this = _super.call(this, props, context) || this;
908 _this.state = {
909 limit: props.limit,
910 page: props.page || 0,
911 total: 0,
912 };
913 return _this;
914 }
915 Pagination.prototype.componentWillMount = function () {
916 var _this = this;
917 if (this.props.enabled) {
918 var processor = void 0;
919 this.setTotalFromTabularFn = this.setTotalFromTabular.bind(this);
920 if (this.props.server) {
921 processor = new ServerPaginationLimit({
922 limit: this.state.limit,
923 page: this.state.page,
924 url: this.props.server.url,
925 body: this.props.server.body,
926 });
927 this.config.pipeline.on('afterProcess', this.setTotalFromTabularFn);
928 }
929 else {
930 processor = new PaginationLimit({
931 limit: this.state.limit,
932 page: this.state.page,
933 });
934 // Pagination (all Limit processors) is the last step in the pipeline
935 // and we assume that at this stage, we have the rows that we care about.
936 // Let's grab the rows before processing Pagination and set total number of rows
937 processor.on('beforeProcess', this.setTotalFromTabularFn);
938 }
939 this.processor = processor;
940 this.config.pipeline.register(processor);
941 // we need to make sure that the state is set
942 // to the default props when an error happens
943 this.config.pipeline.on('error', function () {
944 _this.setState({
945 total: 0,
946 page: 0,
947 });
948 });
949 }
950 };
951 Pagination.prototype.setTotalFromTabular = function (tabular) {
952 this.setTotal(tabular.length);
953 };
954 Pagination.prototype.onUpdate = function (processor) {
955 // this is to ensure that the current page is set to 0
956 // when a processor is updated for some reason
957 if (this.props.resetPageOnUpdate && processor !== this.processor) {
958 this.setPage(0);
959 }
960 };
961 Pagination.prototype.componentDidMount = function () {
962 this.onUpdateFn = this.onUpdate.bind(this);
963 this.config.pipeline.on('updated', this.onUpdateFn);
964 };
965 Pagination.prototype.componentWillUnmount = function () {
966 this.config.pipeline.unregister(this.processor);
967 this.config.pipeline.off('updated', this.onUpdateFn);
968 };
969 Object.defineProperty(Pagination.prototype, "pages", {
970 get: function () {
971 return Math.ceil(this.state.total / this.state.limit);
972 },
973 enumerable: false,
974 configurable: true
975 });
976 Pagination.prototype.setPage = function (page) {
977 if (page >= this.pages || page < 0 || page === this.state.page) {
978 return null;
979 }
980 this.setState({
981 page: page,
982 });
983 this.processor.setProps({
984 page: page,
985 });
986 };
987 Pagination.prototype.setTotal = function (totalRows) {
988 // to set the correct total number of rows
989 // when running in-memory operations
990 this.setState({
991 total: totalRows,
992 });
993 };
994 Pagination.prototype.renderPages = function () {
995 var _this = this;
996 if (this.props.buttonsCount <= 0) {
997 return null;
998 }
999 // how many pagination buttons to render?
1000 var maxCount = Math.min(this.pages, this.props.buttonsCount);
1001 var pagePivot = Math.min(this.state.page, Math.floor(maxCount / 2));
1002 if (this.state.page + Math.floor(maxCount / 2) >= this.pages) {
1003 pagePivot = maxCount - (this.pages - this.state.page);
1004 }
1005 return (v(p, null,
1006 this.pages > maxCount && this.state.page - pagePivot > 0 && (v(p, null,
1007 v("button", { tabIndex: 0, role: "button", onClick: this.setPage.bind(this, 0), title: this._('pagination.firstPage'), "aria-label": this._('pagination.firstPage'), className: this.config.className.paginationButton }, this._('1')),
1008 v("button", { tabIndex: -1, className: classJoin(className('spread'), this.config.className.paginationButton) }, "..."))),
1009 Array.from(Array(maxCount).keys())
1010 .map(function (i) { return _this.state.page + (i - pagePivot); })
1011 .map(function (i) { return (v("button", { tabIndex: 0, role: "button", onClick: _this.setPage.bind(_this, i), className: classJoin(_this.state.page === i
1012 ? classJoin(className('currentPage'), _this.config.className.paginationButtonCurrent)
1013 : null, _this.config.className.paginationButton), title: _this._('pagination.page', i + 1), "aria-label": _this._('pagination.page', i + 1) }, _this._("" + (i + 1)))); }),
1014 this.pages > maxCount && this.pages > this.state.page + pagePivot + 1 && (v(p, null,
1015 v("button", { tabIndex: -1, className: classJoin(className('spread'), this.config.className.paginationButton) }, "..."),
1016 v("button", { tabIndex: 0, role: "button", onClick: this.setPage.bind(this, this.pages - 1), title: this._('pagination.page', this.pages), "aria-label": this._('pagination.page', this.pages), className: this.config.className.paginationButton }, this._("" + this.pages))))));
1017 };
1018 Pagination.prototype.renderSummary = function () {
1019 return (v(p, null, this.props.summary && this.state.total > 0 && (v("div", { role: "status", "aria-live": "polite", className: classJoin(className('summary'), this.config.className.paginationSummary), title: this._('pagination.navigate', this.state.page + 1, this.pages) },
1020 this._('pagination.showing'),
1021 ' ',
1022 v("b", null, this._("" + (this.state.page * this.state.limit + 1))),
1023 ' ',
1024 this._('pagination.to'),
1025 ' ',
1026 v("b", null, this._("" + Math.min((this.state.page + 1) * this.state.limit, this.state.total))),
1027 ' ',
1028 this._('pagination.of'),
1029 " ",
1030 v("b", null, this._("" + this.state.total)),
1031 ' ',
1032 this._('pagination.results')))));
1033 };
1034 Pagination.prototype.render = function () {
1035 if (!this.props.enabled)
1036 return null;
1037 return (v("div", { className: classJoin(className('pagination'), this.config.className.pagination) },
1038 this.renderSummary(),
1039 v("div", { className: className('pages') },
1040 this.props.prevButton && (v("button", { tabIndex: 0, role: "button", disabled: this.state.page === 0, onClick: this.setPage.bind(this, this.state.page - 1), title: this._('pagination.previous'), "aria-label": this._('pagination.previous'), className: classJoin(this.config.className.paginationButton, this.config.className.paginationButtonPrev) }, this._('pagination.previous'))),
1041 this.renderPages(),
1042 this.props.nextButton && (v("button", { tabIndex: 0, role: "button", disabled: this.pages === this.state.page + 1 || this.pages === 0, onClick: this.setPage.bind(this, this.state.page + 1), title: this._('pagination.next'), "aria-label": this._('pagination.next'), className: classJoin(this.config.className.paginationButton, this.config.className.paginationButtonNext) }, this._('pagination.next'))))));
1043 };
1044 Pagination.defaultProps = {
1045 summary: true,
1046 nextButton: true,
1047 prevButton: true,
1048 buttonsCount: 3,
1049 limit: 10,
1050 resetPageOnUpdate: true,
1051 };
1052 return Pagination;
1053}(PluginBaseComponent));
1054
1055function width(width, containerWidth) {
1056 if (typeof width == 'string') {
1057 if (width.indexOf('%') > -1) {
1058 return (containerWidth / 100) * parseInt(width, 10);
1059 }
1060 else {
1061 return parseInt(width, 10);
1062 }
1063 }
1064 return width;
1065}
1066function px(width) {
1067 if (!width)
1068 return '';
1069 return Math.floor(width) + "px";
1070}
1071/**
1072 * Accepts a ShadowTable and tries to find the clientWidth
1073 * that is already rendered on the web browser
1074 *
1075 * @param shadowTable
1076 * @param columnId
1077 */
1078function getWidth(shadowTable, columnId) {
1079 if (!shadowTable) {
1080 return null;
1081 }
1082 var td = shadowTable.querySelector("thead th[data-column-id=\"" + columnId + "\"]");
1083 if (td) {
1084 return td.clientWidth;
1085 }
1086 return null;
1087}
1088
1089/**
1090 * ShadowTable renders a hidden table and is used to calculate the column's width
1091 * when autoWidth option is enabled
1092 */
1093var ShadowTable = /** @class */ (function (_super) {
1094 __extends(ShadowTable, _super);
1095 function ShadowTable() {
1096 return _super !== null && _super.apply(this, arguments) || this;
1097 }
1098 ShadowTable.prototype.render = function () {
1099 if (this.props.tableRef.current) {
1100 var tableRef = this.props.tableRef;
1101 var tableElement_1 = tableRef.current.base.cloneNode(true);
1102 tableElement_1.className += " " + className('shadowTable');
1103 tableElement_1.style.position = 'absolute';
1104 tableElement_1.style.zIndex = '-2147483640';
1105 tableElement_1.style.visibility = 'hidden';
1106 tableElement_1.style.tableLayout = 'auto';
1107 tableElement_1.style.width = 'auto';
1108 tableElement_1.style.padding = '0';
1109 tableElement_1.style.margin = '0';
1110 tableElement_1.style.border = 'none';
1111 tableElement_1.style.outline = 'none';
1112 return (v("div", { ref: function (nodeElement) {
1113 nodeElement && nodeElement.appendChild(tableElement_1);
1114 } }));
1115 }
1116 return null;
1117 };
1118 return ShadowTable;
1119}(BaseComponent));
1120
1121function camelCase(str) {
1122 if (!str)
1123 return '';
1124 var words = str.split(' ');
1125 // do not convert strings that are already in camelCase format
1126 if (words.length === 1 && /([a-z][A-Z])+/g.test(str)) {
1127 return str;
1128 }
1129 return words
1130 .map(function (word, index) {
1131 // if it is the first word, lowercase all the chars
1132 if (index == 0) {
1133 return word.toLowerCase();
1134 }
1135 // if it is not the first word only upper case the first char and lowercase the rest
1136 return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
1137 })
1138 .join('');
1139}
1140
1141var Header = /** @class */ (function (_super) {
1142 __extends(Header, _super);
1143 function Header() {
1144 var _this = _super.call(this) || this;
1145 _this._columns = [];
1146 return _this;
1147 }
1148 Object.defineProperty(Header.prototype, "columns", {
1149 get: function () {
1150 return this._columns;
1151 },
1152 set: function (columns) {
1153 this._columns = columns;
1154 },
1155 enumerable: false,
1156 configurable: true
1157 });
1158 /**
1159 * Tries to automatically adjust the width of columns based on:
1160 * - Header cell content
1161 * - Cell content of the first row
1162 * - Cell content of the last row
1163 *
1164 * @param container
1165 * @param tableRef
1166 * @param tempRef
1167 * @param autoWidth
1168 */
1169 Header.prototype.adjustWidth = function (container, tableRef, tempRef, autoWidth) {
1170 if (autoWidth === void 0) { autoWidth = true; }
1171 if (!container) {
1172 // we can't calculate the width because the container
1173 // is unknown at this stage
1174 return this;
1175 }
1176 // pixels
1177 var containerWidth = container.clientWidth;
1178 // let's create a shadow table with the first 10 rows of the data
1179 // and let the browser to render the table with table-layout: auto
1180 // no padding, margin or border to get the minimum space required
1181 // to render columns. One the table is rendered and widths are known,
1182 // we unmount the shadow table from the DOM and set the correct width
1183 var shadowTable = y();
1184 if (tableRef.current && autoWidth) {
1185 // render a ShadowTable with the first 10 rows
1186 var el = v(ShadowTable, {
1187 tableRef: tableRef,
1188 });
1189 el.ref = shadowTable;
1190 O(el, tempRef.current);
1191 }
1192 for (var _i = 0, _a = flatten(Header.tabularFormat(this.columns)); _i < _a.length; _i++) {
1193 var column = _a[_i];
1194 // because we don't want to set the width of parent THs
1195 if (column.columns && column.columns.length > 0) {
1196 continue;
1197 }
1198 if (!column.width && autoWidth) {
1199 // tries to find the corresponding cell
1200 // from the ShadowTable and set the correct width
1201 column.width = px(getWidth(shadowTable.current.base, column.id));
1202 }
1203 else {
1204 // column with is already defined
1205 // sets the column with based on the width of its container
1206 column.width = px(width(column.width, containerWidth));
1207 }
1208 }
1209 if (tableRef.current && autoWidth) {
1210 // unmount the shadow table from temp
1211 O(null, tempRef.current);
1212 }
1213 return this;
1214 };
1215 Header.prototype.setSort = function (userConfig, columns) {
1216 var cols = columns || this.columns || [];
1217 for (var _i = 0, cols_1 = cols; _i < cols_1.length; _i++) {
1218 var column = cols_1[_i];
1219 // sorting can only be enabled for columns without any children
1220 if (column.columns && column.columns.length > 0) {
1221 column.sort = {
1222 enabled: false,
1223 };
1224 }
1225 // implicit userConfig.sort flag
1226 if (column.sort === undefined && userConfig.sort) {
1227 column.sort = {
1228 enabled: true,
1229 };
1230 }
1231 // false, null, etc.
1232 if (!column.sort) {
1233 column.sort = {
1234 enabled: false,
1235 };
1236 }
1237 else if (typeof column.sort === 'object') {
1238 column.sort = __assign({ enabled: true }, column.sort);
1239 }
1240 if (column.columns) {
1241 this.setSort(userConfig, column.columns);
1242 }
1243 }
1244 };
1245 Header.prototype.setFixedHeader = function (userConfig, columns) {
1246 var cols = columns || this.columns || [];
1247 for (var _i = 0, cols_2 = cols; _i < cols_2.length; _i++) {
1248 var column = cols_2[_i];
1249 if (column.fixedHeader === undefined) {
1250 column.fixedHeader = userConfig.fixedHeader;
1251 }
1252 if (column.columns) {
1253 this.setFixedHeader(userConfig, column.columns);
1254 }
1255 }
1256 };
1257 Header.prototype.setID = function (columns) {
1258 var cols = columns || this.columns || [];
1259 for (var _i = 0, cols_3 = cols; _i < cols_3.length; _i++) {
1260 var column = cols_3[_i];
1261 if (!column.id && typeof column.name === 'string') {
1262 // let's guess the column ID if it's undefined
1263 column.id = camelCase(column.name);
1264 }
1265 if (!column.id) {
1266 log.error("Could not find a valid ID for one of the columns. Make sure a valid \"id\" is set for all columns.");
1267 }
1268 // nested columns
1269 if (column.columns) {
1270 this.setID(column.columns);
1271 }
1272 }
1273 };
1274 Header.prototype.populatePlugins = function (userConfig, columns) {
1275 // populate the cell columns
1276 for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {
1277 var column = columns_1[_i];
1278 if (column.plugin !== undefined) {
1279 userConfig.plugin.add(__assign(__assign({ id: column.id, props: {} }, column.plugin), { position: PluginPosition.Cell }));
1280 }
1281 }
1282 };
1283 Header.fromColumns = function (columns) {
1284 var header = new Header();
1285 for (var _i = 0, columns_2 = columns; _i < columns_2.length; _i++) {
1286 var column = columns_2[_i];
1287 if (typeof column === 'string' || l(column)) {
1288 header.columns.push({
1289 name: column,
1290 });
1291 }
1292 else if (typeof column === 'object') {
1293 var typedColumn = column;
1294 if (typedColumn.columns) {
1295 typedColumn.columns = Header.fromColumns(typedColumn.columns).columns;
1296 }
1297 // because the data for that cell is null
1298 // if we are trying to render a plugin
1299 if (typeof typedColumn.plugin === 'object') {
1300 if (typedColumn.data === undefined) {
1301 typedColumn.data = null;
1302 }
1303 }
1304 // TColumn type
1305 header.columns.push(column);
1306 }
1307 }
1308 return header;
1309 };
1310 Header.fromUserConfig = function (userConfig) {
1311 var header = new Header();
1312 // TODO: this part needs some refactoring
1313 if (userConfig.from) {
1314 header.columns = Header.fromHTMLTable(userConfig.from).columns;
1315 }
1316 else if (userConfig.columns) {
1317 header.columns = Header.fromColumns(userConfig.columns).columns;
1318 }
1319 else if (userConfig.data &&
1320 typeof userConfig.data[0] === 'object' &&
1321 !(userConfig.data[0] instanceof Array)) {
1322 // if data[0] is an object but not an Array
1323 // used for when a JSON payload is provided
1324 header.columns = Object.keys(userConfig.data[0]).map(function (name) {
1325 return { name: name };
1326 });
1327 }
1328 if (header.columns.length) {
1329 header.setID();
1330 header.setSort(userConfig);
1331 header.setFixedHeader(userConfig);
1332 header.populatePlugins(userConfig, header.columns);
1333 return header;
1334 }
1335 return null;
1336 };
1337 Header.fromHTMLTable = function (element) {
1338 var header = new Header();
1339 var thead = element.querySelector('thead');
1340 var ths = thead.querySelectorAll('th');
1341 for (var _i = 0, _a = ths; _i < _a.length; _i++) {
1342 var th = _a[_i];
1343 header.columns.push({
1344 name: th.innerHTML,
1345 width: th.width,
1346 });
1347 }
1348 return header;
1349 };
1350 /**
1351 * Converts the tree-like format of Header to a tabular format
1352 *
1353 * Example:
1354 *
1355 * H1
1356 * H1-H1
1357 * H1-H2
1358 * H2
1359 * H2-H1
1360 *
1361 * becomes:
1362 * [
1363 * [H1, H2],
1364 * [H1-H1, H1-H2, H2-H1]
1365 * ]
1366 *
1367 * @param columns
1368 */
1369 Header.tabularFormat = function (columns) {
1370 var result = [];
1371 var cols = columns || [];
1372 var nextRow = [];
1373 if (cols && cols.length) {
1374 result.push(cols);
1375 for (var _i = 0, cols_4 = cols; _i < cols_4.length; _i++) {
1376 var col = cols_4[_i];
1377 if (col.columns && col.columns.length) {
1378 nextRow = nextRow.concat(col.columns);
1379 }
1380 }
1381 if (nextRow.length) {
1382 result = result.concat(this.tabularFormat(nextRow));
1383 }
1384 }
1385 return result;
1386 };
1387 /**
1388 * Returns an array of leaf columns (last columns in the tree)
1389 *
1390 * @param columns
1391 */
1392 Header.leafColumns = function (columns) {
1393 var result = [];
1394 var cols = columns || [];
1395 if (cols && cols.length) {
1396 for (var _i = 0, cols_5 = cols; _i < cols_5.length; _i++) {
1397 var col = cols_5[_i];
1398 if (!col.columns || col.columns.length === 0) {
1399 result.push(col);
1400 }
1401 if (col.columns) {
1402 result = result.concat(this.leafColumns(col.columns));
1403 }
1404 }
1405 }
1406 return result;
1407 };
1408 /**
1409 * Returns the maximum depth of a column tree
1410 * @param column
1411 */
1412 Header.maximumDepth = function (column) {
1413 return this.tabularFormat([column]).length - 1;
1414 };
1415 return Header;
1416}(Base));
1417
1418var _prefix = 'ID_';
1419/**
1420 * This class is mostly based on Flux's Dispatcher by Facebook
1421 * https://github.com/facebook/flux/blob/master/src/Dispatcher.js
1422 */
1423var Dispatcher = /** @class */ (function () {
1424 function Dispatcher() {
1425 this._callbacks = {};
1426 this._isDispatching = false;
1427 this._isHandled = {};
1428 this._isPending = {};
1429 this._lastID = 1;
1430 }
1431 /**
1432 * Registers a callback to be invoked with every dispatched payload. Returns
1433 * a token that can be used with `waitFor()`.
1434 */
1435 Dispatcher.prototype.register = function (callback) {
1436 var id = _prefix + this._lastID++;
1437 this._callbacks[id] = callback;
1438 return id;
1439 };
1440 /**
1441 * Removes a callback based on its token.
1442 */
1443 Dispatcher.prototype.unregister = function (id) {
1444 if (!this._callbacks[id]) {
1445 throw Error("Dispatcher.unregister(...): " + id + " does not map to a registered callback.");
1446 }
1447 delete this._callbacks[id];
1448 };
1449 /**
1450 * Waits for the callbacks specified to be invoked before continuing execution
1451 * of the current callback. This method should only be used by a callback in
1452 * response to a dispatched payload.
1453 */
1454 Dispatcher.prototype.waitFor = function (ids) {
1455 if (!this._isDispatching) {
1456 throw Error('Dispatcher.waitFor(...): Must be invoked while dispatching.');
1457 }
1458 for (var ii = 0; ii < ids.length; ii++) {
1459 var id = ids[ii];
1460 if (this._isPending[id]) {
1461 if (!this._isHandled[id]) {
1462 throw Error("Dispatcher.waitFor(...): Circular dependency detected while ' +\n 'waiting for " + id + ".");
1463 }
1464 continue;
1465 }
1466 if (!this._callbacks[id]) {
1467 throw Error("Dispatcher.waitFor(...): " + id + " does not map to a registered callback.");
1468 }
1469 this._invokeCallback(id);
1470 }
1471 };
1472 /**
1473 * Dispatches a payload to all registered callbacks.
1474 */
1475 Dispatcher.prototype.dispatch = function (payload) {
1476 if (this._isDispatching) {
1477 throw Error('Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.');
1478 }
1479 this._startDispatching(payload);
1480 try {
1481 for (var id in this._callbacks) {
1482 if (this._isPending[id]) {
1483 continue;
1484 }
1485 this._invokeCallback(id);
1486 }
1487 }
1488 finally {
1489 this._stopDispatching();
1490 }
1491 };
1492 /**
1493 * Is this Dispatcher currently dispatching.
1494 */
1495 Dispatcher.prototype.isDispatching = function () {
1496 return this._isDispatching;
1497 };
1498 /**
1499 * Call the callback stored with the given id. Also do some internal
1500 * bookkeeping.
1501 *
1502 * @internal
1503 */
1504 Dispatcher.prototype._invokeCallback = function (id) {
1505 this._isPending[id] = true;
1506 this._callbacks[id](this._pendingPayload);
1507 this._isHandled[id] = true;
1508 };
1509 /**
1510 * Set up bookkeeping needed when dispatching.
1511 *
1512 * @internal
1513 */
1514 Dispatcher.prototype._startDispatching = function (payload) {
1515 for (var id in this._callbacks) {
1516 this._isPending[id] = false;
1517 this._isHandled[id] = false;
1518 }
1519 this._pendingPayload = payload;
1520 this._isDispatching = true;
1521 };
1522 /**
1523 * Clear bookkeeping used for dispatching.
1524 *
1525 * @internal
1526 */
1527 Dispatcher.prototype._stopDispatching = function () {
1528 delete this._pendingPayload;
1529 this._isDispatching = false;
1530 };
1531 return Dispatcher;
1532}());
1533
1534var Storage = /** @class */ (function () {
1535 function Storage() {
1536 }
1537 return Storage;
1538}());
1539
1540var MemoryStorage = /** @class */ (function (_super) {
1541 __extends(MemoryStorage, _super);
1542 function MemoryStorage(data) {
1543 var _this = _super.call(this) || this;
1544 _this.set(data);
1545 return _this;
1546 }
1547 MemoryStorage.prototype.get = function () {
1548 return __awaiter(this, void 0, void 0, function () {
1549 var data;
1550 return __generator(this, function (_a) {
1551 switch (_a.label) {
1552 case 0: return [4 /*yield*/, this.data()];
1553 case 1:
1554 data = _a.sent();
1555 return [2 /*return*/, {
1556 data: data,
1557 total: data.length,
1558 }];
1559 }
1560 });
1561 });
1562 };
1563 MemoryStorage.prototype.set = function (data) {
1564 if (data instanceof Array) {
1565 this.data = function () { return data; };
1566 }
1567 else if (data instanceof Function) {
1568 this.data = data;
1569 }
1570 return this;
1571 };
1572 return MemoryStorage;
1573}(Storage));
1574
1575var ServerStorage = /** @class */ (function (_super) {
1576 __extends(ServerStorage, _super);
1577 function ServerStorage(options) {
1578 var _this = _super.call(this) || this;
1579 _this.options = options;
1580 return _this;
1581 }
1582 ServerStorage.prototype.handler = function (response) {
1583 if (typeof this.options.handle === 'function') {
1584 return this.options.handle(response);
1585 }
1586 if (response.ok) {
1587 return response.json();
1588 }
1589 else {
1590 log.error("Could not fetch data: " + response.status + " - " + response.statusText, true);
1591 return null;
1592 }
1593 };
1594 ServerStorage.prototype.get = function (options) {
1595 // this.options is the initial config object
1596 // options is the runtime config passed by the pipeline (e.g. search component)
1597 var opts = __assign(__assign({}, this.options), options);
1598 // if `options.data` is provided, the current ServerStorage
1599 // implementation will be ignored and we let options.data to
1600 // handle the request. Useful when HTTP client needs to be
1601 // replaced with something else
1602 if (typeof opts.data === 'function') {
1603 return opts.data(opts);
1604 }
1605 return fetch(opts.url, opts)
1606 .then(this.handler.bind(this))
1607 .then(function (res) {
1608 return {
1609 data: opts.then(res),
1610 total: typeof opts.total === 'function' ? opts.total(res) : undefined,
1611 };
1612 });
1613 };
1614 return ServerStorage;
1615}(Storage));
1616
1617var StorageUtils = /** @class */ (function () {
1618 function StorageUtils() {
1619 }
1620 /**
1621 * Accepts the userConfig dict and tries to guess and return a Storage type
1622 *
1623 * @param userConfig
1624 */
1625 StorageUtils.createFromUserConfig = function (userConfig) {
1626 var storage = null;
1627 // `data` array is provided
1628 if (userConfig.data) {
1629 storage = new MemoryStorage(userConfig.data);
1630 }
1631 if (userConfig.from) {
1632 storage = new MemoryStorage(this.tableElementToArray(userConfig.from));
1633 // remove the source table element from the DOM
1634 userConfig.from.style.display = 'none';
1635 }
1636 if (userConfig.server) {
1637 storage = new ServerStorage(userConfig.server);
1638 }
1639 if (!storage) {
1640 log.error('Could not determine the storage type', true);
1641 }
1642 return storage;
1643 };
1644 /**
1645 * Accepts a HTML table element and converts it into a 2D array of data
1646 *
1647 * TODO: This function can be a step in the pipeline: Convert Table -> Load into a memory storage -> ...
1648 *
1649 * @param element
1650 */
1651 StorageUtils.tableElementToArray = function (element) {
1652 var arr = [];
1653 var tbody = element.querySelector('tbody');
1654 var rows = tbody.querySelectorAll('tr');
1655 for (var _i = 0, _a = rows; _i < _a.length; _i++) {
1656 var row = _a[_i];
1657 var cells = row.querySelectorAll('td');
1658 var parsedRow = [];
1659 for (var _b = 0, cells_1 = cells; _b < cells_1.length; _b++) {
1660 var cell = cells_1[_b];
1661 // try to capture a TD with single text element first
1662 if (cell.childNodes.length === 1 &&
1663 cell.childNodes[0].nodeType === Node.TEXT_NODE) {
1664 parsedRow.push(decode(cell.innerHTML));
1665 }
1666 else {
1667 parsedRow.push(html(cell.innerHTML));
1668 }
1669 }
1670 arr.push(parsedRow);
1671 }
1672 return arr;
1673 };
1674 return StorageUtils;
1675}());
1676
1677var Pipeline = /** @class */ (function (_super) {
1678 __extends(Pipeline, _super);
1679 function Pipeline(steps) {
1680 var _this = _super.call(this) || this;
1681 // available steps for this pipeline
1682 _this._steps = new Map();
1683 // used to cache the results of processors using their id field
1684 _this.cache = new Map();
1685 // keeps the index of the last updated processor in the registered
1686 // processors list and will be used to invalidate the cache
1687 // -1 means all new processors should be processed
1688 _this.lastProcessorIndexUpdated = -1;
1689 if (steps) {
1690 steps.forEach(function (step) { return _this.register(step); });
1691 }
1692 return _this;
1693 }
1694 /**
1695 * Clears the `cache` array
1696 */
1697 Pipeline.prototype.clearCache = function () {
1698 this.cache = new Map();
1699 this.lastProcessorIndexUpdated = -1;
1700 };
1701 /**
1702 * Registers a new processor
1703 *
1704 * @param processor
1705 * @param priority
1706 */
1707 Pipeline.prototype.register = function (processor, priority) {
1708 if (priority === void 0) { priority = null; }
1709 if (processor.type === null) {
1710 throw Error('Processor type is not defined');
1711 }
1712 // binding the propsUpdated callback to the Pipeline
1713 processor.on('propsUpdated', this.processorPropsUpdated.bind(this));
1714 this.addProcessorByPriority(processor, priority);
1715 this.afterRegistered(processor);
1716 };
1717 /**
1718 * Removes a processor from the list
1719 *
1720 * @param processor
1721 */
1722 Pipeline.prototype.unregister = function (processor) {
1723 if (!processor)
1724 return;
1725 var subSteps = this._steps.get(processor.type);
1726 if (subSteps && subSteps.length) {
1727 this._steps.set(processor.type, subSteps.filter(function (proc) { return proc != processor; }));
1728 this.emit('updated', processor);
1729 }
1730 };
1731 /**
1732 * Registers a new processor
1733 *
1734 * @param processor
1735 * @param priority
1736 */
1737 Pipeline.prototype.addProcessorByPriority = function (processor, priority) {
1738 var subSteps = this._steps.get(processor.type);
1739 if (!subSteps) {
1740 var newSubStep = [];
1741 this._steps.set(processor.type, newSubStep);
1742 subSteps = newSubStep;
1743 }
1744 if (priority === null || priority < 0) {
1745 subSteps.push(processor);
1746 }
1747 else {
1748 if (!subSteps[priority]) {
1749 // slot is empty
1750 subSteps[priority] = processor;
1751 }
1752 else {
1753 // slot is NOT empty
1754 var first = subSteps.slice(0, priority - 1);
1755 var second = subSteps.slice(priority + 1);
1756 this._steps.set(processor.type, first.concat(processor).concat(second));
1757 }
1758 }
1759 };
1760 Object.defineProperty(Pipeline.prototype, "steps", {
1761 /**
1762 * Flattens the _steps Map and returns a list of steps with their correct priorities
1763 */
1764 get: function () {
1765 var steps = [];
1766 for (var _i = 0, _a = this.getSortedProcessorTypes(); _i < _a.length; _i++) {
1767 var type = _a[_i];
1768 var subSteps = this._steps.get(type);
1769 if (subSteps && subSteps.length) {
1770 steps = steps.concat(subSteps);
1771 }
1772 }
1773 // to remove any undefined elements
1774 return steps.filter(function (s) { return s; });
1775 },
1776 enumerable: false,
1777 configurable: true
1778 });
1779 /**
1780 * Accepts ProcessType and returns an array of the registered processes
1781 * with the give type
1782 *
1783 * @param type
1784 */
1785 Pipeline.prototype.getStepsByType = function (type) {
1786 return this.steps.filter(function (process) { return process.type === type; });
1787 };
1788 /**
1789 * Returns a list of ProcessorType according to their priority
1790 */
1791 Pipeline.prototype.getSortedProcessorTypes = function () {
1792 return Object.keys(ProcessorType)
1793 .filter(function (key) { return !isNaN(Number(key)); })
1794 .map(function (key) { return Number(key); });
1795 };
1796 /**
1797 * Runs all registered processors based on their correct priority
1798 * and returns the final output after running all steps
1799 *
1800 * @param data
1801 */
1802 Pipeline.prototype.process = function (data) {
1803 return __awaiter(this, void 0, void 0, function () {
1804 var lastProcessorIndexUpdated, steps, prev, _i, steps_1, processor, processorIndex, e_1;
1805 return __generator(this, function (_a) {
1806 switch (_a.label) {
1807 case 0:
1808 lastProcessorIndexUpdated = this.lastProcessorIndexUpdated;
1809 steps = this.steps;
1810 prev = data;
1811 _a.label = 1;
1812 case 1:
1813 _a.trys.push([1, 7, , 8]);
1814 _i = 0, steps_1 = steps;
1815 _a.label = 2;
1816 case 2:
1817 if (!(_i < steps_1.length)) return [3 /*break*/, 6];
1818 processor = steps_1[_i];
1819 processorIndex = this.findProcessorIndexByID(processor.id);
1820 if (!(processorIndex >= lastProcessorIndexUpdated)) return [3 /*break*/, 4];
1821 return [4 /*yield*/, processor.process(prev)];
1822 case 3:
1823 // we should execute process() here since the last
1824 // updated processor was before "processor".
1825 // This is to ensure that we always have correct and up to date
1826 // data from processors and also to skip them when necessary
1827 prev = _a.sent();
1828 this.cache.set(processor.id, prev);
1829 return [3 /*break*/, 5];
1830 case 4:
1831 // cached results already exist
1832 prev = this.cache.get(processor.id);
1833 _a.label = 5;
1834 case 5:
1835 _i++;
1836 return [3 /*break*/, 2];
1837 case 6: return [3 /*break*/, 8];
1838 case 7:
1839 e_1 = _a.sent();
1840 log.error(e_1);
1841 // trigger the onError callback
1842 this.emit('error', prev);
1843 // rethrow
1844 throw e_1;
1845 case 8:
1846 // means the pipeline is up to date
1847 this.lastProcessorIndexUpdated = steps.length;
1848 // triggers the afterProcess callbacks with the results
1849 this.emit('afterProcess', prev);
1850 return [2 /*return*/, prev];
1851 }
1852 });
1853 });
1854 };
1855 /**
1856 * Returns the registered processor's index in _steps array
1857 *
1858 * @param processorID
1859 */
1860 Pipeline.prototype.findProcessorIndexByID = function (processorID) {
1861 return this.steps.findIndex(function (p) { return p.id == processorID; });
1862 };
1863 /**
1864 * Sets the last updates processors index locally
1865 * This is used to invalid or skip a processor in
1866 * the process() method
1867 */
1868 Pipeline.prototype.setLastProcessorIndex = function (processor) {
1869 var processorIndex = this.findProcessorIndexByID(processor.id);
1870 if (this.lastProcessorIndexUpdated > processorIndex) {
1871 this.lastProcessorIndexUpdated = processorIndex;
1872 }
1873 };
1874 Pipeline.prototype.processorPropsUpdated = function (processor) {
1875 this.setLastProcessorIndex(processor);
1876 this.emit('propsUpdated');
1877 this.emit('updated', processor);
1878 };
1879 Pipeline.prototype.afterRegistered = function (processor) {
1880 this.setLastProcessorIndex(processor);
1881 this.emit('afterRegister');
1882 this.emit('updated', processor);
1883 };
1884 return Pipeline;
1885}(EventEmitter));
1886
1887var StorageExtractor = /** @class */ (function (_super) {
1888 __extends(StorageExtractor, _super);
1889 function StorageExtractor() {
1890 return _super !== null && _super.apply(this, arguments) || this;
1891 }
1892 Object.defineProperty(StorageExtractor.prototype, "type", {
1893 get: function () {
1894 return ProcessorType.Extractor;
1895 },
1896 enumerable: false,
1897 configurable: true
1898 });
1899 StorageExtractor.prototype._process = function (opts) {
1900 return __awaiter(this, void 0, void 0, function () {
1901 return __generator(this, function (_a) {
1902 switch (_a.label) {
1903 case 0: return [4 /*yield*/, this.props.storage.get(opts)];
1904 case 1: return [2 /*return*/, _a.sent()];
1905 }
1906 });
1907 });
1908 };
1909 return StorageExtractor;
1910}(PipelineProcessor));
1911
1912var ArrayToTabularTransformer = /** @class */ (function (_super) {
1913 __extends(ArrayToTabularTransformer, _super);
1914 function ArrayToTabularTransformer() {
1915 return _super !== null && _super.apply(this, arguments) || this;
1916 }
1917 Object.defineProperty(ArrayToTabularTransformer.prototype, "type", {
1918 get: function () {
1919 return ProcessorType.Transformer;
1920 },
1921 enumerable: false,
1922 configurable: true
1923 });
1924 ArrayToTabularTransformer.prototype._process = function (arrayResponse) {
1925 var tabular = Tabular.fromArray(arrayResponse.data);
1926 // for server-side storage
1927 tabular.length = arrayResponse.total;
1928 return tabular;
1929 };
1930 return ArrayToTabularTransformer;
1931}(PipelineProcessor));
1932
1933var ServerInitiator = /** @class */ (function (_super) {
1934 __extends(ServerInitiator, _super);
1935 function ServerInitiator() {
1936 return _super !== null && _super.apply(this, arguments) || this;
1937 }
1938 Object.defineProperty(ServerInitiator.prototype, "type", {
1939 get: function () {
1940 return ProcessorType.Initiator;
1941 },
1942 enumerable: false,
1943 configurable: true
1944 });
1945 ServerInitiator.prototype._process = function () {
1946 return Object.entries(this.props.serverStorageOptions)
1947 .filter(function (_a) {
1948 var _ = _a[0], val = _a[1];
1949 return typeof val !== 'function';
1950 })
1951 .reduce(function (acc, _a) {
1952 var _b;
1953 var k = _a[0], v = _a[1];
1954 return (__assign(__assign({}, acc), (_b = {}, _b[k] = v, _b)));
1955 }, {});
1956 };
1957 return ServerInitiator;
1958}(PipelineProcessor));
1959
1960var StorageResponseToArrayTransformer = /** @class */ (function (_super) {
1961 __extends(StorageResponseToArrayTransformer, _super);
1962 function StorageResponseToArrayTransformer() {
1963 return _super !== null && _super.apply(this, arguments) || this;
1964 }
1965 Object.defineProperty(StorageResponseToArrayTransformer.prototype, "type", {
1966 get: function () {
1967 return ProcessorType.Transformer;
1968 },
1969 enumerable: false,
1970 configurable: true
1971 });
1972 StorageResponseToArrayTransformer.prototype.castData = function (data) {
1973 if (!data || !data.length) {
1974 return [];
1975 }
1976 if (!this.props.header || !this.props.header.columns) {
1977 return data;
1978 }
1979 var columns = Header.leafColumns(this.props.header.columns);
1980 // if it's a 2d array already
1981 if (data[0] instanceof Array) {
1982 return data.map(function (row) {
1983 var pad = 0;
1984 return columns.map(function (column, i) {
1985 // default `data` is provided for this column
1986 if (column.data !== undefined) {
1987 pad++;
1988 if (typeof column.data === 'function') {
1989 return column.data(row);
1990 }
1991 else {
1992 return column.data;
1993 }
1994 }
1995 return row[i - pad];
1996 });
1997 });
1998 }
1999 // if it's an array of objects (but not array of arrays, i.e JSON payload)
2000 if (typeof data[0] === 'object' && !(data[0] instanceof Array)) {
2001 return data.map(function (row) {
2002 return columns.map(function (column, i) {
2003 if (column.data !== undefined) {
2004 if (typeof column.data === 'function') {
2005 return column.data(row);
2006 }
2007 else {
2008 return column.data;
2009 }
2010 }
2011 else if (column.id) {
2012 return row[column.id];
2013 }
2014 else {
2015 log.error("Could not find the correct cell for column at position " + i + ".\n Make sure either 'id' or 'selector' is defined for all columns.");
2016 return null;
2017 }
2018 });
2019 });
2020 }
2021 return [];
2022 };
2023 StorageResponseToArrayTransformer.prototype._process = function (storageResponse) {
2024 return {
2025 data: this.castData(storageResponse.data),
2026 total: storageResponse.total,
2027 };
2028 };
2029 return StorageResponseToArrayTransformer;
2030}(PipelineProcessor));
2031
2032var PipelineUtils = /** @class */ (function () {
2033 function PipelineUtils() {
2034 }
2035 PipelineUtils.createFromConfig = function (config) {
2036 var pipeline = new Pipeline();
2037 if (config.storage instanceof ServerStorage) {
2038 pipeline.register(new ServerInitiator({
2039 serverStorageOptions: config.server,
2040 }));
2041 }
2042 pipeline.register(new StorageExtractor({ storage: config.storage }));
2043 pipeline.register(new StorageResponseToArrayTransformer({ header: config.header }));
2044 pipeline.register(new ArrayToTabularTransformer());
2045 return pipeline;
2046 };
2047 return PipelineUtils;
2048}());
2049
2050var Config = /** @class */ (function () {
2051 function Config(config) {
2052 Object.assign(this, __assign(__assign({}, Config.defaultConfig()), config));
2053 this._userConfig = {};
2054 }
2055 /**
2056 * Assigns `updatedConfig` keys to the current config file
2057 *
2058 * @param updatedConfig
2059 */
2060 Config.prototype.assign = function (updatedConfig) {
2061 for (var _i = 0, _a = Object.keys(updatedConfig); _i < _a.length; _i++) {
2062 var key = _a[_i];
2063 // because we don't want to update the _userConfig cache
2064 if (key === '_userConfig')
2065 continue;
2066 this[key] = updatedConfig[key];
2067 }
2068 return this;
2069 };
2070 /**
2071 * Updates the config from a UserConfig
2072 *
2073 * @param userConfig
2074 */
2075 Config.prototype.update = function (userConfig) {
2076 if (!userConfig)
2077 return this;
2078 this._userConfig = __assign(__assign({}, this._userConfig), userConfig);
2079 this.assign(Config.fromUserConfig(this._userConfig));
2080 return this;
2081 };
2082 Config.defaultConfig = function () {
2083 return {
2084 plugin: new PluginManager(),
2085 dispatcher: new Dispatcher(),
2086 tableRef: y(),
2087 tempRef: y(),
2088 width: '100%',
2089 height: 'auto',
2090 autoWidth: true,
2091 style: {},
2092 className: {},
2093 };
2094 };
2095 Config.fromUserConfig = function (userConfig) {
2096 var config = new Config(userConfig);
2097 // to set the initial _userConfig object
2098 config._userConfig = userConfig;
2099 // Sort
2100 if (typeof userConfig.sort === 'boolean' && userConfig.sort) {
2101 config.assign({
2102 sort: {
2103 multiColumn: true,
2104 },
2105 });
2106 }
2107 // Header
2108 config.assign({
2109 header: Header.fromUserConfig(config),
2110 });
2111 config.assign({
2112 storage: StorageUtils.createFromUserConfig(userConfig),
2113 });
2114 config.assign({
2115 pipeline: PipelineUtils.createFromConfig(config),
2116 });
2117 // Translator
2118 config.assign({
2119 translator: new Translator(userConfig.language),
2120 });
2121 // Search
2122 config.plugin.add({
2123 id: 'search',
2124 position: PluginPosition.Header,
2125 component: Search,
2126 props: __assign({ enabled: userConfig.search === true || userConfig.search instanceof Object }, userConfig.search),
2127 });
2128 // Pagination
2129 config.plugin.add({
2130 id: 'pagination',
2131 position: PluginPosition.Footer,
2132 component: Pagination,
2133 props: __assign({ enabled: userConfig.pagination === true ||
2134 userConfig.pagination instanceof Object }, userConfig.pagination),
2135 });
2136 // Additional plugins
2137 if (userConfig.plugins) {
2138 userConfig.plugins.forEach(function (p) { return config.plugin.add(p); });
2139 }
2140 return config;
2141 };
2142 return Config;
2143}());
2144
2145// container status
2146var Status;
2147(function (Status) {
2148 Status[Status["Init"] = 0] = "Init";
2149 Status[Status["Loading"] = 1] = "Loading";
2150 Status[Status["Loaded"] = 2] = "Loaded";
2151 Status[Status["Rendered"] = 3] = "Rendered";
2152 Status[Status["Error"] = 4] = "Error";
2153})(Status || (Status = {}));
2154
2155var TD = /** @class */ (function (_super) {
2156 __extends(TD, _super);
2157 function TD() {
2158 return _super !== null && _super.apply(this, arguments) || this;
2159 }
2160 TD.prototype.content = function () {
2161 if (this.props.column &&
2162 typeof this.props.column.formatter === 'function') {
2163 return this.props.column.formatter(this.props.cell.data, this.props.row, this.props.column);
2164 }
2165 if (this.props.column && this.props.column.plugin) {
2166 return (v(PluginRenderer, { pluginId: this.props.column.id, props: {
2167 column: this.props.column,
2168 cell: this.props.cell,
2169 row: this.props.row,
2170 } }));
2171 }
2172 return this.props.cell.data;
2173 };
2174 TD.prototype.handleClick = function (e) {
2175 if (this.props.messageCell)
2176 return;
2177 this.config.eventEmitter.emit('cellClick', e, this.props.cell, this.props.column, this.props.row);
2178 };
2179 TD.prototype.getCustomAttributes = function (column) {
2180 if (column) {
2181 if (typeof column.attributes === 'function') {
2182 return column.attributes(this.props.cell.data, this.props.row, this.props.column);
2183 }
2184 else {
2185 return column.attributes;
2186 }
2187 }
2188 return {};
2189 };
2190 TD.prototype.render = function () {
2191 return (v("td", __assign({ role: this.props.role, colSpan: this.props.colSpan, "data-column-id": this.props.column && this.props.column.id, className: classJoin(className('td'), this.props.className, this.config.className.td), style: __assign(__assign({}, this.props.style), this.config.style.td), onClick: this.handleClick.bind(this) }, this.getCustomAttributes(this.props.column)), this.content()));
2192 };
2193 return TD;
2194}(BaseComponent));
2195
2196var TR = /** @class */ (function (_super) {
2197 __extends(TR, _super);
2198 function TR() {
2199 return _super !== null && _super.apply(this, arguments) || this;
2200 }
2201 TR.prototype.getColumn = function (cellIndex) {
2202 if (this.props.header) {
2203 var cols = Header.leafColumns(this.props.header.columns);
2204 if (cols) {
2205 return cols[cellIndex];
2206 }
2207 }
2208 return null;
2209 };
2210 TR.prototype.handleClick = function (e) {
2211 if (this.props.messageRow)
2212 return;
2213 this.config.eventEmitter.emit('rowClick', e, this.props.row);
2214 };
2215 TR.prototype.getChildren = function () {
2216 var _this = this;
2217 if (this.props.children) {
2218 return this.props.children;
2219 }
2220 else {
2221 return (v(p, null, this.props.row.cells.map(function (cell, i) {
2222 var column = _this.getColumn(i);
2223 if (column && column.hidden)
2224 return null;
2225 return (v(TD, { key: cell.id, cell: cell, row: _this.props.row, column: column }));
2226 })));
2227 }
2228 };
2229 TR.prototype.render = function () {
2230 return (v("tr", { className: className('tr'), onClick: this.handleClick.bind(this) }, this.getChildren()));
2231 };
2232 return TR;
2233}(BaseComponent));
2234
2235var MessageRow = /** @class */ (function (_super) {
2236 __extends(MessageRow, _super);
2237 function MessageRow() {
2238 return _super !== null && _super.apply(this, arguments) || this;
2239 }
2240 MessageRow.prototype.render = function () {
2241 return (v(TR, { messageRow: true },
2242 v(TD, { role: "alert", colSpan: this.props.colSpan, messageCell: true, cell: new Cell(this.props.message), className: classJoin(className('message'), this.props.className ? this.props.className : null) })));
2243 };
2244 return MessageRow;
2245}(BaseComponent));
2246
2247var TBody = /** @class */ (function (_super) {
2248 __extends(TBody, _super);
2249 function TBody() {
2250 return _super !== null && _super.apply(this, arguments) || this;
2251 }
2252 TBody.prototype.headerLength = function () {
2253 if (this.props.header) {
2254 return this.props.header.columns.length;
2255 }
2256 return 0;
2257 };
2258 TBody.prototype.render = function () {
2259 var _this = this;
2260 return (v("tbody", { className: classJoin(className('tbody'), this.config.className.tbody) },
2261 this.props.data &&
2262 this.props.data.rows.map(function (row) {
2263 return v(TR, { key: row.id, row: row, header: _this.props.header });
2264 }),
2265 this.props.status === Status.Loading &&
2266 (!this.props.data || this.props.data.length === 0) && (v(MessageRow, { message: this._('loading'), colSpan: this.headerLength(), className: classJoin(className('loading'), this.config.className.loading) })),
2267 this.props.status === Status.Rendered &&
2268 this.props.data &&
2269 this.props.data.length === 0 && (v(MessageRow, { message: this._('noRecordsFound'), colSpan: this.headerLength(), className: classJoin(className('notfound'), this.config.className.notfound) })),
2270 this.props.status === Status.Error && (v(MessageRow, { message: this._('error'), colSpan: this.headerLength(), className: classJoin(className('error'), this.config.className.error) }))));
2271 };
2272 return TBody;
2273}(BaseComponent));
2274
2275var NativeSort = /** @class */ (function (_super) {
2276 __extends(NativeSort, _super);
2277 function NativeSort() {
2278 return _super !== null && _super.apply(this, arguments) || this;
2279 }
2280 NativeSort.prototype.validateProps = function () {
2281 for (var _i = 0, _a = this.props.columns; _i < _a.length; _i++) {
2282 var condition = _a[_i];
2283 if (condition.direction === undefined) {
2284 condition.direction = 1;
2285 }
2286 if (condition.direction !== 1 && condition.direction !== -1) {
2287 log.error("Invalid sort direction " + condition.direction);
2288 }
2289 }
2290 };
2291 Object.defineProperty(NativeSort.prototype, "type", {
2292 get: function () {
2293 return ProcessorType.Sort;
2294 },
2295 enumerable: false,
2296 configurable: true
2297 });
2298 NativeSort.prototype.compare = function (cellA, cellB) {
2299 if (cellA > cellB) {
2300 return 1;
2301 }
2302 else if (cellA < cellB) {
2303 return -1;
2304 }
2305 return 0;
2306 };
2307 NativeSort.prototype.compareWrapper = function (a, b) {
2308 var cmp = 0;
2309 for (var _i = 0, _a = this.props.columns; _i < _a.length; _i++) {
2310 var column = _a[_i];
2311 if (cmp === 0) {
2312 var cellA = a.cells[column.index].data;
2313 var cellB = b.cells[column.index].data;
2314 if (typeof column.compare === 'function') {
2315 cmp |= column.compare(cellA, cellB) * column.direction;
2316 }
2317 else {
2318 cmp |= this.compare(cellA, cellB) * column.direction;
2319 }
2320 }
2321 else {
2322 break;
2323 }
2324 }
2325 return cmp;
2326 };
2327 NativeSort.prototype._process = function (data) {
2328 var sortedRows = __spreadArrays(data.rows);
2329 sortedRows.sort(this.compareWrapper.bind(this));
2330 var sorted = new Tabular(sortedRows);
2331 // we have to set the tabular length manually
2332 // because of the server-side storage
2333 sorted.length = data.length;
2334 return sorted;
2335 };
2336 return NativeSort;
2337}(PipelineProcessor));
2338
2339var SortStore = /** @class */ (function (_super) {
2340 __extends(SortStore, _super);
2341 function SortStore() {
2342 return _super !== null && _super.apply(this, arguments) || this;
2343 }
2344 SortStore.prototype.getInitialState = function () {
2345 return [];
2346 };
2347 SortStore.prototype.handle = function (type, payload) {
2348 if (type === 'SORT_COLUMN') {
2349 var index = payload.index, direction = payload.direction, multi = payload.multi, compare = payload.compare;
2350 this.sortColumn(index, direction, multi, compare);
2351 }
2352 else if (type === 'SORT_COLUMN_TOGGLE') {
2353 var index = payload.index, multi = payload.multi, compare = payload.compare;
2354 this.sortToggle(index, multi, compare);
2355 }
2356 };
2357 SortStore.prototype.sortToggle = function (index, multi, compare) {
2358 var columns = __spreadArrays(this.state);
2359 var column = columns.find(function (x) { return x.index === index; });
2360 if (!column) {
2361 this.sortColumn(index, 1, multi, compare);
2362 }
2363 else {
2364 this.sortColumn(index, column.direction === 1 ? -1 : 1, multi, compare);
2365 }
2366 };
2367 SortStore.prototype.sortColumn = function (index, direction, multi, compare) {
2368 var columns = __spreadArrays(this.state);
2369 var count = columns.length;
2370 var column = columns.find(function (x) { return x.index === index; });
2371 var exists = column !== undefined;
2372 var add = false;
2373 var reset = false;
2374 var remove = false;
2375 var update = false;
2376 if (!exists) {
2377 // the column has not been sorted
2378 if (count === 0) {
2379 // the first column to be sorted
2380 add = true;
2381 }
2382 else if (count > 0 && !multi) {
2383 // remove the previously sorted column
2384 // and sort the current column
2385 add = true;
2386 reset = true;
2387 }
2388 else if (count > 0 && multi) {
2389 // multi-sorting
2390 // sort this column as well
2391 add = true;
2392 }
2393 }
2394 else {
2395 // the column has been sorted before
2396 if (!multi) {
2397 // single column sorting
2398 if (count === 1) {
2399 update = true;
2400 }
2401 else if (count > 1) {
2402 // this situation happens when we have already entered
2403 // multi-sorting mode but then user tries to sort a single column
2404 reset = true;
2405 add = true;
2406 }
2407 }
2408 else {
2409 // multi sorting
2410 if (column.direction === -1) {
2411 // remove the current column from the
2412 // sorted columns array
2413 remove = true;
2414 }
2415 else {
2416 update = true;
2417 }
2418 }
2419 }
2420 if (reset) {
2421 // resetting the sorted columns
2422 columns = [];
2423 }
2424 if (add) {
2425 columns.push({
2426 index: index,
2427 direction: direction,
2428 compare: compare,
2429 });
2430 }
2431 else if (update) {
2432 var index_1 = columns.indexOf(column);
2433 columns[index_1].direction = direction;
2434 }
2435 else if (remove) {
2436 var index_2 = columns.indexOf(column);
2437 columns.splice(index_2, 1);
2438 }
2439 this.setState(columns);
2440 };
2441 return SortStore;
2442}(BaseStore));
2443
2444var SortActions = /** @class */ (function (_super) {
2445 __extends(SortActions, _super);
2446 function SortActions() {
2447 return _super !== null && _super.apply(this, arguments) || this;
2448 }
2449 SortActions.prototype.sortColumn = function (index, direction, multi, compare) {
2450 this.dispatch('SORT_COLUMN', {
2451 index: index,
2452 direction: direction,
2453 multi: multi,
2454 compare: compare,
2455 });
2456 };
2457 SortActions.prototype.sortToggle = function (index, multi, compare) {
2458 this.dispatch('SORT_COLUMN_TOGGLE', {
2459 index: index,
2460 multi: multi,
2461 compare: compare,
2462 });
2463 };
2464 return SortActions;
2465}(BaseActions));
2466
2467var ServerSort = /** @class */ (function (_super) {
2468 __extends(ServerSort, _super);
2469 function ServerSort() {
2470 return _super !== null && _super.apply(this, arguments) || this;
2471 }
2472 Object.defineProperty(ServerSort.prototype, "type", {
2473 get: function () {
2474 return ProcessorType.ServerSort;
2475 },
2476 enumerable: false,
2477 configurable: true
2478 });
2479 ServerSort.prototype._process = function (options) {
2480 var updates = {};
2481 if (this.props.url) {
2482 updates['url'] = this.props.url(options.url, this.props.columns);
2483 }
2484 if (this.props.body) {
2485 updates['body'] = this.props.body(options.body, this.props.columns);
2486 }
2487 return __assign(__assign({}, options), updates);
2488 };
2489 return ServerSort;
2490}(PipelineProcessor));
2491
2492var Sort = /** @class */ (function (_super) {
2493 __extends(Sort, _super);
2494 function Sort(props, context) {
2495 var _this = _super.call(this, props, context) || this;
2496 _this.actions = new SortActions(_this.config.dispatcher);
2497 _this.store = new SortStore(_this.config.dispatcher);
2498 if (props.enabled) {
2499 _this.sortProcessor = _this.getOrCreateSortProcessor();
2500 _this.updateStateFn = _this.updateState.bind(_this);
2501 _this.store.on('updated', _this.updateStateFn);
2502 _this.state = { direction: 0 };
2503 }
2504 return _this;
2505 }
2506 Sort.prototype.componentWillUnmount = function () {
2507 this.config.pipeline.unregister(this.sortProcessor);
2508 this.store.off('updated', this.updateStateFn);
2509 if (this.updateSortProcessorFn)
2510 this.store.off('updated', this.updateSortProcessorFn);
2511 };
2512 /**
2513 * Sets the internal state of component
2514 */
2515 Sort.prototype.updateState = function () {
2516 var _this = this;
2517 var currentColumn = this.store.state.find(function (x) { return x.index === _this.props.index; });
2518 if (!currentColumn) {
2519 this.setState({
2520 direction: 0,
2521 });
2522 }
2523 else {
2524 this.setState({
2525 direction: currentColumn.direction,
2526 });
2527 }
2528 };
2529 Sort.prototype.updateSortProcessor = function (sortedColumns) {
2530 // updates the Sorting processor
2531 this.sortProcessor.setProps({
2532 columns: sortedColumns,
2533 });
2534 };
2535 Sort.prototype.getOrCreateSortProcessor = function () {
2536 var processorType = ProcessorType.Sort;
2537 if (this.config.sort && typeof this.config.sort.server === 'object') {
2538 processorType = ProcessorType.ServerSort;
2539 }
2540 var processors = this.config.pipeline.getStepsByType(processorType);
2541 // my assumption is that we only have ONE sorting processor in the
2542 // entire pipeline and that's why I'm displaying a warning here
2543 var processor;
2544 // A sort process is already registered
2545 if (processors.length > 0) {
2546 processor = processors[0];
2547 }
2548 else {
2549 // let's create a new sort processor
2550 // this event listener is here because
2551 // we want to subscribe to the sort store only once
2552 this.updateSortProcessorFn = this.updateSortProcessor.bind(this);
2553 this.store.on('updated', this.updateSortProcessorFn);
2554 if (processorType === ProcessorType.ServerSort) {
2555 processor = new ServerSort(__assign({ columns: this.store.state }, this.config.sort.server));
2556 }
2557 else {
2558 processor = new NativeSort({
2559 columns: this.store.state,
2560 });
2561 }
2562 this.config.pipeline.register(processor);
2563 }
2564 return processor;
2565 };
2566 Sort.prototype.changeDirection = function (e) {
2567 e.preventDefault();
2568 e.stopPropagation();
2569 // to sort two or more columns at the same time
2570 this.actions.sortToggle(this.props.index, e.shiftKey === true && this.config.sort.multiColumn, this.props.compare);
2571 };
2572 Sort.prototype.render = function () {
2573 if (!this.props.enabled) {
2574 return null;
2575 }
2576 var direction = this.state.direction;
2577 var sortClassName = 'neutral';
2578 if (direction === 1) {
2579 sortClassName = 'asc';
2580 }
2581 else if (direction === -1) {
2582 sortClassName = 'desc';
2583 }
2584 return (v("button", {
2585 // because the corresponding <th> has tabIndex=0
2586 tabIndex: -1, "aria-label": this._("sort.sort" + (direction === 1 ? 'Desc' : 'Asc')), title: this._("sort.sort" + (direction === 1 ? 'Desc' : 'Asc')), className: classJoin(className('sort'), className('sort', sortClassName), this.config.className.sort), onClick: this.changeDirection.bind(this) }));
2587 };
2588 return Sort;
2589}(BaseComponent));
2590
2591var TH = /** @class */ (function (_super) {
2592 __extends(TH, _super);
2593 function TH(props, context) {
2594 var _this = _super.call(this, props, context) || this;
2595 _this.sortRef = y();
2596 _this.thRef = y();
2597 _this.state = {
2598 style: {},
2599 };
2600 return _this;
2601 }
2602 TH.prototype.isSortable = function () {
2603 return this.props.column.sort.enabled;
2604 };
2605 TH.prototype.onClick = function (e) {
2606 e.stopPropagation();
2607 if (this.isSortable()) {
2608 this.sortRef.current.changeDirection(e);
2609 }
2610 };
2611 TH.prototype.keyDown = function (e) {
2612 if (this.isSortable() && e.which === 13) {
2613 this.onClick(e);
2614 }
2615 };
2616 TH.prototype.componentDidMount = function () {
2617 var _this = this;
2618 setTimeout(function () {
2619 // sets the `top` style if the current TH is fixed
2620 if (_this.props.column.fixedHeader && _this.thRef.current) {
2621 var offsetTop = _this.thRef.current.offsetTop;
2622 if (typeof offsetTop === 'number') {
2623 _this.setState({
2624 style: {
2625 top: offsetTop,
2626 },
2627 });
2628 }
2629 }
2630 }, 0);
2631 };
2632 TH.prototype.content = function () {
2633 if (this.props.column.name !== undefined) {
2634 return this.props.column.name;
2635 }
2636 if (this.props.column.plugin !== undefined) {
2637 return (v(PluginRenderer, { pluginId: this.props.column.plugin.id, props: {
2638 column: this.props.column,
2639 } }));
2640 }
2641 return null;
2642 };
2643 TH.prototype.render = function () {
2644 var props = {};
2645 if (this.isSortable()) {
2646 props['tabIndex'] = 0;
2647 }
2648 return (v("th", __assign({ ref: this.thRef, "data-column-id": this.props.column && this.props.column.id, className: classJoin(className('th'), this.isSortable() ? className('th', 'sort') : null, this.props.column.fixedHeader ? className('th', 'fixed') : null, this.config.className.th), onClick: this.onClick.bind(this), style: __assign(__assign(__assign(__assign({}, this.config.style.th), { width: this.props.column.width }), this.state.style), this.props.style), onKeyDown: this.keyDown.bind(this), rowSpan: this.props.rowSpan > 1 ? this.props.rowSpan : undefined, colSpan: this.props.colSpan > 1 ? this.props.colSpan : undefined }, props),
2649 this.content(),
2650 this.isSortable() && (v(Sort, __assign({ ref: this.sortRef, index: this.props.index }, this.props.column.sort)))));
2651 };
2652 return TH;
2653}(BaseComponent));
2654
2655function calculateRowColSpans(column, rowIndex, totalRows) {
2656 var depth = Header.maximumDepth(column);
2657 var remainingRows = totalRows - rowIndex;
2658 var rowSpan = Math.floor(remainingRows - depth - depth / remainingRows);
2659 var colSpan = (column.columns && column.columns.length) || 1;
2660 return {
2661 rowSpan: rowSpan,
2662 colSpan: colSpan,
2663 };
2664}
2665
2666var THead = /** @class */ (function (_super) {
2667 __extends(THead, _super);
2668 function THead() {
2669 return _super !== null && _super.apply(this, arguments) || this;
2670 }
2671 THead.prototype.renderColumn = function (column, rowIndex, columnIndex, totalRows) {
2672 var _a = calculateRowColSpans(column, rowIndex, totalRows), rowSpan = _a.rowSpan, colSpan = _a.colSpan;
2673 return (v(TH, { column: column, index: columnIndex, colSpan: colSpan, rowSpan: rowSpan }));
2674 };
2675 THead.prototype.renderRow = function (row, rowIndex, totalRows) {
2676 var _this = this;
2677 // because the only sortable columns are leaf columns (not parents)
2678 var leafColumns = Header.leafColumns(this.props.header.columns);
2679 return (v(TR, null, row.map(function (col) {
2680 if (col.hidden)
2681 return null;
2682 return _this.renderColumn(col, rowIndex, leafColumns.indexOf(col), totalRows);
2683 })));
2684 };
2685 THead.prototype.renderRows = function () {
2686 var _this = this;
2687 var rows = Header.tabularFormat(this.props.header.columns);
2688 return rows.map(function (row, rowIndex) {
2689 return _this.renderRow(row, rowIndex, rows.length);
2690 });
2691 };
2692 THead.prototype.render = function () {
2693 if (this.props.header) {
2694 return (v("thead", { key: this.props.header.id, className: classJoin(className('thead'), this.config.className.thead) }, this.renderRows()));
2695 }
2696 return null;
2697 };
2698 return THead;
2699}(BaseComponent));
2700
2701var Table = /** @class */ (function (_super) {
2702 __extends(Table, _super);
2703 function Table() {
2704 return _super !== null && _super.apply(this, arguments) || this;
2705 }
2706 Table.prototype.render = function () {
2707 return (v("table", { role: "grid", className: classJoin(className('table'), this.config.className.table), style: __assign(__assign({}, this.config.style.table), {
2708 width: this.props.width,
2709 height: this.props.height,
2710 }) },
2711 v(THead, { header: this.props.header }),
2712 v(TBody, { data: this.props.data, status: this.props.status, header: this.props.header })));
2713 };
2714 return Table;
2715}(BaseComponent));
2716
2717var HeaderContainer = /** @class */ (function (_super) {
2718 __extends(HeaderContainer, _super);
2719 function HeaderContainer(props, context) {
2720 var _this = _super.call(this, props, context) || this;
2721 _this.headerRef = y();
2722 _this.state = {
2723 isActive: true,
2724 };
2725 return _this;
2726 }
2727 HeaderContainer.prototype.componentDidMount = function () {
2728 if (this.headerRef.current.children.length === 0) {
2729 this.setState({
2730 isActive: false,
2731 });
2732 }
2733 };
2734 HeaderContainer.prototype.render = function () {
2735 if (this.state.isActive) {
2736 return (v("div", { ref: this.headerRef, className: classJoin(className('head'), this.config.className.header), style: __assign({}, this.config.style.header) },
2737 v(PluginRenderer, { position: PluginPosition.Header })));
2738 }
2739 return null;
2740 };
2741 return HeaderContainer;
2742}(BaseComponent));
2743
2744var FooterContainer = /** @class */ (function (_super) {
2745 __extends(FooterContainer, _super);
2746 function FooterContainer(props, context) {
2747 var _this = _super.call(this, props, context) || this;
2748 _this.footerRef = y();
2749 _this.state = {
2750 isActive: true,
2751 };
2752 return _this;
2753 }
2754 FooterContainer.prototype.componentDidMount = function () {
2755 if (this.footerRef.current.children.length === 0) {
2756 this.setState({
2757 isActive: false,
2758 });
2759 }
2760 };
2761 FooterContainer.prototype.render = function () {
2762 if (this.state.isActive) {
2763 return (v("div", { ref: this.footerRef, className: classJoin(className('footer'), this.config.className.footer), style: __assign({}, this.config.style.footer) },
2764 v(PluginRenderer, { position: PluginPosition.Footer })));
2765 }
2766 return null;
2767 };
2768 return FooterContainer;
2769}(BaseComponent));
2770
2771var Container = /** @class */ (function (_super) {
2772 __extends(Container, _super);
2773 function Container(props, context) {
2774 var _this = _super.call(this, props, context) || this;
2775 // global Config context which is passed to all components
2776 _this.configContext = B(null);
2777 _this.state = {
2778 status: Status.Loading,
2779 header: props.header,
2780 data: null,
2781 };
2782 return _this;
2783 }
2784 Container.prototype.processPipeline = function () {
2785 return __awaiter(this, void 0, void 0, function () {
2786 var data, e_1;
2787 return __generator(this, function (_a) {
2788 switch (_a.label) {
2789 case 0:
2790 this.props.config.eventEmitter.emit('beforeLoad');
2791 this.setState({
2792 status: Status.Loading,
2793 });
2794 _a.label = 1;
2795 case 1:
2796 _a.trys.push([1, 3, , 4]);
2797 return [4 /*yield*/, this.props.pipeline.process()];
2798 case 2:
2799 data = _a.sent();
2800 this.setState({
2801 data: data,
2802 status: Status.Loaded,
2803 });
2804 this.props.config.eventEmitter.emit('load', data);
2805 return [3 /*break*/, 4];
2806 case 3:
2807 e_1 = _a.sent();
2808 log.error(e_1);
2809 this.setState({
2810 status: Status.Error,
2811 data: null,
2812 });
2813 return [3 /*break*/, 4];
2814 case 4: return [2 /*return*/];
2815 }
2816 });
2817 });
2818 };
2819 Container.prototype.componentDidMount = function () {
2820 return __awaiter(this, void 0, void 0, function () {
2821 var config;
2822 return __generator(this, function (_a) {
2823 switch (_a.label) {
2824 case 0:
2825 config = this.props.config;
2826 // for the initial load
2827 return [4 /*yield*/, this.processPipeline()];
2828 case 1:
2829 // for the initial load
2830 _a.sent();
2831 if (config.header && this.state.data && this.state.data.length) {
2832 // now that we have the data, let's adjust columns width
2833 // NOTE: that we only calculate the columns width once
2834 this.setState({
2835 header: config.header.adjustWidth(config.container, config.tableRef, config.tempRef, config.autoWidth),
2836 });
2837 }
2838 this.processPipelineFn = this.processPipeline.bind(this);
2839 this.props.pipeline.on('updated', this.processPipelineFn);
2840 return [2 /*return*/];
2841 }
2842 });
2843 });
2844 };
2845 Container.prototype.componentWillUnmount = function () {
2846 this.props.pipeline.off('updated', this.processPipelineFn);
2847 };
2848 Container.prototype.componentDidUpdate = function (_, previousState) {
2849 // we can't jump to the Status.Rendered if previous status is not Status.Loaded
2850 if (previousState.status != Status.Rendered &&
2851 this.state.status == Status.Loaded) {
2852 this.setState({
2853 status: Status.Rendered,
2854 });
2855 this.props.config.eventEmitter.emit('ready');
2856 }
2857 };
2858 Container.prototype.render = function () {
2859 var configContext = this.configContext;
2860 return (v(configContext.Provider, { value: this.props.config },
2861 v("div", { role: "complementary", className: classJoin('gridjs', className('container'), this.state.status === Status.Loading ? className('loading') : null, this.props.config.className.container), style: __assign(__assign({}, this.props.config.style.container), {
2862 width: this.props.width,
2863 }) },
2864 this.state.status === Status.Loading && (v("div", { className: className('loading-bar') })),
2865 v(HeaderContainer, null),
2866 v("div", { className: className('wrapper'), style: { width: this.props.width, height: this.props.height } },
2867 v(Table, { ref: this.props.config.tableRef, data: this.state.data, header: this.state.header, width: this.props.width, height: this.props.height, status: this.state.status })),
2868 v(FooterContainer, null)),
2869 v("div", { ref: this.props.config.tempRef, id: "gridjs-temp", className: className('temp') })));
2870 };
2871 return Container;
2872}(BaseComponent));
2873
2874var Grid = /** @class */ (function (_super) {
2875 __extends(Grid, _super);
2876 function Grid(userConfig) {
2877 var _this = _super.call(this) || this;
2878 _this.config = new Config({ instance: _this, eventEmitter: _this }).update(userConfig);
2879 _this.plugin = _this.config.plugin;
2880 return _this;
2881 }
2882 Grid.prototype.updateConfig = function (userConfig) {
2883 this.config.update(userConfig);
2884 return this;
2885 };
2886 Grid.prototype.createElement = function () {
2887 return v(Container, {
2888 config: this.config,
2889 pipeline: this.config.pipeline,
2890 header: this.config.header,
2891 width: this.config.width,
2892 height: this.config.height,
2893 });
2894 };
2895 /**
2896 * Uses the existing container and tries to clear the cache
2897 * and re-render the existing Grid.js instance again. This is
2898 * useful when a new config is set/updated.
2899 *
2900 */
2901 Grid.prototype.forceRender = function () {
2902 if (!this.config || !this.config.container) {
2903 log.error('Container is empty. Make sure you call render() before forceRender()', true);
2904 }
2905 // clear the pipeline cache
2906 this.config.pipeline.clearCache();
2907 // TODO: not sure if it's a good idea to render a null element but I couldn't find a better way
2908 O(null, this.config.container);
2909 O(this.createElement(), this.config.container);
2910 return this;
2911 };
2912 /**
2913 * Mounts the Grid.js instance to the container
2914 * and renders the instance
2915 *
2916 * @param container
2917 */
2918 Grid.prototype.render = function (container) {
2919 if (!container) {
2920 log.error('Container element cannot be null', true);
2921 }
2922 if (container.childNodes.length > 0) {
2923 log.error("The container element " + container + " is not empty. Make sure the container is empty and call render() again");
2924 return this;
2925 }
2926 this.config.container = container;
2927 O(this.createElement(), container);
2928 return this;
2929 };
2930 return Grid;
2931}(EventEmitter));
2932
2933var t$1,u$1,r$1,o$1=0,i$1=[],c$1=n.__b,f$1=n.__r,e$1=n.diffed,a$1=n.__c,v$1=n.unmount;function m$1(t,r){n.__h&&n.__h(u$1,t,o$1||r),o$1=0;var i=u$1.__H||(u$1.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function y$1(r,o){var i=m$1(t$1++,3);!n.__s&&k$1(i.__H,o)&&(i.__=r,i.__H=o,u$1.__H.__h.push(i));}function s$1(n){return o$1=5,d$1(function(){return {current:n}},[])}function d$1(n,u){var r=m$1(t$1++,7);return k$1(r.__H,u)&&(r.__=n(),r.__H=u,r.__h=n),r.__}function x(){i$1.forEach(function(t){if(t.__P)try{t.__H.__h.forEach(g$1),t.__H.__h.forEach(j$1),t.__H.__h=[];}catch(u){t.__H.__h=[],n.__e(u,t.__v);}}),i$1=[];}n.__b=function(n){u$1=null,c$1&&c$1(n);},n.__r=function(n){f$1&&f$1(n),t$1=0;var r=(u$1=n.__c).__H;r&&(r.__h.forEach(g$1),r.__h.forEach(j$1),r.__h=[]);},n.diffed=function(t){e$1&&e$1(t);var o=t.__c;o&&o.__H&&o.__H.__h.length&&(1!==i$1.push(o)&&r$1===n.requestAnimationFrame||((r$1=n.requestAnimationFrame)||function(n){var t,u=function(){clearTimeout(r),b$1&&cancelAnimationFrame(t),setTimeout(n);},r=setTimeout(u,100);b$1&&(t=requestAnimationFrame(u));})(x)),u$1=void 0;},n.__c=function(t,u){u.some(function(t){try{t.__h.forEach(g$1),t.__h=t.__h.filter(function(n){return !n.__||j$1(n)});}catch(r){u.some(function(n){n.__h&&(n.__h=[]);}),u=[],n.__e(r,t.__v);}}),a$1&&a$1(t,u);},n.unmount=function(t){v$1&&v$1(t);var u=t.__c;if(u&&u.__H)try{u.__H.__.forEach(g$1);}catch(t){n.__e(t,u.__v);}};var b$1="function"==typeof requestAnimationFrame;function g$1(n){var t=u$1;"function"==typeof n.__c&&n.__c(),u$1=t;}function j$1(n){var t=u$1;n.__c=n.__(),u$1=t;}function k$1(n,t){return !n||n.length!==t.length||t.some(function(t,u){return t!==n[u]})}
2934
2935export { BaseActions, BaseComponent, BaseStore, Cell, d as Component, Config, Dispatcher, Grid, PluginBaseComponent, PluginPosition, Row, className, v as createElement, y as createRef, v as h, html, y$1 as useEffect, s$1 as useRef };
2936//# sourceMappingURL=gridjs.development.es.js.map