UNPKG

106 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 (b.hasOwnProperty(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
87function generateID() {
88 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
89 var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
90 return v.toString(16);
91 });
92}
93
94var Base = /** @class */ (function () {
95 function Base(id) {
96 this._id = id || generateID();
97 }
98 Object.defineProperty(Base.prototype, "id", {
99 get: function () {
100 return this._id;
101 },
102 enumerable: false,
103 configurable: true
104 });
105 return Base;
106}());
107
108var n,l,u,i,t,r,o,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=arguments,r={};for(i in l)"key"!==i&&"ref"!==i&&(r[i]=l[i]);if(arguments.length>3)for(u=[u],i=3;i<arguments.length;i++)u.push(t[i]);if(null!=u&&(r.children=u),"function"==typeof n&&null!=n.defaultProps)for(i in n.defaultProps)void 0===r[i]&&(r[i]=n.defaultProps[i]);return h(n,r,l&&l.key,l&&l.ref,null)}function h(l,u,i,t,r){var o={type:l,props:u,key:i,ref:t,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:r};return null==r&&(o.__v=o),n.vnode&&n.vnode(o),o}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 k(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 k(n)}}function w(l){(!l.__d&&(l.__d=!0)&&u.push(l)&&!m.__r++||t!==n.debounceRendering)&&((t=n.debounceRendering)||i)(m);}function m(){for(var n;m.__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,r,o,f;n.__d&&(o=(r=(l=n).__v).__e,(f=l.__P)&&(u=[],(i=s({},r)).__v=i,t=T(f,r,i,l.__n,void 0!==f.ownerSVGElement,null,u,null==o?_(r):o),$(u,r),t!=o&&k(r)));});}function g(n,l,u,i,t,r,o,c,s,v){var y,d,k,w,m,g,b,A=i&&i.__k||e,P=A.length;for(s==f&&(s=null!=o?o[0]:P?_(i,0):null),u.__k=[],y=0;y<l.length;y++)if(null!=(w=u.__k[y]=null==(w=l[y])||"boolean"==typeof w?null:"string"==typeof w||"number"==typeof w?h(null,w,null,null,w):Array.isArray(w)?h(p,{children:w},null,null,null):null!=w.__e||null!=w.__c?h(w.type,w.props,w.key,null,w.__v):w)){if(w.__=u,w.__b=u.__b+1,null===(k=A[y])||k&&w.key==k.key&&w.type===k.type)A[y]=void 0;else for(d=0;d<P;d++){if((k=A[d])&&w.key==k.key&&w.type===k.type){A[d]=void 0;break}k=null;}m=T(n,w,k=k||f,t,r,o,c,s,v),(d=w.ref)&&k.ref!=d&&(b||(b=[]),k.ref&&b.push(k.ref,null,w),b.push(d,w.__c||m,w)),null!=m?(null==g&&(g=m),s=x(n,w,k,A,o,m,s),"option"==u.type?n.value="":"function"==typeof u.type&&(u.__d=s)):s&&k.__e==s&&s.parentNode!=n&&(s=_(k));}if(u.__e=g,null!=o&&"function"!=typeof u.type)for(y=o.length;y--;)null!=o[y]&&a(o[y]);for(y=P;y--;)null!=A[y]&&I(A[y],A[y]);if(b)for(y=0;y<b.length;y++)H(b[y],b[++y],b[++y]);}function x(n,l,u,i,t,r,o){var f,e,c;if(void 0!==l.__d)f=l.__d,l.__d=void 0;else if(t==u||r!=o||null==r.parentNode)n:if(null==o||o.parentNode!==n)n.appendChild(r),f=null;else {for(e=o,c=0;(e=e.nextSibling)&&c<i.length;c+=2)if(e==r)break n;n.insertBefore(r,o),f=o;}return void 0!==f?f:r.nextSibling}function A(n,l,u,i,t){var r;for(r in u)"children"===r||"key"===r||r in l||C(n,r,null,u[r],i);for(r in l)t&&"function"!=typeof l[r]||"children"===r||"key"===r||"value"===r||"checked"===r||u[r]===l[r]||C(n,r,l[r],u[r],i);}function P(n,l,u){"-"===l[0]?n.setProperty(l,u):n[l]="number"==typeof u&&!1===c.test(l)?u+"px":null==u?"":u;}function C(n,l,u,i,t){var r,o,f,e,c;if(t?"className"===l&&(l="class"):"class"===l&&(l="className"),"style"===l)if(r=n.style,"string"==typeof u)r.cssText=u;else {if("string"==typeof i&&(r.cssText="",i=null),i)for(e in i)u&&e in u||P(r,e,"");if(u)for(c in u)i&&u[c]===i[c]||P(r,c,u[c]);}else "o"===l[0]&&"n"===l[1]?(o=l!==(l=l.replace(/Capture$/,"")),f=l.toLowerCase(),l=(f in n?f:l).slice(2),u?(i||n.addEventListener(l,N,o),(n.l||(n.l={}))[l]=u):n.removeEventListener(l,N,o)):"list"!==l&&"tagName"!==l&&"form"!==l&&"type"!==l&&"size"!==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](n.event?n.event(l):l);}function z(n,l,u){var i,t;for(i=0;i<n.__k.length;i++)(t=n.__k[i])&&(t.__=n,t.__e&&("function"==typeof t.type&&t.__k.length>1&&z(t,l,u),l=x(u,t,t,n.__k,null,t.__e,l),"function"==typeof n.type&&(n.__d=l)));}function T(l,u,i,t,r,o,f,e,c){var a,v,h,y,_,k,w,m,b,x,A,P=u.type;if(void 0!==u.constructor)return null;(a=n.__b)&&a(u);try{n:if("function"==typeof P){if(m=u.props,b=(a=P.contextType)&&t[a.__c],x=a?b?b.props.value:a.__:t,i.__c?w=(v=u.__c=i.__c).__=v.__E:("prototype"in P&&P.prototype.render?u.__c=v=new P(m,x):(u.__c=v=new d(m,x),v.constructor=P,v.render=L),b&&b.sub(v),v.props=m,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(m,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&&m!==y&&null!=v.componentWillReceiveProps&&v.componentWillReceiveProps(m,x),!v.__e&&null!=v.shouldComponentUpdate&&!1===v.shouldComponentUpdate(m,v.__s,x)||u.__v===i.__v){v.props=m,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),z(u,e,l);break n}null!=v.componentWillUpdate&&v.componentWillUpdate(m,v.__s,x),null!=v.componentDidUpdate&&v.__h.push(function(){v.componentDidUpdate(y,_,k);});}v.context=x,v.props=m,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||(k=v.getSnapshotBeforeUpdate(y,_)),A=null!=a&&a.type==p&&null==a.key?a.props.children:a,g(l,Array.isArray(A)?A:[A],u,i,t,r,o,f,e,c),v.base=u.__e,v.__h.length&&f.push(v),w&&(v.__E=v.__=null),v.__e=!1;}else null==o&&u.__v===i.__v?(u.__k=i.__k,u.__e=i.__e):u.__e=j(i.__e,u,i,t,r,o,f,c);(a=n.diffed)&&a(u);}catch(l){u.__v=null,n.__e(l,u,i);}return u.__e}function $(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 j(n,l,u,i,t,r,o,c){var s,a,v,h,y,p=u.props,d=l.props;if(t="svg"===l.type||t,null!=r)for(s=0;s<r.length;s++)if(null!=(a=r[s])&&((null===l.type?3===a.nodeType:a.localName===l.type)||n==a)){n=a,r[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}),r=null,c=!1;}if(null===l.type)p!==d&&n.data!=d&&(n.data=d);else {if(null!=r&&(r=e.slice.call(n.childNodes)),v=(p=u.props||f).dangerouslySetInnerHTML,h=d.dangerouslySetInnerHTML,!c){if(null!=r)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||(n.innerHTML=h&&h.__html||""));}A(n,d,p,t,c),h?l.__k=[]:(s=l.props.children,g(n,Array.isArray(s)?s:[s],l,u,i,"foreignObject"!==l.type&&t,r,o,f,c)),c||("value"in d&&void 0!==(s=d.value)&&s!==n.value&&C(n,"value",s,p.value,!1),"checked"in d&&void 0!==(s=d.checked)&&s!==n.checked&&C(n,"checked",s,p.checked,!1));}return n}function H(l,u,i){try{"function"==typeof l?l(u):l.current=u;}catch(l){n.__e(l,i);}}function I(l,u,i){var t,r,o;if(n.unmount&&n.unmount(l),(t=l.ref)&&(t.current&&t.current!==l.__e||H(t,null,u)),i||"function"==typeof l.type||(i=null!=(r=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(o=0;o<t.length;o++)t[o]&&I(t[o],u,i);null!=r&&a(r);}function L(n,l,u){return this.constructor(n,u)}function M(l,u,i){var t,o,c;n.__&&n.__(l,u),o=(t=i===r)?null:i&&i.__k||u.__k,l=v(p,null,[l]),c=[],T(u,(t?u:i||u).__k=l,o||f,f,void 0!==u.ownerSVGElement,i&&!t?[i]:o?null:u.childNodes.length?e.slice.call(u.childNodes):null,c,i||f,t),$(c,l);}function q(n){var l={},u={__c:"__cC"+o++,__:n,Consumer:function(n,l){return n.children(l)},Provider:function(n){var i,t=this;return this.getChildContext||(i=[],this.getChildContext=function(){return l[u.__c]=t,l},this.shouldComponentUpdate=function(n){t.props.value!==n.value&&i.some(function(l){l.context=n.value,w(l);});},this.sub=function(n){i.push(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){i.splice(i.indexOf(n),1),l&&l.call(n);};}),n.children}};return u.Consumer.contextType=u,u.Provider.__=u,u}n={__e:function(n,l){for(var u,i;l=l.__;)if((u=l.__c)&&!u.__)try{if(u.constructor&&null!=u.constructor.getDerivedStateFromError&&(i=!0,u.setState(u.constructor.getDerivedStateFromError(n))),null!=u.componentDidCatch&&(i=!0,u.componentDidCatch(n)),i)return w(u.__E=u)}catch(l){n=l;}throw n}},l=function(n){return null!=n&&void 0===n.constructor},d.prototype.setState=function(n,l){var u;u=this.__s!==this.state?this.__s:this.__s=s({},this.state),"function"==typeof n&&(n=n(u,this.props)),n&&s(u,n),null!=n&&this.__v&&(l&&this.__h.push(l),w(this));},d.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),w(this));},d.prototype.render=p,u=[],i="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,m.__r=0,r=f,o=0;
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 html(content, parentElement) {
242 return v(HTMLElement$1, { content: content, parentElement: parentElement });
243}
244
245var Cell = /** @class */ (function (_super) {
246 __extends(Cell, _super);
247 function Cell(data) {
248 var _this = _super.call(this) || this;
249 _this.setData(data);
250 return _this;
251 }
252 Cell.prototype.cast = function (data) {
253 if (data instanceof HTMLElement) {
254 return html(data.outerHTML);
255 }
256 return data;
257 };
258 Cell.prototype.setData = function (data) {
259 this.data = this.cast(data);
260 return this;
261 };
262 return Cell;
263}(Base));
264
265var Row = /** @class */ (function (_super) {
266 __extends(Row, _super);
267 function Row(cells) {
268 var _this = _super.call(this) || this;
269 _this.cells = cells || [];
270 return _this;
271 }
272 Object.defineProperty(Row.prototype, "cells", {
273 get: function () {
274 return this._cells;
275 },
276 set: function (cells) {
277 this._cells = cells;
278 },
279 enumerable: false,
280 configurable: true
281 });
282 /**
283 * Creates a new Row from an array of Cell(s)
284 * This method generates a new ID for the Row and all nested elements
285 *
286 * @param cells
287 * @returns Row
288 */
289 Row.fromCells = function (cells) {
290 return new Row(cells.map(function (cell) { return new Cell(cell.data); }));
291 };
292 Object.defineProperty(Row.prototype, "length", {
293 get: function () {
294 return this.cells.length;
295 },
296 enumerable: false,
297 configurable: true
298 });
299 return Row;
300}(Base));
301
302function oneDtoTwoD(data) {
303 if (data[0] && !(data[0] instanceof Array)) {
304 return [data];
305 }
306 return data;
307}
308
309var Tabular = /** @class */ (function (_super) {
310 __extends(Tabular, _super);
311 function Tabular(rows) {
312 var _this = _super.call(this) || this;
313 if (rows instanceof Array) {
314 _this.rows = rows;
315 }
316 else if (rows instanceof Row) {
317 _this.rows = [rows];
318 }
319 else {
320 _this.rows = [];
321 }
322 return _this;
323 }
324 Object.defineProperty(Tabular.prototype, "rows", {
325 get: function () {
326 return this._rows;
327 },
328 set: function (rows) {
329 this._rows = rows;
330 },
331 enumerable: false,
332 configurable: true
333 });
334 Object.defineProperty(Tabular.prototype, "length", {
335 get: function () {
336 return this._length || this.rows.length;
337 },
338 // we want to sent the length when storage is ServerStorage
339 set: function (len) {
340 this._length = len;
341 },
342 enumerable: false,
343 configurable: true
344 });
345 /**
346 * Creates a new Tabular from an array of Row(s)
347 * This method generates a new ID for the Tabular and all nested elements
348 *
349 * @param rows
350 * @returns Tabular
351 */
352 Tabular.fromRows = function (rows) {
353 return new Tabular(rows.map(function (row) { return Row.fromCells(row.cells); }));
354 };
355 /**
356 * Creates a new Tabular from a 2D array
357 * This method generates a new ID for the Tabular and all nested elements
358 *
359 * @param data
360 * @returns Tabular
361 */
362 Tabular.fromArray = function (data) {
363 data = oneDtoTwoD(data);
364 return new Tabular(data.map(function (row) { return new Row(row.map(function (cell) { return new Cell(cell); })); }));
365 };
366 return Tabular;
367}(Base));
368
369function width(width, containerWidth) {
370 if (typeof width == 'string') {
371 if (width.indexOf('%') > -1) {
372 return (containerWidth / 100) * parseInt(width, 10);
373 }
374 else {
375 return parseInt(width, 10);
376 }
377 }
378 return width;
379}
380function px(width) {
381 if (!width)
382 return '';
383 return Math.floor(width) + "px";
384}
385/**
386 * Accepts a ShadowTable and tries to find the clientWidth
387 * that is already rendered on the web browser
388 *
389 * @param shadowTable
390 * @param columnIndex
391 */
392function getWidth(shadowTable, columnIndex) {
393 if (!shadowTable) {
394 return null;
395 }
396 var tds = shadowTable.querySelectorAll('tr:first-child > td');
397 if (tds && tds[columnIndex]) {
398 return tds[columnIndex].clientWidth;
399 }
400 return null;
401}
402
403var ShadowTable = /** @class */ (function (_super) {
404 __extends(ShadowTable, _super);
405 function ShadowTable() {
406 return _super !== null && _super.apply(this, arguments) || this;
407 }
408 ShadowTable.prototype.resetStyle = function () {
409 return { padding: 0, margin: 0, border: 'none', outline: 'none' };
410 };
411 ShadowTable.prototype.head = function () {
412 var _this = this;
413 return (v("thead", { style: this.resetStyle() },
414 v("tr", null, this.props.header.columns.map(function (col) {
415 return (v("th", { style: __assign(__assign({}, _this.resetStyle()), { whiteSpace: 'nowrap',
416 // pagination buttons
417 paddingRight: col.sort ? '18px' : '0' }) }, col.name));
418 }))));
419 };
420 ShadowTable.prototype.td = function (cell) {
421 return v("td", { style: this.resetStyle() }, cell.data);
422 };
423 ShadowTable.prototype.tr = function (row) {
424 var _this = this;
425 return (v("tr", { style: this.resetStyle() }, row.cells.map(function (cell) {
426 return _this.td(cell);
427 })));
428 };
429 ShadowTable.prototype.body = function () {
430 var _this = this;
431 return (v("tbody", { style: this.resetStyle() }, this.props.data &&
432 this.props.data.rows.map(function (row) {
433 return _this.tr(row);
434 })));
435 };
436 ShadowTable.prototype.render = function () {
437 return (v("table", { style: __assign({ position: 'absolute', zIndex: '-2147483640', visibility: 'hidden', tableLayout: 'auto', width: 'auto' }, this.resetStyle()) },
438 this.head(),
439 this.body()));
440 };
441 return ShadowTable;
442}(BaseComponent));
443
444function camelCase(str) {
445 return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {
446 if (+match === 0)
447 return ''; // or if (/\s+/.test(match)) for white spaces
448 return index === 0 ? match.toLowerCase() : match.toUpperCase();
449 });
450}
451
452var Header = /** @class */ (function (_super) {
453 __extends(Header, _super);
454 function Header() {
455 var _this = _super.call(this) || this;
456 _this._columns = [];
457 return _this;
458 }
459 Object.defineProperty(Header.prototype, "columns", {
460 get: function () {
461 return this._columns;
462 },
463 set: function (columns) {
464 this._columns = columns;
465 },
466 enumerable: false,
467 configurable: true
468 });
469 /**
470 * Tries to automatically adjust the width of columns based on:
471 * - Header cell content
472 * - Cell content of the first row
473 * - Cell content of the last row
474 *
475 * @param container
476 * @param tempRef
477 * @param data
478 * @param autoWidth
479 */
480 Header.prototype.adjustWidth = function (container, tempRef, data, autoWidth) {
481 if (autoWidth === void 0) { autoWidth = true; }
482 if (!container) {
483 // we can't calculate the width because the container
484 // is unknown at this stage
485 return this;
486 }
487 // pixels
488 var containerWidth = container.clientWidth;
489 // let's create a shadow table with the first 10 rows of the data
490 // and let the browser to render the table with table-layout: auto
491 // no padding, margin or border to get the minimum space required
492 // to render columns. One the table is rendered and widths are known,
493 // we unmount the shadow table from the DOM and set the correct width
494 var shadowTable = y();
495 if (data && data.length && autoWidth) {
496 // render a ShadowTable with the first 10 rows
497 var el = v(ShadowTable, {
498 data: Tabular.fromRows(data.rows.slice(0, 10)),
499 header: this,
500 });
501 el.ref = shadowTable;
502 // TODO: we should NOT query the container here. use Refs instead
503 M(el, tempRef.current);
504 }
505 for (var _i = 0, _a = this.columns; _i < _a.length; _i++) {
506 var column = _a[_i];
507 if (!column.width && autoWidth) {
508 // tries to find the corresponding cell
509 // from the ShadowTable and set the correct width
510 column.width = px(getWidth(shadowTable.current.base, this.columns.indexOf(column)));
511 }
512 else {
513 column.width = px(width(column.width, containerWidth));
514 }
515 }
516 if (data && data.length && autoWidth) {
517 // unmount the shadow table from temp
518 M(null, tempRef.current);
519 }
520 return this;
521 };
522 Header.prototype.setSort = function (userConfig) {
523 for (var _i = 0, _a = this.columns; _i < _a.length; _i++) {
524 var column = _a[_i];
525 // implicit userConfig.sort flag
526 if (column.sort === undefined && userConfig.sort) {
527 column.sort = {
528 enabled: true,
529 };
530 }
531 // false, null, etc.
532 if (!column.sort) {
533 column.sort = {
534 enabled: false,
535 };
536 }
537 else if (typeof column.sort === 'object') {
538 column.sort = __assign({ enabled: true }, column.sort);
539 }
540 }
541 };
542 Header.prototype.setID = function () {
543 for (var _i = 0, _a = this.columns; _i < _a.length; _i++) {
544 var column = _a[_i];
545 if (!column.id && typeof column.name === 'string') {
546 // let's guess the column ID if it's undefined
547 column.id = camelCase(column.name);
548 }
549 }
550 };
551 Header.fromUserConfig = function (userConfig) {
552 var header = new Header();
553 if (userConfig.from) {
554 header.columns = Header.fromHTMLTable(userConfig.from).columns;
555 }
556 else if (userConfig.columns) {
557 for (var _i = 0, _a = userConfig.columns; _i < _a.length; _i++) {
558 var column = _a[_i];
559 if (typeof column === 'string' || l(column)) {
560 header.columns.push({
561 name: column,
562 });
563 }
564 else if (typeof column === 'object') {
565 header.columns.push(column);
566 }
567 }
568 }
569 else if (userConfig.data &&
570 typeof userConfig.data[0] === 'object' &&
571 !(userConfig.data[0] instanceof Array)) {
572 // if data[0] is an object but not an Array
573 header.columns = Object.keys(userConfig.data[0]).map(function (name) {
574 return { name: name };
575 });
576 }
577 if (header.columns.length) {
578 header.setID();
579 header.setSort(userConfig);
580 return header;
581 }
582 return null;
583 };
584 Header.fromHTMLTable = function (element) {
585 var header = new Header();
586 var thead = element.querySelector('thead');
587 var ths = thead.querySelectorAll('th');
588 for (var _i = 0, _a = ths; _i < _a.length; _i++) {
589 var th = _a[_i];
590 header.columns.push({
591 name: th.innerText,
592 width: th.width,
593 });
594 }
595 return header;
596 };
597 return Header;
598}(Base));
599
600var _prefix = 'ID_';
601/**
602 * This class is mostly based on Flux's Dispatcher by Facebook
603 * https://github.com/facebook/flux/blob/master/src/Dispatcher.js
604 */
605var Dispatcher = /** @class */ (function () {
606 function Dispatcher() {
607 this._callbacks = {};
608 this._isDispatching = false;
609 this._isHandled = {};
610 this._isPending = {};
611 this._lastID = 1;
612 }
613 /**
614 * Registers a callback to be invoked with every dispatched payload. Returns
615 * a token that can be used with `waitFor()`.
616 */
617 Dispatcher.prototype.register = function (callback) {
618 var id = _prefix + this._lastID++;
619 this._callbacks[id] = callback;
620 return id;
621 };
622 /**
623 * Removes a callback based on its token.
624 */
625 Dispatcher.prototype.unregister = function (id) {
626 if (!this._callbacks[id]) {
627 throw Error("Dispatcher.unregister(...): " + id + " does not map to a registered callback.");
628 }
629 delete this._callbacks[id];
630 };
631 /**
632 * Waits for the callbacks specified to be invoked before continuing execution
633 * of the current callback. This method should only be used by a callback in
634 * response to a dispatched payload.
635 */
636 Dispatcher.prototype.waitFor = function (ids) {
637 if (!this._isDispatching) {
638 throw Error('Dispatcher.waitFor(...): Must be invoked while dispatching.');
639 }
640 for (var ii = 0; ii < ids.length; ii++) {
641 var id = ids[ii];
642 if (this._isPending[id]) {
643 if (!this._isHandled[id]) {
644 throw Error("Dispatcher.waitFor(...): Circular dependency detected while ' +\n 'waiting for " + id + ".");
645 }
646 continue;
647 }
648 if (!this._callbacks[id]) {
649 throw Error("Dispatcher.waitFor(...): " + id + " does not map to a registered callback.");
650 }
651 this._invokeCallback(id);
652 }
653 };
654 /**
655 * Dispatches a payload to all registered callbacks.
656 */
657 Dispatcher.prototype.dispatch = function (payload) {
658 if (this._isDispatching) {
659 throw Error('Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.');
660 }
661 this._startDispatching(payload);
662 try {
663 for (var id in this._callbacks) {
664 if (this._isPending[id]) {
665 continue;
666 }
667 this._invokeCallback(id);
668 }
669 }
670 finally {
671 this._stopDispatching();
672 }
673 };
674 /**
675 * Is this Dispatcher currently dispatching.
676 */
677 Dispatcher.prototype.isDispatching = function () {
678 return this._isDispatching;
679 };
680 /**
681 * Call the callback stored with the given id. Also do some internal
682 * bookkeeping.
683 *
684 * @internal
685 */
686 Dispatcher.prototype._invokeCallback = function (id) {
687 this._isPending[id] = true;
688 this._callbacks[id](this._pendingPayload);
689 this._isHandled[id] = true;
690 };
691 /**
692 * Set up bookkeeping needed when dispatching.
693 *
694 * @internal
695 */
696 Dispatcher.prototype._startDispatching = function (payload) {
697 for (var id in this._callbacks) {
698 this._isPending[id] = false;
699 this._isHandled[id] = false;
700 }
701 this._pendingPayload = payload;
702 this._isDispatching = true;
703 };
704 /**
705 * Clear bookkeeping used for dispatching.
706 *
707 * @internal
708 */
709 Dispatcher.prototype._stopDispatching = function () {
710 delete this._pendingPayload;
711 this._isDispatching = false;
712 };
713 return Dispatcher;
714}());
715
716var Storage = /** @class */ (function () {
717 function Storage() {
718 }
719 return Storage;
720}());
721
722var MemoryStorage = /** @class */ (function (_super) {
723 __extends(MemoryStorage, _super);
724 function MemoryStorage(data) {
725 var _this = _super.call(this) || this;
726 _this.set(data);
727 return _this;
728 }
729 MemoryStorage.prototype.get = function () {
730 return __awaiter(this, void 0, void 0, function () {
731 var data;
732 return __generator(this, function (_a) {
733 switch (_a.label) {
734 case 0: return [4 /*yield*/, this.data()];
735 case 1:
736 data = _a.sent();
737 return [2 /*return*/, {
738 data: data,
739 total: data.length,
740 }];
741 }
742 });
743 });
744 };
745 MemoryStorage.prototype.set = function (data) {
746 if (data instanceof Array) {
747 this.data = function () { return data; };
748 }
749 else if (data instanceof Function) {
750 this.data = data;
751 }
752 return this;
753 };
754 return MemoryStorage;
755}(Storage));
756
757/**
758 * Centralized logging lib
759 *
760 * This class needs some improvements but so far it has been used to have a coherent way to log
761 */
762var Logger = /** @class */ (function () {
763 function Logger() {
764 }
765 Logger.prototype.format = function (message, type) {
766 return "[Grid.js] [" + type.toUpperCase() + "]: " + message;
767 };
768 Logger.prototype.error = function (message, throwException) {
769 if (throwException === void 0) { throwException = false; }
770 var msg = this.format(message, 'error');
771 if (throwException) {
772 throw Error(msg);
773 }
774 else {
775 console.error(msg);
776 }
777 };
778 Logger.prototype.warn = function (message) {
779 console.warn(this.format(message, 'warn'));
780 };
781 Logger.prototype.info = function (message) {
782 console.info(this.format(message, 'info'));
783 };
784 return Logger;
785}());
786var log = new Logger();
787
788var ServerStorage = /** @class */ (function (_super) {
789 __extends(ServerStorage, _super);
790 function ServerStorage(options) {
791 var _this = _super.call(this) || this;
792 _this.options = options;
793 return _this;
794 }
795 ServerStorage.prototype.handler = function (response) {
796 if (typeof this.options.handle === 'function') {
797 return this.options.handle(response);
798 }
799 if (response.ok) {
800 return response.json();
801 }
802 else {
803 log.error("Could not fetch data: " + response.status + " - " + response.statusText, true);
804 return null;
805 }
806 };
807 ServerStorage.prototype.get = function (options) {
808 // this.options is the initial config object
809 // options is the runtime config passed by the pipeline (e.g. search component)
810 var opts = __assign(__assign({}, this.options), options);
811 return fetch(opts.url, opts)
812 .then(this.handler.bind(this))
813 .then(function (res) {
814 return {
815 data: opts.then(res),
816 total: typeof opts.total === 'function' ? opts.total(res) : undefined,
817 };
818 });
819 };
820 return ServerStorage;
821}(Storage));
822
823var StorageUtils = /** @class */ (function () {
824 function StorageUtils() {
825 }
826 /**
827 * Accepts the userConfig dict and tries to guess and return a Storage type
828 *
829 * @param userConfig
830 */
831 StorageUtils.createFromUserConfig = function (userConfig) {
832 var storage = null;
833 // `data` array is provided
834 if (userConfig.data) {
835 storage = new MemoryStorage(userConfig.data);
836 }
837 if (userConfig.from) {
838 storage = new MemoryStorage(this.tableElementToArray(userConfig.from));
839 // remove the source table element from the DOM
840 userConfig.from.style.display = 'none';
841 }
842 if (userConfig.server) {
843 storage = new ServerStorage(userConfig.server);
844 }
845 if (!storage) {
846 log.error('Could not determine the storage type', true);
847 }
848 return storage;
849 };
850 /**
851 * Accepts a HTML table element and converts it into a 2D array of data
852 *
853 * TODO: This function can be a step in the pipeline: Convert Table -> Load into a memory storage -> ...
854 *
855 * @param element
856 */
857 StorageUtils.tableElementToArray = function (element) {
858 var arr = [];
859 var tbody = element.querySelector('tbody');
860 var rows = tbody.querySelectorAll('tr');
861 for (var _i = 0, _a = rows; _i < _a.length; _i++) {
862 var row = _a[_i];
863 var cells = row.querySelectorAll('td');
864 var parsedRow = [];
865 for (var _b = 0, cells_1 = cells; _b < cells_1.length; _b++) {
866 var cell = cells_1[_b];
867 // try to capture a TD with single text element first
868 if (cell.childNodes.length === 1 &&
869 cell.childNodes[0].nodeType === Node.TEXT_NODE) {
870 parsedRow.push(cell.innerText);
871 }
872 else {
873 parsedRow.push(html(cell.innerHTML));
874 }
875 }
876 arr.push(parsedRow);
877 }
878 return arr;
879 };
880 return StorageUtils;
881}());
882
883var EventEmitter = /** @class */ (function () {
884 function EventEmitter() {
885 }
886 // because we are using EventEmitter as a mixin and the
887 // constructor won't be called by the applyMixins function
888 // see src/base.ts and src/util/applyMixin.ts
889 EventEmitter.prototype.init = function (event) {
890 if (!this.callbacks) {
891 this.callbacks = {};
892 }
893 if (event && !this.callbacks[event]) {
894 this.callbacks[event] = [];
895 }
896 };
897 EventEmitter.prototype.on = function (event, listener) {
898 this.init(event);
899 this.callbacks[event].push(listener);
900 return this;
901 };
902 EventEmitter.prototype.off = function (event, listener) {
903 var eventName = event;
904 this.init();
905 if (!this.callbacks[eventName] || this.callbacks[eventName].length === 0) {
906 // there is no callbacks with this key
907 return this;
908 }
909 this.callbacks[eventName] = this.callbacks[eventName].filter(function (value) { return value != listener; });
910 return this;
911 };
912 EventEmitter.prototype.emit = function (event) {
913 var args = [];
914 for (var _i = 1; _i < arguments.length; _i++) {
915 args[_i - 1] = arguments[_i];
916 }
917 var eventName = event;
918 this.init(eventName);
919 if (this.callbacks[eventName].length > 0) {
920 this.callbacks[eventName].forEach(function (value) { return value.apply(void 0, args); });
921 return true;
922 }
923 return false;
924 };
925 return EventEmitter;
926}());
927
928var ProcessorType;
929(function (ProcessorType) {
930 ProcessorType[ProcessorType["Initiator"] = 0] = "Initiator";
931 ProcessorType[ProcessorType["ServerFilter"] = 1] = "ServerFilter";
932 ProcessorType[ProcessorType["ServerSort"] = 2] = "ServerSort";
933 ProcessorType[ProcessorType["ServerLimit"] = 3] = "ServerLimit";
934 ProcessorType[ProcessorType["Extractor"] = 4] = "Extractor";
935 ProcessorType[ProcessorType["Transformer"] = 5] = "Transformer";
936 ProcessorType[ProcessorType["Filter"] = 6] = "Filter";
937 ProcessorType[ProcessorType["Sort"] = 7] = "Sort";
938 ProcessorType[ProcessorType["Limit"] = 8] = "Limit";
939})(ProcessorType || (ProcessorType = {}));
940var PipelineProcessor = /** @class */ (function (_super) {
941 __extends(PipelineProcessor, _super);
942 function PipelineProcessor(props) {
943 var _this = _super.call(this) || this;
944 _this._props = {};
945 _this.id = generateID();
946 if (props)
947 _this.setProps(props);
948 return _this;
949 }
950 /**
951 * process is used to call beforeProcess and afterProcess callbacks
952 * This function is just a wrapper that calls _process()
953 *
954 * @param args
955 */
956 PipelineProcessor.prototype.process = function () {
957 var args = [];
958 for (var _i = 0; _i < arguments.length; _i++) {
959 args[_i] = arguments[_i];
960 }
961 if (this.validateProps instanceof Function) {
962 this.validateProps.apply(this, args);
963 }
964 this.emit.apply(this, __spreadArrays(['beforeProcess'], args));
965 var result = this._process.apply(this, args);
966 this.emit.apply(this, __spreadArrays(['afterProcess'], args));
967 return result;
968 };
969 PipelineProcessor.prototype.setProps = function (props) {
970 Object.assign(this._props, props);
971 this.emit('propsUpdated', this);
972 return this;
973 };
974 Object.defineProperty(PipelineProcessor.prototype, "props", {
975 get: function () {
976 return this._props;
977 },
978 enumerable: false,
979 configurable: true
980 });
981 return PipelineProcessor;
982}(EventEmitter));
983
984var Pipeline = /** @class */ (function (_super) {
985 __extends(Pipeline, _super);
986 function Pipeline(steps) {
987 var _this = _super.call(this) || this;
988 // available steps for this pipeline
989 _this._steps = new Map();
990 // used to cache the results of processors using their id field
991 _this.cache = new Map();
992 // keeps the index of the last updated processor in the registered
993 // processors list and will be used to invalidate the cache
994 // -1 means all new processors should be processed
995 _this.lastProcessorIndexUpdated = -1;
996 if (steps) {
997 steps.forEach(function (step) { return _this.register(step); });
998 }
999 return _this;
1000 }
1001 /**
1002 * Clears the `cache` array
1003 */
1004 Pipeline.prototype.clearCache = function () {
1005 this.cache = new Map();
1006 this.lastProcessorIndexUpdated = -1;
1007 };
1008 /**
1009 * Registers a new processor
1010 *
1011 * @param processor
1012 * @param priority
1013 */
1014 Pipeline.prototype.register = function (processor, priority) {
1015 if (priority === void 0) { priority = null; }
1016 if (processor.type === null) {
1017 throw Error('Processor type is not defined');
1018 }
1019 // binding the propsUpdated callback to the Pipeline
1020 processor.on('propsUpdated', this.processorPropsUpdated.bind(this));
1021 this.addProcessorByPriority(processor, priority);
1022 this.afterRegistered(processor);
1023 };
1024 /**
1025 * Removes a processor from the list
1026 *
1027 * @param processor
1028 */
1029 Pipeline.prototype.unregister = function (processor) {
1030 if (!processor)
1031 return;
1032 var subSteps = this._steps.get(processor.type);
1033 if (subSteps && subSteps.length) {
1034 this._steps.set(processor.type, subSteps.filter(function (proc) { return proc != processor; }));
1035 this.emit('updated', processor);
1036 }
1037 };
1038 /**
1039 * Registers a new processor
1040 *
1041 * @param processor
1042 * @param priority
1043 */
1044 Pipeline.prototype.addProcessorByPriority = function (processor, priority) {
1045 var subSteps = this._steps.get(processor.type);
1046 if (!subSteps) {
1047 var newSubStep = [];
1048 this._steps.set(processor.type, newSubStep);
1049 subSteps = newSubStep;
1050 }
1051 if (priority === null || priority < 0) {
1052 subSteps.push(processor);
1053 }
1054 else {
1055 if (!subSteps[priority]) {
1056 // slot is empty
1057 subSteps[priority] = processor;
1058 }
1059 else {
1060 // slot is NOT empty
1061 var first = subSteps.slice(0, priority - 1);
1062 var second = subSteps.slice(priority + 1);
1063 this._steps.set(processor.type, first.concat(processor).concat(second));
1064 }
1065 }
1066 };
1067 Object.defineProperty(Pipeline.prototype, "steps", {
1068 /**
1069 * Flattens the _steps Map and returns a list of steps with their correct priorities
1070 */
1071 get: function () {
1072 var steps = [];
1073 for (var _i = 0, _a = this.getSortedProcessorTypes(); _i < _a.length; _i++) {
1074 var type = _a[_i];
1075 var subSteps = this._steps.get(type);
1076 if (subSteps && subSteps.length) {
1077 steps = steps.concat(subSteps);
1078 }
1079 }
1080 // to remove any undefined elements
1081 return steps.filter(function (s) { return s; });
1082 },
1083 enumerable: false,
1084 configurable: true
1085 });
1086 /**
1087 * Accepts ProcessType and returns an array of the registered processes
1088 * with the give type
1089 *
1090 * @param type
1091 */
1092 Pipeline.prototype.getStepsByType = function (type) {
1093 return this.steps.filter(function (process) { return process.type === type; });
1094 };
1095 /**
1096 * Returns a list of ProcessorType according to their priority
1097 */
1098 Pipeline.prototype.getSortedProcessorTypes = function () {
1099 return Object.keys(ProcessorType)
1100 .filter(function (key) { return !isNaN(Number(key)); })
1101 .map(function (key) { return Number(key); });
1102 };
1103 /**
1104 * Runs all registered processors based on their correct priority
1105 * and returns the final output after running all steps
1106 *
1107 * @param data
1108 */
1109 Pipeline.prototype.process = function (data) {
1110 return __awaiter(this, void 0, void 0, function () {
1111 var lastProcessorIndexUpdated, steps, prev, _i, steps_1, processor, processorIndex, e_1;
1112 return __generator(this, function (_a) {
1113 switch (_a.label) {
1114 case 0:
1115 lastProcessorIndexUpdated = this.lastProcessorIndexUpdated;
1116 steps = this.steps;
1117 prev = data;
1118 _a.label = 1;
1119 case 1:
1120 _a.trys.push([1, 7, , 8]);
1121 _i = 0, steps_1 = steps;
1122 _a.label = 2;
1123 case 2:
1124 if (!(_i < steps_1.length)) return [3 /*break*/, 6];
1125 processor = steps_1[_i];
1126 processorIndex = this.findProcessorIndexByID(processor.id);
1127 if (!(processorIndex >= lastProcessorIndexUpdated)) return [3 /*break*/, 4];
1128 return [4 /*yield*/, processor.process(prev)];
1129 case 3:
1130 // we should execute process() here since the last
1131 // updated processor was before "processor".
1132 // This is to ensure that we always have correct and up to date
1133 // data from processors and also to skip them when necessary
1134 prev = _a.sent();
1135 this.cache.set(processor.id, prev);
1136 return [3 /*break*/, 5];
1137 case 4:
1138 // cached results already exist
1139 prev = this.cache.get(processor.id);
1140 _a.label = 5;
1141 case 5:
1142 _i++;
1143 return [3 /*break*/, 2];
1144 case 6: return [3 /*break*/, 8];
1145 case 7:
1146 e_1 = _a.sent();
1147 log.error(e_1);
1148 // trigger the onError callback
1149 this.emit('error', prev);
1150 // rethrow
1151 throw e_1;
1152 case 8:
1153 // means the pipeline is up to date
1154 this.lastProcessorIndexUpdated = steps.length;
1155 // triggers the afterProcess callbacks with the results
1156 this.emit('afterProcess', prev);
1157 return [2 /*return*/, prev];
1158 }
1159 });
1160 });
1161 };
1162 /**
1163 * Returns the registered processor's index in _steps array
1164 *
1165 * @param processorID
1166 */
1167 Pipeline.prototype.findProcessorIndexByID = function (processorID) {
1168 return this.steps.findIndex(function (p) { return p.id == processorID; });
1169 };
1170 /**
1171 * Sets the last updates processors index locally
1172 * This is used to invalid or skip a processor in
1173 * the process() method
1174 */
1175 Pipeline.prototype.setLastProcessorIndex = function (processor) {
1176 var processorIndex = this.findProcessorIndexByID(processor.id);
1177 if (this.lastProcessorIndexUpdated > processorIndex) {
1178 this.lastProcessorIndexUpdated = processorIndex;
1179 }
1180 };
1181 Pipeline.prototype.processorPropsUpdated = function (processor) {
1182 this.setLastProcessorIndex(processor);
1183 this.emit('propsUpdated');
1184 this.emit('updated', processor);
1185 };
1186 Pipeline.prototype.afterRegistered = function (processor) {
1187 this.setLastProcessorIndex(processor);
1188 this.emit('afterRegister');
1189 this.emit('updated', processor);
1190 };
1191 return Pipeline;
1192}(EventEmitter));
1193
1194var StorageExtractor = /** @class */ (function (_super) {
1195 __extends(StorageExtractor, _super);
1196 function StorageExtractor() {
1197 return _super !== null && _super.apply(this, arguments) || this;
1198 }
1199 Object.defineProperty(StorageExtractor.prototype, "type", {
1200 get: function () {
1201 return ProcessorType.Extractor;
1202 },
1203 enumerable: false,
1204 configurable: true
1205 });
1206 StorageExtractor.prototype._process = function (opts) {
1207 return __awaiter(this, void 0, void 0, function () {
1208 return __generator(this, function (_a) {
1209 switch (_a.label) {
1210 case 0: return [4 /*yield*/, this.props.storage.get(opts)];
1211 case 1: return [2 /*return*/, _a.sent()];
1212 }
1213 });
1214 });
1215 };
1216 return StorageExtractor;
1217}(PipelineProcessor));
1218
1219var ArrayToTabularTransformer = /** @class */ (function (_super) {
1220 __extends(ArrayToTabularTransformer, _super);
1221 function ArrayToTabularTransformer() {
1222 return _super !== null && _super.apply(this, arguments) || this;
1223 }
1224 Object.defineProperty(ArrayToTabularTransformer.prototype, "type", {
1225 get: function () {
1226 return ProcessorType.Transformer;
1227 },
1228 enumerable: false,
1229 configurable: true
1230 });
1231 ArrayToTabularTransformer.prototype._process = function (arrayResponse) {
1232 var tabular = Tabular.fromArray(arrayResponse.data);
1233 // for server-side storage
1234 tabular.length = arrayResponse.total;
1235 return tabular;
1236 };
1237 return ArrayToTabularTransformer;
1238}(PipelineProcessor));
1239
1240var ServerInitiator = /** @class */ (function (_super) {
1241 __extends(ServerInitiator, _super);
1242 function ServerInitiator() {
1243 return _super !== null && _super.apply(this, arguments) || this;
1244 }
1245 Object.defineProperty(ServerInitiator.prototype, "type", {
1246 get: function () {
1247 return ProcessorType.Initiator;
1248 },
1249 enumerable: false,
1250 configurable: true
1251 });
1252 ServerInitiator.prototype._process = function () {
1253 return {
1254 url: this.props.serverStorageOptions.url,
1255 method: this.props.serverStorageOptions.method,
1256 };
1257 };
1258 return ServerInitiator;
1259}(PipelineProcessor));
1260
1261var StorageResponseToArrayTransformer = /** @class */ (function (_super) {
1262 __extends(StorageResponseToArrayTransformer, _super);
1263 function StorageResponseToArrayTransformer() {
1264 return _super !== null && _super.apply(this, arguments) || this;
1265 }
1266 Object.defineProperty(StorageResponseToArrayTransformer.prototype, "type", {
1267 get: function () {
1268 return ProcessorType.Transformer;
1269 },
1270 enumerable: false,
1271 configurable: true
1272 });
1273 StorageResponseToArrayTransformer.prototype.castData = function (data) {
1274 var _this = this;
1275 if (!data || !data.length) {
1276 return [];
1277 }
1278 // if it's a 2d array already
1279 if (data[0] instanceof Array) {
1280 return data;
1281 }
1282 // if it's an array of objects (but not array of arrays)
1283 if (typeof data[0] === 'object' && !(data[0] instanceof Array)) {
1284 return data.map(function (row) {
1285 return _this.props.header.columns.map(function (column) { return row[column.id]; });
1286 });
1287 }
1288 return [];
1289 };
1290 StorageResponseToArrayTransformer.prototype._process = function (storageResponse) {
1291 return {
1292 data: this.castData(storageResponse.data),
1293 total: storageResponse.total,
1294 };
1295 };
1296 return StorageResponseToArrayTransformer;
1297}(PipelineProcessor));
1298
1299var PipelineUtils = /** @class */ (function () {
1300 function PipelineUtils() {
1301 }
1302 PipelineUtils.createFromConfig = function (config) {
1303 var pipeline = new Pipeline();
1304 if (config.storage instanceof ServerStorage) {
1305 pipeline.register(new ServerInitiator({
1306 serverStorageOptions: config.server,
1307 }));
1308 }
1309 pipeline.register(new StorageExtractor({ storage: config.storage }));
1310 pipeline.register(new StorageResponseToArrayTransformer({ header: config.header }));
1311 pipeline.register(new ArrayToTabularTransformer());
1312 return pipeline;
1313 };
1314 return PipelineUtils;
1315}());
1316
1317var Config = /** @class */ (function () {
1318 function Config(config) {
1319 Object.assign(this, __assign(__assign({}, Config.defaultConfig()), config));
1320 this._userConfig = {};
1321 }
1322 /**
1323 * Assigns `updatedConfig` keys to the current config file
1324 *
1325 * @param updatedConfig
1326 */
1327 Config.prototype.assign = function (updatedConfig) {
1328 for (var _i = 0, _a = Object.keys(updatedConfig); _i < _a.length; _i++) {
1329 var key = _a[_i];
1330 // because we don't want to update the _userConfig cache
1331 if (key === '_userConfig')
1332 continue;
1333 this[key] = updatedConfig[key];
1334 }
1335 return this;
1336 };
1337 /**
1338 * Updates the config from a UserConfig
1339 *
1340 * @param userConfig
1341 */
1342 Config.prototype.update = function (userConfig) {
1343 if (!userConfig)
1344 return this;
1345 this._userConfig = __assign(__assign({}, this._userConfig), userConfig);
1346 this.assign(Config.fromUserConfig(this._userConfig));
1347 return this;
1348 };
1349 Config.defaultConfig = function () {
1350 return {
1351 dispatcher: new Dispatcher(),
1352 tempRef: y(),
1353 width: '100%',
1354 autoWidth: true,
1355 style: {},
1356 className: {},
1357 };
1358 };
1359 Config.fromUserConfig = function (userConfig) {
1360 var config = new Config(userConfig);
1361 // to set the initial _userConfig object
1362 config._userConfig = userConfig;
1363 // Sort
1364 if (typeof userConfig.sort === 'boolean' && userConfig.sort) {
1365 config.assign({
1366 sort: {
1367 multiColumn: true,
1368 },
1369 });
1370 }
1371 // Header
1372 config.assign({
1373 header: Header.fromUserConfig(config),
1374 });
1375 config.assign({
1376 storage: StorageUtils.createFromUserConfig(userConfig),
1377 });
1378 config.assign({
1379 pipeline: PipelineUtils.createFromConfig(config),
1380 });
1381 // Pagination
1382 config.assign({
1383 pagination: __assign({ enabled: userConfig.pagination === true ||
1384 userConfig.pagination instanceof Object }, userConfig.pagination),
1385 });
1386 // Search
1387 config.assign({
1388 search: __assign({ enabled: userConfig.search === true || userConfig.search instanceof Object }, userConfig.search),
1389 });
1390 // Translator
1391 config.assign({
1392 translator: new Translator(userConfig.language),
1393 });
1394 return config;
1395 };
1396 return Config;
1397}());
1398
1399function className() {
1400 var args = [];
1401 for (var _i = 0; _i < arguments.length; _i++) {
1402 args[_i] = arguments[_i];
1403 }
1404 var prefix = 'gridjs';
1405 return "" + prefix + args.reduce(function (prev, cur) { return prev + "-" + cur; }, '');
1406}
1407function classJoin() {
1408 var classNames = [];
1409 for (var _i = 0; _i < arguments.length; _i++) {
1410 classNames[_i] = arguments[_i];
1411 }
1412 return classNames
1413 .filter(function (x) { return x; })
1414 .reduce(function (className, prev) { return (className || '') + " " + prev; }, '')
1415 .trim();
1416}
1417
1418// container status
1419var Status;
1420(function (Status) {
1421 Status[Status["Init"] = 0] = "Init";
1422 Status[Status["Loading"] = 1] = "Loading";
1423 Status[Status["Loaded"] = 2] = "Loaded";
1424 Status[Status["Rendered"] = 3] = "Rendered";
1425 Status[Status["Error"] = 4] = "Error";
1426})(Status || (Status = {}));
1427
1428var TD = /** @class */ (function (_super) {
1429 __extends(TD, _super);
1430 function TD() {
1431 return _super !== null && _super.apply(this, arguments) || this;
1432 }
1433 TD.prototype.content = function () {
1434 if (this.props.column &&
1435 typeof this.props.column.formatter === 'function') {
1436 return this.props.column.formatter(this.props.cell.data, this.props.row, this.props.column);
1437 }
1438 return this.props.cell.data;
1439 };
1440 TD.prototype.handleClick = function (e) {
1441 this.config.eventEmitter.emit('cellClick', e, this.props.cell, this.props.column, this.props.row);
1442 };
1443 TD.prototype.render = function () {
1444 return (v("td", { role: this.props.role, colSpan: this.props.colSpan, className: classJoin(className('td'), this.props.className, this.config.className.td), style: __assign({}, this.config.style.td), onClick: this.handleClick.bind(this) }, this.content()));
1445 };
1446 return TD;
1447}(BaseComponent));
1448
1449var TR = /** @class */ (function (_super) {
1450 __extends(TR, _super);
1451 function TR() {
1452 return _super !== null && _super.apply(this, arguments) || this;
1453 }
1454 TR.prototype.getColumn = function (cellIndex) {
1455 if (this.props.header) {
1456 return this.props.header.columns[cellIndex];
1457 }
1458 return null;
1459 };
1460 TR.prototype.handleClick = function (e) {
1461 this.config.eventEmitter.emit('rowClick', e, this.props.row);
1462 };
1463 TR.prototype.render = function () {
1464 var _this = this;
1465 if (this.props.children) {
1466 return v("tr", { className: className('tr') }, this.props.children);
1467 }
1468 else {
1469 return (v("tr", { className: className('tr'), onClick: this.handleClick.bind(this) }, this.props.row.cells.map(function (cell, i) {
1470 return (v(TD, { key: cell.id, cell: cell, row: _this.props.row, column: _this.getColumn(i) }));
1471 })));
1472 }
1473 };
1474 return TR;
1475}(BaseComponent));
1476
1477var MessageRow = /** @class */ (function (_super) {
1478 __extends(MessageRow, _super);
1479 function MessageRow() {
1480 return _super !== null && _super.apply(this, arguments) || this;
1481 }
1482 MessageRow.prototype.render = function () {
1483 return (v(TR, null,
1484 v(TD, { role: "alert", colSpan: this.props.colSpan, cell: new Cell(this.props.message), className: classJoin(className('message'), this.props.className ? this.props.className : null) })));
1485 };
1486 return MessageRow;
1487}(BaseComponent));
1488
1489var TBody = /** @class */ (function (_super) {
1490 __extends(TBody, _super);
1491 function TBody() {
1492 return _super !== null && _super.apply(this, arguments) || this;
1493 }
1494 TBody.prototype.headerLength = function () {
1495 if (this.props.header) {
1496 return this.props.header.columns.length;
1497 }
1498 return 0;
1499 };
1500 TBody.prototype.render = function () {
1501 var _this = this;
1502 return (v("tbody", { className: className('tbody') },
1503 this.props.data &&
1504 this.props.data.rows.map(function (row) {
1505 return v(TR, { key: row.id, row: row, header: _this.props.header });
1506 }),
1507 this.props.status === Status.Loading &&
1508 (!this.props.data || this.props.data.length === 0) && (v(MessageRow, { message: this._('loading'), colSpan: this.headerLength(), className: className('loading') })),
1509 this.props.status === Status.Loaded &&
1510 this.props.data &&
1511 this.props.data.length === 0 && (v(MessageRow, { message: this._('noRecordsFound'), colSpan: this.headerLength(), className: className('notfound') })),
1512 this.props.status === Status.Error && (v(MessageRow, { message: this._('error'), colSpan: this.headerLength(), className: className('error') }))));
1513 };
1514 return TBody;
1515}(BaseComponent));
1516
1517var NativeSort = /** @class */ (function (_super) {
1518 __extends(NativeSort, _super);
1519 function NativeSort() {
1520 return _super !== null && _super.apply(this, arguments) || this;
1521 }
1522 NativeSort.prototype.validateProps = function () {
1523 for (var _i = 0, _a = this.props.columns; _i < _a.length; _i++) {
1524 var condition = _a[_i];
1525 if (condition.direction === undefined) {
1526 condition.direction = 1;
1527 }
1528 if (condition.direction !== 1 && condition.direction !== -1) {
1529 log.error("Invalid sort direction " + condition.direction);
1530 }
1531 }
1532 };
1533 Object.defineProperty(NativeSort.prototype, "type", {
1534 get: function () {
1535 return ProcessorType.Sort;
1536 },
1537 enumerable: false,
1538 configurable: true
1539 });
1540 NativeSort.prototype.compare = function (cellA, cellB) {
1541 if (cellA > cellB) {
1542 return 1;
1543 }
1544 else if (cellA < cellB) {
1545 return -1;
1546 }
1547 return 0;
1548 };
1549 NativeSort.prototype.compareWrapper = function (a, b) {
1550 var cmp = 0;
1551 for (var _i = 0, _a = this.props.columns; _i < _a.length; _i++) {
1552 var column = _a[_i];
1553 if (cmp === 0) {
1554 var cellA = a.cells[column.index].data;
1555 var cellB = b.cells[column.index].data;
1556 if (typeof column.compare === 'function') {
1557 cmp |= column.compare(cellA, cellB) * column.direction;
1558 }
1559 else {
1560 cmp |= this.compare(cellA, cellB) * column.direction;
1561 }
1562 }
1563 else {
1564 break;
1565 }
1566 }
1567 return cmp;
1568 };
1569 NativeSort.prototype._process = function (data) {
1570 var sortedRows = __spreadArrays(data.rows);
1571 sortedRows.sort(this.compareWrapper.bind(this));
1572 var sorted = new Tabular(sortedRows);
1573 // we have to set the tabular length manually
1574 // because of the server-side storage
1575 sorted.length = data.length;
1576 return sorted;
1577 };
1578 return NativeSort;
1579}(PipelineProcessor));
1580
1581var BaseStore = /** @class */ (function (_super) {
1582 __extends(BaseStore, _super);
1583 function BaseStore(dispatcher) {
1584 var _this = _super.call(this) || this;
1585 _this.dispatcher = dispatcher;
1586 _this._state = _this.getInitialState();
1587 dispatcher.register(_this._handle.bind(_this));
1588 return _this;
1589 }
1590 BaseStore.prototype._handle = function (action) {
1591 this.handle(action.type, action.payload);
1592 };
1593 BaseStore.prototype.setState = function (newState) {
1594 var prevState = this._state;
1595 this._state = newState;
1596 this.emit('updated', newState, prevState);
1597 };
1598 Object.defineProperty(BaseStore.prototype, "state", {
1599 get: function () {
1600 return this._state;
1601 },
1602 enumerable: false,
1603 configurable: true
1604 });
1605 return BaseStore;
1606}(EventEmitter));
1607
1608var SortStore = /** @class */ (function (_super) {
1609 __extends(SortStore, _super);
1610 function SortStore() {
1611 return _super !== null && _super.apply(this, arguments) || this;
1612 }
1613 SortStore.prototype.getInitialState = function () {
1614 return [];
1615 };
1616 SortStore.prototype.handle = function (type, payload) {
1617 if (type === 'SORT_COLUMN') {
1618 var index = payload.index, direction = payload.direction, multi = payload.multi, compare = payload.compare;
1619 this.sortColumn(index, direction, multi, compare);
1620 }
1621 else if (type === 'SORT_COLUMN_TOGGLE') {
1622 var index = payload.index, multi = payload.multi, compare = payload.compare;
1623 this.sortToggle(index, multi, compare);
1624 }
1625 };
1626 SortStore.prototype.sortToggle = function (index, multi, compare) {
1627 var columns = __spreadArrays(this.state);
1628 var column = columns.find(function (x) { return x.index === index; });
1629 if (!column) {
1630 this.sortColumn(index, 1, multi, compare);
1631 }
1632 else {
1633 this.sortColumn(index, column.direction === 1 ? -1 : 1, multi, compare);
1634 }
1635 };
1636 SortStore.prototype.sortColumn = function (index, direction, multi, compare) {
1637 var columns = __spreadArrays(this.state);
1638 var count = columns.length;
1639 var column = columns.find(function (x) { return x.index === index; });
1640 var exists = column !== undefined;
1641 var add = false;
1642 var reset = false;
1643 var remove = false;
1644 var update = false;
1645 if (!exists) {
1646 // the column has not been sorted
1647 if (count === 0) {
1648 // the first column to be sorted
1649 add = true;
1650 }
1651 else if (count > 0 && !multi) {
1652 // remove the previously sorted column
1653 // and sort the current column
1654 add = true;
1655 reset = true;
1656 }
1657 else if (count > 0 && multi) {
1658 // multi-sorting
1659 // sort this column as well
1660 add = true;
1661 }
1662 }
1663 else {
1664 // the column has been sorted before
1665 if (!multi) {
1666 // single column sorting
1667 if (count === 1) {
1668 update = true;
1669 }
1670 else if (count > 1) {
1671 // this situation happens when we have already entered
1672 // multi-sorting mode but then user tries to sort a single column
1673 reset = true;
1674 add = true;
1675 }
1676 }
1677 else {
1678 // multi sorting
1679 if (column.direction === -1) {
1680 // remove the current column from the
1681 // sorted columns array
1682 remove = true;
1683 }
1684 else {
1685 update = true;
1686 }
1687 }
1688 }
1689 if (reset) {
1690 // resetting the sorted columns
1691 columns = [];
1692 }
1693 if (add) {
1694 columns.push({
1695 index: index,
1696 direction: direction,
1697 compare: compare,
1698 });
1699 }
1700 else if (update) {
1701 var index_1 = columns.indexOf(column);
1702 columns[index_1].direction = direction;
1703 }
1704 else if (remove) {
1705 var index_2 = columns.indexOf(column);
1706 columns.splice(index_2, 1);
1707 }
1708 this.setState(columns);
1709 };
1710 return SortStore;
1711}(BaseStore));
1712
1713var BaseActions = /** @class */ (function () {
1714 function BaseActions(dispatcher) {
1715 this.dispatcher = dispatcher;
1716 }
1717 BaseActions.prototype.dispatch = function (type, payload) {
1718 this.dispatcher.dispatch({
1719 type: type,
1720 payload: payload,
1721 });
1722 };
1723 return BaseActions;
1724}());
1725
1726var SortActions = /** @class */ (function (_super) {
1727 __extends(SortActions, _super);
1728 function SortActions() {
1729 return _super !== null && _super.apply(this, arguments) || this;
1730 }
1731 SortActions.prototype.sortColumn = function (index, direction, multi, compare) {
1732 this.dispatch('SORT_COLUMN', {
1733 index: index,
1734 direction: direction,
1735 multi: multi,
1736 compare: compare,
1737 });
1738 };
1739 SortActions.prototype.sortToggle = function (index, multi, compare) {
1740 this.dispatch('SORT_COLUMN_TOGGLE', {
1741 index: index,
1742 multi: multi,
1743 compare: compare,
1744 });
1745 };
1746 return SortActions;
1747}(BaseActions));
1748
1749var ServerSort = /** @class */ (function (_super) {
1750 __extends(ServerSort, _super);
1751 function ServerSort() {
1752 return _super !== null && _super.apply(this, arguments) || this;
1753 }
1754 Object.defineProperty(ServerSort.prototype, "type", {
1755 get: function () {
1756 return ProcessorType.ServerSort;
1757 },
1758 enumerable: false,
1759 configurable: true
1760 });
1761 ServerSort.prototype._process = function (options) {
1762 var updates = {};
1763 if (this.props.url) {
1764 updates['url'] = this.props.url(options.url, this.props.columns);
1765 }
1766 if (this.props.body) {
1767 updates['body'] = this.props.body(options.body, this.props.columns);
1768 }
1769 return __assign(__assign({}, options), updates);
1770 };
1771 return ServerSort;
1772}(PipelineProcessor));
1773
1774var Sort = /** @class */ (function (_super) {
1775 __extends(Sort, _super);
1776 function Sort(props, context) {
1777 var _this = _super.call(this, props, context) || this;
1778 _this.actions = new SortActions(_this.config.dispatcher);
1779 _this.store = new SortStore(_this.config.dispatcher);
1780 if (props.enabled) {
1781 _this.sortProcessor = _this.getOrCreateSortProcessor();
1782 _this.updateStateFn = _this.updateState.bind(_this);
1783 _this.store.on('updated', _this.updateStateFn);
1784 _this.state = { direction: 0 };
1785 }
1786 return _this;
1787 }
1788 Sort.prototype.componentWillUnmount = function () {
1789 this.config.pipeline.unregister(this.sortProcessor);
1790 this.store.off('updated', this.updateStateFn);
1791 if (this.updateSortProcessorFn)
1792 this.store.off('updated', this.updateSortProcessorFn);
1793 };
1794 /**
1795 * Sets the internal state of component
1796 */
1797 Sort.prototype.updateState = function () {
1798 var _this = this;
1799 var currentColumn = this.store.state.find(function (x) { return x.index === _this.props.index; });
1800 if (!currentColumn) {
1801 this.setState({
1802 direction: 0,
1803 });
1804 }
1805 else {
1806 this.setState({
1807 direction: currentColumn.direction,
1808 });
1809 }
1810 };
1811 Sort.prototype.updateSortProcessor = function (sortedColumns) {
1812 // updates the Sorting processor
1813 this.sortProcessor.setProps({
1814 columns: sortedColumns,
1815 });
1816 };
1817 Sort.prototype.getOrCreateSortProcessor = function () {
1818 var processorType = ProcessorType.Sort;
1819 if (this.config.sort && typeof this.config.sort.server === 'object') {
1820 processorType = ProcessorType.ServerSort;
1821 }
1822 var processors = this.config.pipeline.getStepsByType(processorType);
1823 // my assumption is that we only have ONE sorting processor in the
1824 // entire pipeline and that's why I'm displaying a warning here
1825 var processor;
1826 // A sort process is already registered
1827 if (processors.length > 0) {
1828 processor = processors[0];
1829 }
1830 else {
1831 // let's create a new sort processor
1832 // this event listener is here because
1833 // we want to subscribe to the sort store only once
1834 this.updateSortProcessorFn = this.updateSortProcessor.bind(this);
1835 this.store.on('updated', this.updateSortProcessorFn);
1836 if (processorType === ProcessorType.ServerSort) {
1837 processor = new ServerSort(__assign({ columns: this.store.state }, this.config.sort.server));
1838 }
1839 else {
1840 processor = new NativeSort({
1841 columns: this.store.state,
1842 });
1843 }
1844 this.config.pipeline.register(processor);
1845 }
1846 return processor;
1847 };
1848 Sort.prototype.changeDirection = function (e) {
1849 e.preventDefault();
1850 e.stopPropagation();
1851 // to sort two or more columns at the same time
1852 this.actions.sortToggle(this.props.index, e.shiftKey === true && this.config.sort.multiColumn, this.props.compare);
1853 };
1854 Sort.prototype.render = function () {
1855 if (!this.props.enabled) {
1856 return null;
1857 }
1858 var direction = this.state.direction;
1859 var sortClassName = 'neutral';
1860 if (direction === 1) {
1861 sortClassName = 'asc';
1862 }
1863 else if (direction === -1) {
1864 sortClassName = 'desc';
1865 }
1866 return (v("button", {
1867 // because the corresponding <th> has tabIndex=0
1868 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)), onClick: this.changeDirection.bind(this) }));
1869 };
1870 return Sort;
1871}(BaseComponent));
1872
1873var TH = /** @class */ (function (_super) {
1874 __extends(TH, _super);
1875 function TH() {
1876 var _this = _super !== null && _super.apply(this, arguments) || this;
1877 _this.sortRef = y();
1878 return _this;
1879 }
1880 TH.prototype.isSortable = function () {
1881 return this.props.column.sort.enabled;
1882 };
1883 TH.prototype.onClick = function (e) {
1884 e.stopPropagation();
1885 if (this.isSortable()) {
1886 this.sortRef.current.changeDirection(e);
1887 }
1888 };
1889 TH.prototype.keyDown = function (e) {
1890 if (this.isSortable() && e.which === 13) {
1891 this.onClick(e);
1892 }
1893 };
1894 TH.prototype.render = function () {
1895 var props = {};
1896 if (this.isSortable()) {
1897 props['tabIndex'] = 0;
1898 }
1899 return (v("th", __assign({ className: classJoin(className('th'), this.isSortable() ? className('th', 'sort') : null, this.config.className.th), onClick: this.onClick.bind(this), style: __assign(__assign({}, this.config.style.th), { width: this.props.column.width }), onKeyDown: this.keyDown.bind(this) }, props),
1900 this.props.column.name,
1901 this.isSortable() && (v(Sort, __assign({ ref: this.sortRef, index: this.props.index }, this.props.column.sort)))));
1902 };
1903 return TH;
1904}(BaseComponent));
1905
1906var THead = /** @class */ (function (_super) {
1907 __extends(THead, _super);
1908 function THead() {
1909 return _super !== null && _super.apply(this, arguments) || this;
1910 }
1911 THead.prototype.render = function () {
1912 if (this.props.header) {
1913 return (v("thead", { key: this.props.header.id, className: className('thead') },
1914 v(TR, null, this.props.header.columns.map(function (col, i) {
1915 return v(TH, { column: col, index: i });
1916 }))));
1917 }
1918 return null;
1919 };
1920 return THead;
1921}(BaseComponent));
1922
1923var Table = /** @class */ (function (_super) {
1924 __extends(Table, _super);
1925 function Table() {
1926 return _super !== null && _super.apply(this, arguments) || this;
1927 }
1928 Table.prototype.render = function () {
1929 return (v("table", { role: "grid", className: classJoin(className('table'), this.config.className.table), style: __assign(__assign({}, this.config.style.table), {
1930 width: this.props.width,
1931 }) },
1932 v(THead, { header: this.props.header }),
1933 v(TBody, { data: this.props.data, status: this.props.status, header: this.props.header })));
1934 };
1935 return Table;
1936}(BaseComponent));
1937
1938function search (keyword, tabular) {
1939 // escape special regex chars
1940 keyword = keyword.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
1941 return new Tabular(tabular.rows.filter(function (row) {
1942 return row.cells.some(function (cell) {
1943 if (!cell || !cell.data) {
1944 return false;
1945 }
1946 var data = '';
1947 if (typeof cell.data === 'object') {
1948 // HTMLContent element
1949 var element = cell.data;
1950 if (element.props && element.props.content) {
1951 // TODO: we should only search in the content of the element. props.content is the entire HTML element
1952 data = element.props.content;
1953 }
1954 }
1955 else {
1956 // primitive types
1957 data = String(cell.data);
1958 }
1959 return new RegExp(keyword, 'gi').test(data);
1960 });
1961 }));
1962}
1963
1964var GlobalSearchFilter = /** @class */ (function (_super) {
1965 __extends(GlobalSearchFilter, _super);
1966 function GlobalSearchFilter() {
1967 return _super !== null && _super.apply(this, arguments) || this;
1968 }
1969 Object.defineProperty(GlobalSearchFilter.prototype, "type", {
1970 get: function () {
1971 return ProcessorType.Filter;
1972 },
1973 enumerable: false,
1974 configurable: true
1975 });
1976 GlobalSearchFilter.prototype._process = function (data) {
1977 if (this.props.keyword) {
1978 return search(String(this.props.keyword).trim(), data);
1979 }
1980 return data;
1981 };
1982 return GlobalSearchFilter;
1983}(PipelineProcessor));
1984
1985var SearchStore = /** @class */ (function (_super) {
1986 __extends(SearchStore, _super);
1987 function SearchStore() {
1988 return _super !== null && _super.apply(this, arguments) || this;
1989 }
1990 SearchStore.prototype.getInitialState = function () {
1991 return { keyword: null };
1992 };
1993 SearchStore.prototype.handle = function (type, payload) {
1994 if (type === 'SEARCH_KEYWORD') {
1995 var keyword = payload.keyword;
1996 this.search(keyword);
1997 }
1998 };
1999 SearchStore.prototype.search = function (keyword) {
2000 this.setState({ keyword: keyword });
2001 };
2002 return SearchStore;
2003}(BaseStore));
2004
2005var SearchActions = /** @class */ (function (_super) {
2006 __extends(SearchActions, _super);
2007 function SearchActions() {
2008 return _super !== null && _super.apply(this, arguments) || this;
2009 }
2010 SearchActions.prototype.search = function (keyword) {
2011 this.dispatch('SEARCH_KEYWORD', {
2012 keyword: keyword,
2013 });
2014 };
2015 return SearchActions;
2016}(BaseActions));
2017
2018var ServerGlobalSearchFilter = /** @class */ (function (_super) {
2019 __extends(ServerGlobalSearchFilter, _super);
2020 function ServerGlobalSearchFilter() {
2021 return _super !== null && _super.apply(this, arguments) || this;
2022 }
2023 Object.defineProperty(ServerGlobalSearchFilter.prototype, "type", {
2024 get: function () {
2025 return ProcessorType.ServerFilter;
2026 },
2027 enumerable: false,
2028 configurable: true
2029 });
2030 ServerGlobalSearchFilter.prototype._process = function (options) {
2031 if (!this.props.keyword)
2032 return options;
2033 var updates = {};
2034 if (this.props.url) {
2035 updates['url'] = this.props.url(options.url, this.props.keyword);
2036 }
2037 if (this.props.body) {
2038 updates['body'] = this.props.body(options.body, this.props.keyword);
2039 }
2040 return __assign(__assign({}, options), updates);
2041 };
2042 return ServerGlobalSearchFilter;
2043}(PipelineProcessor));
2044
2045var debounce = function (func, waitFor) {
2046 var timeout;
2047 return function () {
2048 var args = [];
2049 for (var _i = 0; _i < arguments.length; _i++) {
2050 args[_i] = arguments[_i];
2051 }
2052 return new Promise(function (resolve) {
2053 if (timeout) {
2054 clearTimeout(timeout);
2055 }
2056 timeout = setTimeout(function () { return resolve(func.apply(void 0, args)); }, waitFor);
2057 });
2058 };
2059};
2060
2061var Search = /** @class */ (function (_super) {
2062 __extends(Search, _super);
2063 function Search(props, context) {
2064 var _this = _super.call(this, props, context) || this;
2065 _this.actions = new SearchActions(_this.config.dispatcher);
2066 _this.store = new SearchStore(_this.config.dispatcher);
2067 var enabled = props.enabled, keyword = props.keyword;
2068 if (enabled) {
2069 // initial search
2070 _this.actions.search(keyword);
2071 _this.storeUpdatedFn = _this.storeUpdated.bind(_this);
2072 _this.store.on('updated', _this.storeUpdatedFn);
2073 var searchProcessor = void 0;
2074 if (props.server) {
2075 searchProcessor = new ServerGlobalSearchFilter({
2076 keyword: props.keyword,
2077 url: props.server.url,
2078 body: props.server.body,
2079 });
2080 }
2081 else {
2082 searchProcessor = new GlobalSearchFilter({
2083 keyword: props.keyword,
2084 });
2085 }
2086 _this.searchProcessor = searchProcessor;
2087 // adds a new processor to the pipeline
2088 _this.config.pipeline.register(searchProcessor);
2089 }
2090 return _this;
2091 }
2092 Search.prototype.componentWillUnmount = function () {
2093 this.config.pipeline.unregister(this.searchProcessor);
2094 this.store.off('updated', this.storeUpdatedFn);
2095 };
2096 Search.prototype.storeUpdated = function (state) {
2097 // updates the processor state
2098 this.searchProcessor.setProps({
2099 keyword: state.keyword,
2100 });
2101 };
2102 Search.prototype.onChange = function (event) {
2103 var keyword = event.target.value;
2104 this.actions.search(keyword);
2105 };
2106 Search.prototype.render = function () {
2107 if (!this.props.enabled)
2108 return null;
2109 var onInput = this.onChange.bind(this);
2110 // add debounce to input only if it's a server-side search
2111 if (this.searchProcessor instanceof ServerGlobalSearchFilter) {
2112 onInput = debounce(onInput, this.props.debounceTimeout);
2113 }
2114 return (v("div", { className: className('search') },
2115 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 })));
2116 };
2117 Search.defaultProps = {
2118 debounceTimeout: 250,
2119 };
2120 return Search;
2121}(BaseComponent));
2122
2123var t$1,u$1,r$1,o$1=0,i$1=[],c$1=n.__r,f$1=n.diffed,e$1=n.__c,a$1=n.unmount;function v$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=v$1(t$1++,3);!n.__s&&j$1(i.__H,o)&&(i.__=r,i.__H=o,u$1.__H.__h.push(i));}function h$1(n){return o$1=5,_$1(function(){return {current:n}},[])}function _$1(n,u){var r=v$1(t$1++,7);return j$1(r.__H,u)?(r.__H=u,r.__h=n,r.__=n()):r.__}function q$1(){i$1.some(function(t){if(t.__P)try{t.__H.__h.forEach(b),t.__H.__h.forEach(g$1),t.__H.__h=[];}catch(u){return t.__H.__h=[],n.__e(u,t.__v),!0}}),i$1=[];}n.__r=function(n){c$1&&c$1(n),t$1=0;var r=(u$1=n.__c).__H;r&&(r.__h.forEach(b),r.__h.forEach(g$1),r.__h=[]);},n.diffed=function(t){f$1&&f$1(t);var u=t.__c;u&&u.__H&&u.__H.__h.length&&(1!==i$1.push(u)&&r$1===n.requestAnimationFrame||((r$1=n.requestAnimationFrame)||function(n){var t,u=function(){clearTimeout(r),x$1&&cancelAnimationFrame(t),setTimeout(n);},r=setTimeout(u,100);x$1&&(t=requestAnimationFrame(u));})(q$1));},n.__c=function(t,u){u.some(function(t){try{t.__h.forEach(b),t.__h=t.__h.filter(function(n){return !n.__||g$1(n)});}catch(r){u.some(function(n){n.__h&&(n.__h=[]);}),u=[],n.__e(r,t.__v);}}),e$1&&e$1(t,u);},n.unmount=function(t){a$1&&a$1(t);var u=t.__c;if(u&&u.__H)try{u.__H.__.forEach(b);}catch(t){n.__e(t,u.__v);}};var x$1="function"==typeof requestAnimationFrame;function b(n){"function"==typeof n.u&&n.u();}function g$1(n){n.u=n.__();}function j$1(n,t){return !n||t.some(function(t,u){return t!==n[u]})}
2124
2125var HeaderContainer = /** @class */ (function (_super) {
2126 __extends(HeaderContainer, _super);
2127 function HeaderContainer(props, context) {
2128 var _this = _super.call(this, props, context) || this;
2129 _this.headerRef = h$1(null);
2130 _this.state = {
2131 isActive: true,
2132 };
2133 return _this;
2134 }
2135 HeaderContainer.prototype.componentDidMount = function () {
2136 if (this.headerRef.current.children.length === 0) {
2137 this.setState({
2138 isActive: false,
2139 });
2140 }
2141 };
2142 HeaderContainer.prototype.render = function () {
2143 if (this.state.isActive) {
2144 return (v("div", { ref: this.headerRef, className: classJoin(className('head'), this.config.className.header), style: __assign({}, this.config.style.header) },
2145 v(Search, __assign({}, this.config.search))));
2146 }
2147 return null;
2148 };
2149 return HeaderContainer;
2150}(BaseComponent));
2151
2152var PaginationLimit = /** @class */ (function (_super) {
2153 __extends(PaginationLimit, _super);
2154 function PaginationLimit() {
2155 return _super !== null && _super.apply(this, arguments) || this;
2156 }
2157 PaginationLimit.prototype.validateProps = function () {
2158 if (isNaN(Number(this.props.limit)) || isNaN(Number(this.props.page))) {
2159 throw Error('Invalid parameters passed');
2160 }
2161 };
2162 Object.defineProperty(PaginationLimit.prototype, "type", {
2163 get: function () {
2164 return ProcessorType.Limit;
2165 },
2166 enumerable: false,
2167 configurable: true
2168 });
2169 PaginationLimit.prototype._process = function (data) {
2170 var page = this.props.page;
2171 var start = page * this.props.limit;
2172 var end = (page + 1) * this.props.limit;
2173 return new Tabular(data.rows.slice(start, end));
2174 };
2175 return PaginationLimit;
2176}(PipelineProcessor));
2177
2178var ServerPaginationLimit = /** @class */ (function (_super) {
2179 __extends(ServerPaginationLimit, _super);
2180 function ServerPaginationLimit() {
2181 return _super !== null && _super.apply(this, arguments) || this;
2182 }
2183 Object.defineProperty(ServerPaginationLimit.prototype, "type", {
2184 get: function () {
2185 return ProcessorType.ServerLimit;
2186 },
2187 enumerable: false,
2188 configurable: true
2189 });
2190 ServerPaginationLimit.prototype._process = function (options) {
2191 var updates = {};
2192 if (this.props.url) {
2193 updates['url'] = this.props.url(options.url, this.props.page, this.props.limit);
2194 }
2195 if (this.props.body) {
2196 updates['body'] = this.props.body(options.body, this.props.page, this.props.limit);
2197 }
2198 return __assign(__assign({}, options), updates);
2199 };
2200 return ServerPaginationLimit;
2201}(PipelineProcessor));
2202
2203var Pagination = /** @class */ (function (_super) {
2204 __extends(Pagination, _super);
2205 function Pagination(props, context) {
2206 var _this = _super.call(this, props, context) || this;
2207 _this.state = {
2208 limit: props.limit,
2209 page: props.page || 0,
2210 total: 0,
2211 };
2212 return _this;
2213 }
2214 Pagination.prototype.componentWillMount = function () {
2215 var _this = this;
2216 if (this.props.enabled) {
2217 var processor = void 0;
2218 this.setTotalFromTabularFn = this.setTotalFromTabular.bind(this);
2219 if (this.props.server) {
2220 processor = new ServerPaginationLimit({
2221 limit: this.state.limit,
2222 page: this.state.page,
2223 url: this.props.server.url,
2224 body: this.props.server.body,
2225 });
2226 this.config.pipeline.on('afterProcess', this.setTotalFromTabularFn);
2227 }
2228 else {
2229 processor = new PaginationLimit({
2230 limit: this.state.limit,
2231 page: this.state.page,
2232 });
2233 // Pagination (all Limit processors) is the last step in the pipeline
2234 // and we assume that at this stage, we have the rows that we care about.
2235 // Let's grab the rows before processing Pagination and set total number of rows
2236 processor.on('beforeProcess', this.setTotalFromTabularFn);
2237 }
2238 this.processor = processor;
2239 this.config.pipeline.register(processor);
2240 // we need to make sure that the state is set
2241 // to the default props when an error happens
2242 this.config.pipeline.on('error', function () {
2243 _this.setState({
2244 total: 0,
2245 page: 0,
2246 });
2247 });
2248 }
2249 };
2250 Pagination.prototype.setTotalFromTabular = function (tabular) {
2251 this.setTotal(tabular.length);
2252 };
2253 Pagination.prototype.onUpdate = function (processor) {
2254 // this is to ensure that the current page is set to 0
2255 // when a processor is updated for some reason
2256 if (this.props.resetPageOnUpdate && processor !== this.processor) {
2257 this.setPage(0);
2258 }
2259 };
2260 Pagination.prototype.componentDidMount = function () {
2261 this.onUpdateFn = this.onUpdate.bind(this);
2262 this.config.pipeline.on('updated', this.onUpdateFn);
2263 };
2264 Pagination.prototype.componentWillUnmount = function () {
2265 this.config.pipeline.unregister(this.processor);
2266 this.config.pipeline.off('updated', this.onUpdateFn);
2267 };
2268 Object.defineProperty(Pagination.prototype, "pages", {
2269 get: function () {
2270 return Math.ceil(this.state.total / this.state.limit);
2271 },
2272 enumerable: false,
2273 configurable: true
2274 });
2275 Pagination.prototype.setPage = function (page) {
2276 if (page >= this.pages || page < 0 || page === this.state.page) {
2277 return null;
2278 }
2279 this.setState({
2280 page: page,
2281 });
2282 this.processor.setProps({
2283 page: page,
2284 });
2285 };
2286 Pagination.prototype.setTotal = function (totalRows) {
2287 // to set the correct total number of rows
2288 // when running in-memory operations
2289 this.setState({
2290 total: totalRows,
2291 });
2292 };
2293 Pagination.prototype.renderPages = function () {
2294 var _this = this;
2295 if (this.props.buttonsCount <= 0) {
2296 return null;
2297 }
2298 // how many pagination buttons to render?
2299 var maxCount = Math.min(this.pages, this.props.buttonsCount);
2300 var pagePivot = Math.min(this.state.page, Math.floor(maxCount / 2));
2301 if (this.state.page + Math.floor(maxCount / 2) >= this.pages) {
2302 pagePivot = maxCount - (this.pages - this.state.page);
2303 }
2304 return (v(p, null,
2305 this.pages > maxCount && this.state.page - pagePivot > 0 && (v(p, null,
2306 v("button", { tabIndex: 0, onClick: this.setPage.bind(this, 0), title: this._('pagination.firstPage') }, this._('1')),
2307 v("button", { tabIndex: -1, className: className('spread') }, "..."))),
2308 Array.from(Array(maxCount).keys())
2309 .map(function (i) { return _this.state.page + (i - pagePivot); })
2310 .map(function (i) { return (v("button", { tabIndex: 0, onClick: _this.setPage.bind(_this, i), className: _this.state.page === i ? className('currentPage') : null, title: _this._('pagination.page', i + 1) }, _this._("" + (i + 1)))); }),
2311 this.pages > maxCount && this.pages > this.state.page + pagePivot + 1 && (v(p, null,
2312 v("button", { tabIndex: -1, className: className('spread') }, "..."),
2313 v("button", { tabIndex: 0, onClick: this.setPage.bind(this, this.pages - 1), title: this._('pagination.page', this.pages) }, this._("" + this.pages))))));
2314 };
2315 Pagination.prototype.renderSummary = function () {
2316 return (v(p, null, this.props.summary && this.state.total > 0 && (v("div", { role: "status", className: className('summary'), title: this._('pagination.navigate', this.state.page + 1, this.pages) },
2317 this._('pagination.showing'),
2318 ' ',
2319 v("b", null, this._("" + (this.state.page * this.state.limit + 1))),
2320 ' ',
2321 this._('pagination.to'),
2322 ' ',
2323 v("b", null, this._("" + Math.min((this.state.page + 1) * this.state.limit, this.state.total))),
2324 ' ',
2325 this._('pagination.of'),
2326 " ",
2327 v("b", null, this._("" + this.state.total)),
2328 ' ',
2329 this._('pagination.results')))));
2330 };
2331 Pagination.prototype.render = function () {
2332 if (!this.props.enabled)
2333 return null;
2334 return (v("div", { className: className('pagination') },
2335 this.renderSummary(),
2336 v("div", { className: className('pages') },
2337 this.props.prevButton && (v("button", { tabIndex: 0, disabled: this.state.page === 0, onClick: this.setPage.bind(this, this.state.page - 1) }, this._('pagination.previous'))),
2338 this.renderPages(),
2339 this.props.nextButton && (v("button", { tabIndex: 0, disabled: this.pages === this.state.page + 1 || this.pages === 0, onClick: this.setPage.bind(this, this.state.page + 1) }, this._('pagination.next'))))));
2340 };
2341 Pagination.defaultProps = {
2342 summary: true,
2343 nextButton: true,
2344 prevButton: true,
2345 buttonsCount: 3,
2346 limit: 10,
2347 resetPageOnUpdate: true,
2348 };
2349 return Pagination;
2350}(BaseComponent));
2351
2352var FooterContainer = /** @class */ (function (_super) {
2353 __extends(FooterContainer, _super);
2354 function FooterContainer(props, context) {
2355 var _this = _super.call(this, props, context) || this;
2356 _this.footerRef = h$1(null);
2357 _this.state = {
2358 isActive: true,
2359 };
2360 return _this;
2361 }
2362 FooterContainer.prototype.componentDidMount = function () {
2363 if (this.footerRef.current.children.length === 0) {
2364 this.setState({
2365 isActive: false,
2366 });
2367 }
2368 };
2369 FooterContainer.prototype.render = function () {
2370 if (this.state.isActive) {
2371 return (v("div", { ref: this.footerRef, className: classJoin(className('footer'), this.config.className.footer), style: __assign({}, this.config.style.footer) },
2372 v(Pagination, __assign({}, this.config.pagination))));
2373 }
2374 return null;
2375 };
2376 return FooterContainer;
2377}(BaseComponent));
2378
2379var Container = /** @class */ (function (_super) {
2380 __extends(Container, _super);
2381 function Container(props, context) {
2382 var _this = _super.call(this, props, context) || this;
2383 // global Config context which is passed to all components
2384 _this.configContext = q(null);
2385 _this.state = {
2386 status: Status.Loading,
2387 header: props.header,
2388 data: null,
2389 };
2390 return _this;
2391 }
2392 Container.prototype.processPipeline = function () {
2393 return __awaiter(this, void 0, void 0, function () {
2394 var data, e_1;
2395 return __generator(this, function (_a) {
2396 switch (_a.label) {
2397 case 0:
2398 this.props.config.eventEmitter.emit('beforeLoad');
2399 this.setState({
2400 status: Status.Loading,
2401 });
2402 _a.label = 1;
2403 case 1:
2404 _a.trys.push([1, 3, , 4]);
2405 return [4 /*yield*/, this.props.pipeline.process()];
2406 case 2:
2407 data = _a.sent();
2408 this.setState({
2409 data: data,
2410 status: Status.Loaded,
2411 });
2412 this.props.config.eventEmitter.emit('load', data);
2413 return [3 /*break*/, 4];
2414 case 3:
2415 e_1 = _a.sent();
2416 log.error(e_1);
2417 this.setState({
2418 status: Status.Error,
2419 data: null,
2420 });
2421 return [3 /*break*/, 4];
2422 case 4: return [2 /*return*/];
2423 }
2424 });
2425 });
2426 };
2427 Container.prototype.componentDidMount = function () {
2428 return __awaiter(this, void 0, void 0, function () {
2429 var config;
2430 return __generator(this, function (_a) {
2431 switch (_a.label) {
2432 case 0:
2433 config = this.props.config;
2434 // for the initial load
2435 return [4 /*yield*/, this.processPipeline()];
2436 case 1:
2437 // for the initial load
2438 _a.sent();
2439 if (config.header && this.state.data && this.state.data.length) {
2440 // now that we have the data, let's adjust columns width
2441 // NOTE: that we only calculate the columns width once
2442 this.setState({
2443 header: config.header.adjustWidth(config.container, config.tempRef, this.state.data, config.autoWidth),
2444 });
2445 }
2446 this.processPipelineFn = this.processPipeline.bind(this);
2447 this.props.pipeline.on('updated', this.processPipelineFn);
2448 return [2 /*return*/];
2449 }
2450 });
2451 });
2452 };
2453 Container.prototype.componentWillUnmount = function () {
2454 this.props.pipeline.off('updated', this.processPipelineFn);
2455 };
2456 Container.prototype.render = function () {
2457 var configContext = this.configContext;
2458 return (v(configContext.Provider, { value: this.props.config },
2459 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), {
2460 width: this.props.width,
2461 }) },
2462 this.state.status === Status.Loading && (v("div", { className: className('loading-bar') })),
2463 v(HeaderContainer, null),
2464 v("div", { className: className('wrapper'), style: { width: this.props.width } },
2465 v(Table, { data: this.state.data, header: this.state.header, width: this.props.width, status: this.state.status })),
2466 v(FooterContainer, null)),
2467 v("div", { ref: this.props.config.tempRef, id: "gridjs-temp", className: className('temp') })));
2468 };
2469 return Container;
2470}(BaseComponent));
2471
2472var Grid = /** @class */ (function (_super) {
2473 __extends(Grid, _super);
2474 function Grid(userConfig) {
2475 var _this = _super.call(this) || this;
2476 _this.config = new Config({ eventEmitter: _this }).update(userConfig);
2477 return _this;
2478 }
2479 Grid.prototype.updateConfig = function (userConfig) {
2480 this.config.update(userConfig);
2481 return this;
2482 };
2483 Grid.prototype.createElement = function () {
2484 return v(Container, {
2485 config: this.config,
2486 pipeline: this.config.pipeline,
2487 header: this.config.header,
2488 width: this.config.width,
2489 });
2490 };
2491 /**
2492 * Uses the existing container and tries to clear the cache
2493 * and re-render the existing Grid.js instance again. This is
2494 * useful when a new config is set/updated.
2495 *
2496 */
2497 Grid.prototype.forceRender = function () {
2498 if (!this.config || !this.config.container) {
2499 log.error('Container is empty. Make sure you call render() before forceRender()', true);
2500 }
2501 // clear the pipeline cache
2502 this.config.pipeline.clearCache();
2503 // TODO: not sure if it's a good idea to render a null element but I couldn't find a better way
2504 M(null, this.config.container);
2505 M(this.createElement(), this.config.container);
2506 return this;
2507 };
2508 /**
2509 * Mounts the Grid.js instance to the container
2510 * and renders the instance
2511 *
2512 * @param container
2513 */
2514 Grid.prototype.render = function (container) {
2515 if (!container) {
2516 log.error('Container element cannot be null', true);
2517 }
2518 if (container.childNodes.length > 0) {
2519 log.error("The container element " + container + " is not empty. Make sure the container is empty and call render() again");
2520 return this;
2521 }
2522 this.config.container = container;
2523 M(this.createElement(), container);
2524 return this;
2525 };
2526 return Grid;
2527}(EventEmitter));
2528
2529export { d as Component, Config, Grid, v as createElement, y as createRef, v as h, html, y$1 as useEffect, h$1 as useRef };
2530//# sourceMappingURL=gridjs.development.es.js.map