descending, false -> ascending\nSortableTable.prototype.defaultDescending = false;\n\n// shared between all instances. This is intentional to allow external files\n// to modify the prototype\nSortableTable.prototype._sortTypeInfo = {};\n\nSortableTable.prototype.setTable = function (oTable) {\n\tif ( this.tHead )\n\t\tthis.uninitHeader();\n\tthis.element = oTable;\n\tthis.setTHead( oTable.tHead );\n\tthis.setTBody( oTable.tBodies[0] );\n};\n\nSortableTable.prototype.setTHead = function (oTHead) {\n\tif (this.tHead && this.tHead != oTHead )\n\t\tthis.uninitHeader();\n\tthis.tHead = oTHead;\n\tthis.initHeader( this.sortTypes );\n};\n\nSortableTable.prototype.setTBody = function (oTBody) {\n\tthis.tBody = oTBody;\n};\n\nSortableTable.prototype.setSortTypes = function ( oSortTypes ) {\n\tif ( this.tHead )\n\t\tthis.uninitHeader();\n\tthis.sortTypes = oSortTypes || [];\n\tif ( this.tHead )\n\t\tthis.initHeader( this.sortTypes );\n};\n\n// adds arrow containers and events\n// also binds sort type to the header cells so that reordering columns does\n// not break the sort types\nSortableTable.prototype.initHeader = function (oSortTypes) {\n\tif (!this.tHead) return;\n\tvar cells = this.tHead.rows[0].cells;\n\tvar doc = this.tHead.ownerDocument || this.tHead.document;\n\tthis.sortTypes = oSortTypes || [];\n\tvar l = cells.length;\n\tvar img, c;\n\tfor (var i = 0; i < l; i++) {\n\t\tc = cells[i];\n\t\tif (this.sortTypes[i] != null && this.sortTypes[i] != "None") {\n\t\t\timg = doc.createElement("IMG");\n\t\t\timg.src = "images/blank.png";\n\t\t\tc.appendChild(img);\n\t\t\tif (this.sortTypes[i] != null)\n\t\t\t\tc._sortType = this.sortTypes[i];\n\t\t\tif (typeof c.addEventListener != "undefined")\n\t\t\t\tc.addEventListener("click", this._headerOnclick, false);\n\t\t\telse if (typeof c.attachEvent != "undefined")\n\t\t\t\tc.attachEvent("onclick", this._headerOnclick);\n\t\t\telse\n\t\t\t\tc.onclick = this._headerOnclick;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tc.setAttribute( "_sortType", oSortTypes[i] );\n\t\t\tc._sortType = "None";\n\t\t}\n\t}\n\tthis.updateHeaderArrows();\n};\n\n// remove arrows and events\nSortableTable.prototype.uninitHeader = function () {\n\tif (!this.tHead) return;\n\tvar cells = this.tHead.rows[0].cells;\n\tvar l = cells.length;\n\tvar c;\n\tfor (var i = 0; i < l; i++) {\n\t\tc = cells[i];\n\t\tif (c._sortType != null && c._sortType != "None") {\n\t\t\tc.removeChild(c.lastChild);\n\t\t\tif (typeof c.removeEventListener != "undefined")\n\t\t\t\tc.removeEventListener("click", this._headerOnclick, false);\n\t\t\telse if (typeof c.detachEvent != "undefined")\n\t\t\t\tc.detachEvent("onclick", this._headerOnclick);\n\t\t\tc._sortType = null;\n\t\t\tc.removeAttribute( "_sortType" );\n\t\t}\n\t}\n};\n\nSortableTable.prototype.updateHeaderArrows = function () {\n\tif (!this.tHead) return;\n\tvar cells = this.tHead.rows[0].cells;\n\tvar l = cells.length;\n\tvar img;\n\tfor (var i = 0; i < l; i++) {\n\t\tif (cells[i]._sortType != null && cells[i]._sortType != "None") {\n\t\t\timg = cells[i].lastChild;\n\t\t\tif (i == this.sortColumn)\n\t\t\t\timg.className = "sort-arrow " + (this.descending ? "descending" : "ascending");\n\t\t\telse\n\t\t\t\timg.className = "sort-arrow";\n\t\t}\n\t}\n};\n\nSortableTable.prototype.headerOnclick = function (e) {\n\t// find TD element\n\tvar el = e.target || e.srcElement;\n\twhile (el.tagName != "TD")\n\t\tel = el.parentNode;\n\n\tthis.sort(SortableTable.msie ? SortableTable.getCellIndex(el) : el.cellIndex);\n};\n\n// IE returns wrong cellIndex when columns are hidden\nSortableTable.getCellIndex = function (oTd) {\n\tvar cells = oTd.parentNode.childNodes\n\tvar l = cells.length;\n\tvar i;\n\tfor (i = 0; cells[i] != oTd && i < l; i++)\n\t\t;\n\treturn i;\n};\n\nSortableTable.prototype.getSortType = function (nColumn) {\n\treturn this.sortTypes[nColumn] || "String";\n};\n\n// only nColumn is required\n// if bDescending is left out the old value is taken into account\n// if sSortType is left out the sort type is found from the sortTypes array\n\nSortableTable.prototype.sort = function (nColumn, bDescending, sSortType) {\n\tif (!this.tBody) return;\n\tif (sSortType == null)\n\t\tsSortType = this.getSortType(nColumn);\n\n\t// exit if None\n\tif (sSortType == "None")\n\t\treturn;\n\n\tif (bDescending == null) {\n\t\tif (this.sortColumn != nColumn)\n\t\t\tthis.descending = this.defaultDescending;\n\t\telse\n\t\t\tthis.descending = !this.descending;\n\t}\n\telse\n\t\tthis.descending = bDescending;\n\n\tthis.sortColumn = nColumn;\n\n\tif (typeof this.onbeforesort == "function")\n\t\tthis.onbeforesort();\n\n\tvar f = this.getSortFunction(sSortType, nColumn);\n\tvar a = this.getCache(sSortType, nColumn);\n\tvar tBody = this.tBody;\n\n\ta.sort(f);\n\n\tif (this.descending)\n\t\ta.reverse();\n\n\tif (SortableTable.removeBeforeSort) {\n\t\t// remove from doc\n\t\tvar nextSibling = tBody.nextSibling;\n\t\tvar p = tBody.parentNode;\n\t\tp.removeChild(tBody);\n\t}\n\n\t// insert in the new order\n\tvar l = a.length;\n\tfor (var i = 0; i < l; i++)\n\t\ttBody.appendChild(a[i].element);\n\n\tif (SortableTable.removeBeforeSort) {\n\t\t// insert into doc\n\t\tp.insertBefore(tBody, nextSibling);\n\t}\n\n\tthis.updateHeaderArrows();\n\n\tthis.destroyCache(a);\n\n\tif (typeof this.onsort == "function")\n\t\tthis.onsort();\n};\n\nSortableTable.prototype.asyncSort = function (nColumn, bDescending, sSortType) {\n\tvar oThis = this;\n\tthis._asyncsort = function () {\n\t\toThis.sort(nColumn, bDescending, sSortType);\n\t};\n\twindow.setTimeout(this._asyncsort, 1);\n};\n\nSortableTable.prototype.getCache = function (sType, nColumn) {\n\tif (!this.tBody) return [];\n\tvar rows = this.tBody.rows;\n\tvar l = rows.length;\n\tvar a = new Array(l);\n\tvar r;\n\tfor (var i = 0; i < l; i++) {\n\t\tr = rows[i];\n\t\ta[i] = {\n\t\t\tvalue:\t\tthis.getRowValue(r, sType, nColumn),\n\t\t\telement:\tr\n\t\t};\n\t};\n\treturn a;\n};\n\nSortableTable.prototype.destroyCache = function (oArray) {\n\tvar l = oArray.length;\n\tfor (var i = 0; i < l; i++) {\n\t\toArray[i].value = null;\n\t\toArray[i].element = null;\n\t\toArray[i] = null;\n\t}\n};\n\nSortableTable.prototype.getRowValue = function (oRow, sType, nColumn) {\n\t// if we have defined a custom getRowValue use that\n\tif (this._sortTypeInfo[sType] && this._sortTypeInfo[sType].getRowValue)\n\t\treturn this._sortTypeInfo[sType].getRowValue(oRow, nColumn);\n\n\tvar s;\n\tvar c = oRow.cells[nColumn];\n\tif (typeof c.innerText != "undefined")\n\t\ts = c.innerText;\n\telse\n\t\ts = SortableTable.getInnerText(c);\n\treturn this.getValueFromString(s, sType);\n};\n\nSortableTable.getInnerText = function (oNode) {\n\tvar s = "";\n\tvar cs = oNode.childNodes;\n\tvar l = cs.length;\n\tfor (var i = 0; i < l; i++) {\n\t\tswitch (cs[i].nodeType) {\n\t\t\tcase 1: //ELEMENT_NODE\n\t\t\t\ts += SortableTable.getInnerText(cs[i]);\n\t\t\t\tbreak;\n\t\t\tcase 3:\t//TEXT_NODE\n\t\t\t\ts += cs[i].nodeValue;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn s;\n};\n\nSortableTable.prototype.getValueFromString = function (sText, sType) {\n\tif (this._sortTypeInfo[sType])\n\t\treturn this._sortTypeInfo[sType].getValueFromString( sText );\n\treturn sText;\n\t/*\n\tswitch (sType) {\n\t\tcase "Number":\n\t\t\treturn Number(sText);\n\t\tcase "CaseInsensitiveString":\n\t\t\treturn sText.toUpperCase();\n\t\tcase "Date":\n\t\t\tvar parts = sText.split("-");\n\t\t\tvar d = new Date(0);\n\t\t\td.setFullYear(parts[0]);\n\t\t\td.setDate(parts[2]);\n\t\t\td.setMonth(parts[1] - 1);\n\t\t\treturn d.valueOf();\n\t}\n\treturn sText;\n\t*/\n\t};\n\nSortableTable.prototype.getSortFunction = function (sType, nColumn) {\n\tif (this._sortTypeInfo[sType])\n\t\treturn this._sortTypeInfo[sType].compare;\n\treturn SortableTable.basicCompare;\n};\n\nSortableTable.prototype.destroy = function () {\n\tthis.uninitHeader();\n\tvar win = this.document.parentWindow;\n\tif (win && typeof win.detachEvent != "undefined") {\t// only IE needs this\n\t\twin.detachEvent("onunload", this._onunload);\n\t}\n\tthis._onunload = null;\n\tthis.element = null;\n\tthis.tHead = null;\n\tthis.tBody = null;\n\tthis.document = null;\n\tthis._headerOnclick = null;\n\tthis.sortTypes = null;\n\tthis._asyncsort = null;\n\tthis.onsort = null;\n};\n\n// Adds a sort type to all instance of SortableTable\n// sType : String - the identifier of the sort type\n// fGetValueFromString : function ( s : string ) : T - A function that takes a\n// string and casts it to a desired format. If left out the string is just\n// returned\n// fCompareFunction : function ( n1 : T, n2 : T ) : Number - A normal JS sort\n// compare function. Takes two values and compares them. If left out less than,\n// <, compare is used\n// fGetRowValue : function( oRow : HTMLTRElement, nColumn : int ) : T - A function\n// that takes the row and the column index and returns the value used to compare.\n// If left out then the innerText is first taken for the cell and then the\n// fGetValueFromString is used to convert that string the desired value and type\n\nSortableTable.prototype.addSortType = function (sType, fGetValueFromString, fCompareFunction, fGetRowValue) {\n\tthis._sortTypeInfo[sType] = {\n\t\ttype:\t\t\t\tsType,\n\t\tgetValueFromString:\tfGetValueFromString || SortableTable.idFunction,\n\t\tcompare:\t\t\tfCompareFunction || SortableTable.basicCompare,\n\t\tgetRowValue:\t\tfGetRowValue\n\t};\n};\n\n// this removes the sort type from all instances of SortableTable\nSortableTable.prototype.removeSortType = function (sType) {\n\tdelete this._sortTypeInfo[sType];\n};\n\nSortableTable.basicCompare = function compare(n1, n2) {\n\tif (n1.value < n2.value)\n\t\treturn -1;\n\tif (n2.value < n1.value)\n\t\treturn 1;\n\treturn 0;\n};\n\nSortableTable.idFunction = function (x) {\n\treturn x;\n};\n\nSortableTable.toUpperCase = function (s) {\n\treturn s.toUpperCase();\n};\n\nSortableTable.toDate = function (s) {\n\tvar parts = s.split("-");\n\tvar d = new Date(0);\n\td.setFullYear(parts[0]);\n\td.setDate(parts[2]);\n\td.setMonth(parts[1] - 1);\n\treturn d.valueOf();\n};\n\n\n// add sort types\nSortableTable.prototype.addSortType("Number", Number);\nSortableTable.prototype.addSortType("CaseInsensitiveString", SortableTable.toUpperCase);\nSortableTable.prototype.addSortType("Date", SortableTable.toDate);\nSortableTable.prototype.addSortType("String");\n// None is a special case\n'}});
\ No newline at end of file
diff --git a/package.json b/package.json
index 730e87f3..31d45e43 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "tablefilter",
- "version": "0.2.67",
+ "version": "0.3.0",
"description": "A Javascript library making HTML tables filterable and a bit more",
"license": "MIT",
"author": {
@@ -28,12 +28,12 @@
"tag": "next"
},
"devDependencies": {
- "babel-core": "^6.14.0",
+ "babel-core": "^6.17.0",
"babel-eslint": "7.0.0",
"babel-loader": "^6.2.5",
- "babel-preset-es2015": "^6.14.0",
"babel-plugin-transform-es2015-classes": "^6.14.0",
- "clean-webpack-plugin": "^0.1.9",
+ "babel-preset-es2015": "^6.16.0",
+ "clean-webpack-plugin": "^0.1.11",
"grunt": "^1.0.1",
"grunt-babel": "^6.0.0",
"grunt-contrib-clean": "^1.0.0",
@@ -45,10 +45,11 @@
"grunt-esdoc": "^0.0.4",
"grunt-eslint": "19.0.0",
"grunt-gh-pages": "^2.0.0",
- "grunt-string-replace": "^1.3.0",
- "grunt-webpack": "^1.0.14",
+ "grunt-string-replace": "^1.3.1",
+ "grunt-webpack": "^1.0.16",
"script-loader": "^0.7.0",
"string-replace-webpack-plugin": "^0.0.3",
+ "sugar-date": "2.0.0",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.16.1"
},
diff --git a/src/const.js b/src/const.js
index eb3e24e7..f2c554a6 100644
--- a/src/const.js
+++ b/src/const.js
@@ -73,6 +73,40 @@ export const HEADER_TAG = 'TH';
*/
export const CELL_TAG = 'TD';
+/**
+ * Data types
+ */
+
+/**
+ * String
+ * @type {String}
+ */
+export const STRING = 'string';
+
+/**
+ * Number
+ * @type {String}
+ */
+export const NUMBER = 'number';
+
+/**
+ * Formatted number
+ * @type {String}
+ */
+export const FORMATTED_NUMBER = 'formatted-number';
+
+/**
+ * Date
+ * @type {String}
+ */
+export const DATE = 'date';
+
+/**
+ * IP address
+ * @type {String}
+ */
+export const IP_ADDRESS = 'ipaddress';
+
/**
* Default values
*/
diff --git a/src/date.js b/src/date.js
deleted file mode 100644
index 72838222..00000000
--- a/src/date.js
+++ /dev/null
@@ -1,183 +0,0 @@
-/**
- * Date utilities
- */
-
-/**
- * Verifies passed formatted date string is valid
- * @param {String} dateStr Formatted date string
- * @param {String} format accepted formats: 'DMY', 'MDY', 'YMD', 'DDMMMYYYY'
- * @return {Boolean}
- */
-export const isValidDate = (dateStr, format) => {
- if (!format) {
- format = 'DMY';
- }
- format = format.toUpperCase();
- if (format.length !== 3) {
- if (format === 'DDMMMYYYY') {
- let d = formatDate(dateStr, format);
- dateStr = d.getDate() + '/' + (d.getMonth() + 1) + '/' +
- d.getFullYear();
- format = 'DMY';
- }
- }
- if ((format.indexOf('M') === -1) || (format.indexOf('D') === -1) ||
- (format.indexOf('Y') === -1)) {
- format = 'DMY';
- }
- let reg1, reg2;
- // If the year is first
- if (format.substring(0, 1) === 'Y') {
- reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
- reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/;
- } else if (format.substring(1, 2) === 'Y') { // If the year is second
- reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/;
- reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/;
- } else { // The year must be third
- reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/;
- reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
- }
- // If it doesn't conform to the right format (with either a 2 digit year
- // or 4 digit year), fail
- if (reg1.test(dateStr) === false && reg2.test(dateStr) === false) {
- return false;
- }
- // Split into 3 parts based on what the divider was
- let parts = dateStr.split(RegExp.$1);
- let mm, dd, yy;
- // Check to see if the 3 parts end up making a valid date
- if (format.substring(0, 1) === 'M') {
- mm = parts[0];
- } else if (format.substring(1, 2) === 'M') {
- mm = parts[1];
- } else {
- mm = parts[2];
- }
- if (format.substring(0, 1) === 'D') {
- dd = parts[0];
- } else if (format.substring(1, 2) === 'D') {
- dd = parts[1];
- } else {
- dd = parts[2];
- }
- if (format.substring(0, 1) === 'Y') {
- yy = parts[0];
- } else if (format.substring(1, 2) === 'Y') {
- yy = parts[1];
- } else {
- yy = parts[2];
- }
- if (parseInt(yy, 10) <= 50) {
- yy = (parseInt(yy, 10) + 2000).toString();
- }
- if (parseInt(yy, 10) <= 99) {
- yy = (parseInt(yy, 10) + 1900).toString();
- }
- let dt = new Date(
- parseInt(yy, 10), parseInt(mm, 10) - 1, parseInt(dd, 10),
- 0, 0, 0, 0);
- if (parseInt(dd, 10) !== dt.getDate()) {
- return false;
- }
- if (parseInt(mm, 10) - 1 !== dt.getMonth()) {
- return false;
- }
- return true;
-}
-
-/**
- * Converts formatted date into a Date object
- * @param {String} dateStr Formatted date string
- * @param {String} format accepted formats: 'DMY', 'MDY', 'YMD', 'DDMMMYYYY'
- * @return {Object} date object
- */
-export const formatDate = (dateStr, formatStr) => {
- if (!formatStr) {
- formatStr = 'DMY';
- }
- if (!dateStr || dateStr === '') {
- return new Date(1001, 0, 1);
- }
- let oDate;
- let parts;
-
- switch (formatStr.toUpperCase()) {
- case 'DDMMMYYYY':
- parts = dateStr.replace(/[- \/.]/g, ' ').split(' ');
- oDate = new Date(y2kDate(parts[2]), mmm2mm(parts[1]) - 1, parts[0]);
- break;
- case 'DMY':
- /* eslint-disable */
- parts = dateStr.replace(
- /^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, '$1 $3 $5').split(' ');
- oDate = new Date(y2kDate(parts[2]), parts[1] - 1, parts[0]);
- /* eslint-enable */
- break;
- case 'MDY':
- /* eslint-disable */
- parts = dateStr.replace(
- /^(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])([- \/.])((\d\d)?\d\d)$/, '$1 $3 $5').split(' ');
- oDate = new Date(y2kDate(parts[2]), parts[0] - 1, parts[1]);
- /* eslint-enable */
- break;
- case 'YMD':
- /* eslint-disable */
- parts = dateStr.replace(/^((\d\d)?\d\d)([- \/.])(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])$/, '$1 $4 $6').split(' ');
- oDate = new Date(y2kDate(parts[0]), parts[1] - 1, parts[2]);
- /* eslint-enable */
- break;
- default: //in case format is not correct
- /* eslint-disable */
- parts = dateStr.replace(/^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, '$1 $3 $5').split(' ');
- oDate = new Date(y2kDate(parts[2]), parts[1] - 1, parts[0]);
- /* eslint-enable */
- break;
- }
- return oDate;
-}
-
-function y2kDate(yr) {
- if (yr === undefined) {
- return 0;
- }
- if (yr.length > 2) {
- return yr;
- }
- let y;
- //>50 belong to 1900
- if (yr <= 99 && yr > 50) {
- y = '19' + yr;
- }
- //<50 belong to 2000
- if (yr < 50 || yr === '00') {
- y = '20' + yr;
- }
- return y;
-}
-
-function mmm2mm(mmm) {
- if (mmm === undefined) {
- return 0;
- }
- let mondigit;
- let MONTH_NAMES = [
- 'january', 'february', 'march', 'april', 'may', 'june', 'july',
- 'august', 'september', 'october', 'november', 'december',
- 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct',
- 'nov', 'dec'
- ];
- for (let m_i = 0; m_i < MONTH_NAMES.length; m_i++) {
- let month_name = MONTH_NAMES[m_i];
- if (mmm.toLowerCase() === month_name) {
- mondigit = m_i + 1;
- break;
- }
- }
- if (mondigit > 11 || mondigit < 23) {
- mondigit = mondigit - 12;
- }
- if (mondigit < 1 || mondigit > 12) {
- return 0;
- }
- return mondigit;
-}
diff --git a/src/extensions/sort/adapterSortabletable.js b/src/extensions/sort/adapterSortabletable.js
index c46b37cb..9e72dca3 100644
--- a/src/extensions/sort/adapterSortabletable.js
+++ b/src/extensions/sort/adapterSortabletable.js
@@ -1,10 +1,12 @@
import {Feature} from '../../feature';
-import {isArray, isFn, isUndef} from '../../types';
+import {isArray, isFn, isUndef, isObj} from '../../types';
import {createElm, elm, getText, tag} from '../../dom';
import {addEvt} from '../../event';
-import {formatDate} from '../../date';
-import {removeNbFormat} from '../../helpers';
-import {NONE, CELL_TAG, HEADER_TAG} from '../../const';
+import {parse as parseNb} from '../../number';
+import {
+ NONE, CELL_TAG, HEADER_TAG, STRING, NUMBER, DATE, FORMATTED_NUMBER,
+ IP_ADDRESS
+} from '../../const';
/**
* SortableTable Adapter module
@@ -42,7 +44,7 @@ export default class AdapterSortableTable extends Feature {
* List of sort type per column basis
* @type {Array}
*/
- this.sortTypes = isArray(opts.types) ? opts.types : [];
+ this.sortTypes = isArray(opts.types) ? opts.types : tf.colTypes;
/**
* Column to be sorted at initialization, ie:
@@ -146,10 +148,14 @@ export default class AdapterSortableTable extends Feature {
throw new Error('SortableTable class not found.');
}
+ // Add any date format if needed
+ let dateType = tf.feature('dateType');
+ dateType.addConfigFormats(this.sortTypes);
+
this.overrideSortableTable();
this.setSortTypes();
- //Column sort at start
+ // Column sort at start
let sortColAtStart = adpt.sortColAtStart;
if (sortColAtStart) {
this.stt.sort(sortColAtStart[0], sortColAtStart[1]);
@@ -378,9 +384,10 @@ export default class AdapterSortableTable extends Feature {
/**
* Adds a sort type
*/
- addSortType() {
- var args = arguments;
- SortableTable.prototype.addSortType(args[0], args[1], args[2], args[3]);
+ addSortType(...args) {
+ // Extract the arguments
+ let [id, caster, sorter] = args;
+ SortableTable.prototype.addSortType(id, caster, sorter);
}
/**
@@ -394,20 +401,32 @@ export default class AdapterSortableTable extends Feature {
for (let i = 0; i < tf.nbCells; i++) {
let colType;
-
if (sortTypes[i]) {
- colType = sortTypes[i].toLowerCase();
- if (colType === NONE) {
- colType = 'None';
- }
- } else { // resolve column types
- if (tf.hasColNbFormat && tf.colNbFormat[i] !== null) {
- colType = tf.colNbFormat[i].toLowerCase();
- } else if (tf.hasColDateType && tf.colDateType[i] !== null) {
- colType = tf.colDateType[i].toLowerCase() + 'date';
+ colType = sortTypes[i];
+ if (isObj(colType)) {
+ if (colType.type === DATE) {
+ colType = this._addDateType(i, sortTypes);
+ }
+ else if (colType.type === FORMATTED_NUMBER) {
+ let decimal = colType.decimal || tf.decimalSeparator;
+ colType = this._addNumberType(i, decimal);
+ }
} else {
- colType = 'String';
+ colType = colType.toLowerCase();
+ if (colType === DATE) {
+ colType = this._addDateType(i, sortTypes);
+ }
+ else if (colType === FORMATTED_NUMBER ||
+ colType === NUMBER) {
+ colType = this._addNumberType(i, tf.decimalSeparator);
+ }
+ else if (colType === NONE) {
+ // TODO: normalise 'none' vs 'None'
+ colType = 'None';
+ }
}
+ } else {
+ colType = STRING;
}
_sortTypes.push(colType);
}
@@ -415,17 +434,9 @@ export default class AdapterSortableTable extends Feature {
//Public TF method to add sort type
//Custom sort types
- this.addSortType('number', Number);
this.addSortType('caseinsensitivestring', SortableTable.toUpperCase);
- this.addSortType('date', SortableTable.toDate);
- this.addSortType('string');
- this.addSortType('us', usNumberConverter);
- this.addSortType('eu', euNumberConverter);
- this.addSortType('dmydate', dmyDateConverter);
- this.addSortType('ymddate', ymdDateConverter);
- this.addSortType('mdydate', mdyDateConverter);
- this.addSortType('ddmmmyyyydate', ddmmmyyyyDateConverter);
- this.addSortType('ipaddress', ipAddress, sortIP);
+ this.addSortType(STRING);
+ this.addSortType(IP_ADDRESS, ipAddress, sortIP);
this.stt = new SortableTable(tf.tbl, _sortTypes);
@@ -453,6 +464,27 @@ export default class AdapterSortableTable extends Feature {
}
}
+ _addDateType(colIndex, types) {
+ let tf = this.tf;
+ let dateType = tf.feature('dateType');
+ let locale = dateType.getOptions(colIndex, types).locale || tf.locale;
+ let colType = `${DATE}-${locale}`;
+
+ this.addSortType(colType, (value) => {
+ return dateType.parse(value, locale);
+ });
+ return colType;
+ }
+
+ _addNumberType(colIndex, decimal) {
+ let colType = `${FORMATTED_NUMBER}${decimal === '.' ? '' : '-custom'}`;
+
+ this.addSortType(colType, (value) => {
+ return parseNb(value, decimal);
+ });
+ return colType;
+ }
+
/**
* Remove extension
*/
@@ -464,7 +496,6 @@ export default class AdapterSortableTable extends Feature {
this.emitter.off(['sort'],
(tf, colIdx, desc) => this.sortByColumnIndex(colIdx, desc));
this.sorted = false;
- this.initialized = false;
this.stt.destroy();
let ids = tf.getFiltersId();
@@ -482,28 +513,6 @@ export default class AdapterSortableTable extends Feature {
}
//Converters
-function usNumberConverter(s) {
- return removeNbFormat(s, 'us');
-}
-function euNumberConverter(s) {
- return removeNbFormat(s, 'eu');
-}
-function dateConverter(s, format) {
- return formatDate(s, format);
-}
-function dmyDateConverter(s) {
- return dateConverter(s, 'DMY');
-}
-function mdyDateConverter(s) {
- return dateConverter(s, 'MDY');
-}
-function ymdDateConverter(s) {
- return dateConverter(s, 'YMD');
-}
-function ddmmmyyyyDateConverter(s) {
- return dateConverter(s, 'DDMMMYYYY');
-}
-
function ipAddress(value) {
let vals = value.split('.');
for (let x in vals) {
diff --git a/src/helpers.js b/src/helpers.js
deleted file mode 100644
index f859bc3b..00000000
--- a/src/helpers.js
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * Misc helpers
- */
-
-/**
- * Returns a unformatted number
- * @param {String} Formatted number
- * @param {String} Format type, currently 'us' or 'eu'
- * @return {String} Unformatted number
- */
-export const removeNbFormat = (data, format = 'us') => {
- let n = data;
- if (format.toLowerCase() === 'us') {
- n = + n.replace(/[^\d\.-]/g, '');
- } else {
- n = + n.replace(/[^\d\,-]/g, '').replace(',', '.');
- }
- return n;
-}
diff --git a/src/modules/dateType.js b/src/modules/dateType.js
new file mode 100644
index 00000000..3e62b178
--- /dev/null
+++ b/src/modules/dateType.js
@@ -0,0 +1,132 @@
+import {Date as SugarDate} from 'sugar-date';
+import 'sugar-date/locales';
+import {Feature} from '../feature';
+import {isObj, isArray} from '../types';
+import {DATE} from '../const';
+
+/**
+ * Wrapper for Sugar Date module providing datetime helpers and locales
+ * @export
+ * @class DateType
+ */
+export class DateType extends Feature {
+
+ /**
+ * Creates an instance of DateType
+ * @param {TableFilter} tf TableFilter instance
+ */
+ constructor(tf) {
+ super(tf, 'dateType');
+
+ /**
+ * Global locale
+ * @type {String}
+ */
+ this.locale = tf.locale;
+
+ /**
+ * Sugar Date instance
+ * @type {Object}
+ */
+ this.datetime = SugarDate;
+
+ this.enable();
+ }
+
+ /**
+ * Initialize DateType instance
+ */
+ init() {
+ if (this.initialized) {
+ return;
+ }
+
+ // Set global locale
+ this.datetime.setLocale(this.locale);
+
+ // Add formats from column types configuration if any
+ this.addConfigFormats(this.tf.colTypes);
+
+ // Broadcast date-type initialization
+ this.emitter.emit('date-type-initialized', this.tf, this);
+
+ /** @inherited */
+ this.initialized = true;
+ }
+
+ /**
+ * Parse a string representation of a date for a specified locale and return
+ * a date object
+ * @param {String} dateStr String representation of a date
+ * @param {String} localeCode Locale code (ie 'en-us')
+ * @returns {Date}
+ */
+ parse(dateStr, localeCode) {
+ return this.datetime.create(dateStr, localeCode);
+ }
+
+ /**
+ * Check string representation of a date for a specified locale is valid
+ * @param {any} dateStr String representation of a date
+ * @param {any} localeCode Locale code (ie 'en-us')
+ * @returns {Boolean}
+ */
+ isValid(dateStr, localeCode) {
+ return this.datetime.isValid(this.parse(dateStr, localeCode));
+ }
+
+ /**
+ * Return the type object of a specified column as per configuration or
+ * passed collection
+ * @param {Number} colIndex Column index
+ * @param {Array} types Collection of column types, optional
+ * @returns {Object}
+ */
+ getOptions(colIndex, types) {
+ types = types || this.tf.colTypes;
+ let colType = types[colIndex];
+ return isObj(colType) ? colType : {};
+ }
+
+ /**
+ * Add date time format(s) to a locale as specified by the passed
+ * collection of column types, ie:
+ * [
+ * 'string',
+ * 'number',
+ * { type: 'date', locale: 'en', format: ['{dd}/{MM}/{yyyy}']}
+ * ]
+ *
+ * @param {Array} [types=[]] Collection of column types
+ */
+ addConfigFormats(types=[]) {
+ types.forEach((type, idx) => {
+ let options = this.getOptions(idx, types);
+ if (options.type === DATE && options.hasOwnProperty('format')) {
+ let locale = this.datetime.getLocale(
+ options.locale || this.locale
+ );
+ if (isArray(options.format)) {
+ options.format.forEach((format) => {
+ locale.addFormat(format);
+ });
+ } else {
+ locale.addFormat(options.format);
+ }
+ }
+ });
+ }
+
+ /**
+ * Remove DateType instance
+ */
+ destroy() {
+ if (!this.initialized) {
+ return;
+ }
+
+ // TODO: remove added formats
+
+ this.initialized = false;
+ }
+}
diff --git a/src/modules/popupFilter.js b/src/modules/popupFilter.js
index 7fc5306b..ea2b433e 100644
--- a/src/modules/popupFilter.js
+++ b/src/modules/popupFilter.js
@@ -162,13 +162,15 @@ export class PopupFilter extends Feature {
let tf = this.tf;
// Override headers row index if no grouped headers
- // TODO: Prevent the filters row to simplify headers row index adjusting
+ // TODO: Because of the filters row generation, headers row index needs
+ // adjusting: prevent useless row generation
if (tf.headersRow <= 1 && isNaN(tf.config().headers_row_index)) {
tf.headersRow = 0;
}
// Adjust headers row index for grid-layout mode
- // TODO: Prevent the filters row to simplify headers row index adjusting
+ // TODO: Because of the filters row generation, headers row index needs
+ // adjusting: prevent useless row generation
if (tf.gridLayout) {
tf.headersRow--;
this.buildIcons();
@@ -204,8 +206,8 @@ export class PopupFilter extends Feature {
buildIcons() {
let tf = this.tf;
- // Filters row is added to the DOM, adjust headers row index
- // TODO: Prevent the filters row to simplify headers row index adjusting
+ // TODO: Because of the filters row generation, headers row index needs
+ // adjusting: prevent useless row generation
tf.headersRow++;
for (let i = 0; i < tf.nbCells; i++) {
diff --git a/src/number.js b/src/number.js
new file mode 100644
index 00000000..e076b85c
--- /dev/null
+++ b/src/number.js
@@ -0,0 +1,29 @@
+import {isNumber} from './types';
+
+/**
+ * Takes a string, removes all formatting/cruft and returns the raw float value
+ * @param {String} Formatted number
+ * @param {String} Decimal type '.' or ','
+ * @return {Number} Unformatted number
+ *
+ * https://github.com/openexchangerates/accounting.js/blob/master/accounting.js
+ */
+export const parse = (value, decimal = '.') => {
+ // Return the value as-is if it's already a number
+ if (isNumber(value)) {
+ return value;
+ }
+
+ // Build regex to strip out everything except digits, decimal point and
+ // minus sign
+ let regex = new RegExp('[^0-9-' + decimal + ']', ['g']);
+ let unformatted = parseFloat(
+ ('' + value)
+ .replace(/\((.*)\)/, '-$1') // replace bracketed values with negatives
+ .replace(regex, '') // strip out any cruft
+ .replace(decimal, '.') // make sure decimal point is standard
+ );
+
+ // This will fail silently
+ return !isNaN(unformatted) ? unformatted : 0;
+}
diff --git a/src/tablefilter.js b/src/tablefilter.js
index dad3fb3e..605bd3b5 100644
--- a/src/tablefilter.js
+++ b/src/tablefilter.js
@@ -5,10 +5,10 @@ import {
} from './dom';
import {contains, matchCase, rgxEsc, trim} from './string';
import {isEmpty as isEmptyString} from './string';
-import {isArray, isEmpty, isFn, isNumber, isObj, isString, isUndef}
-from './types';
-import {formatDate, isValidDate} from './date';
-import {removeNbFormat} from './helpers';
+import {
+ isArray, isEmpty, isFn, isNumber, isObj, isString, isUndef
+} from './types';
+import {parse as parseNb} from './number'
import {root} from './root';
import {Emitter} from './emitter';
@@ -26,11 +26,12 @@ import {Help} from './modules/help';
import {AlternateRows} from './modules/alternateRows';
import {NoResults} from './modules/noResults';
import {State} from './modules/state';
+import {DateType} from './modules/dateType';
import {
INPUT, SELECT, MULTIPLE, CHECKLIST, NONE,
ENTER_KEY, TAB_KEY, ESC_KEY, UP_ARROW_KEY, DOWN_ARROW_KEY,
- CELL_TAG, AUTO_FILTER_DELAY
+ CELL_TAG, AUTO_FILTER_DELAY, NUMBER, DATE, FORMATTED_NUMBER
} from './const';
let doc = root.document;
@@ -838,11 +839,13 @@ export class TableFilter {
this.state = isObj(f.state) || Boolean(f.state);
/*** data types ***/
+
/**
- * Define default date type (DMY)
+ * Define default locale, default to 'en' as per Sugar Date module:
+ * https://sugarjs.com/docs/#/DateLocales
* @type {String}
*/
- this.defaultDateType = f.default_date_type || 'DMY';
+ this.locale = f.locale || 'en';
/**
* Define thousands separator ',' or '.', defaults to ','
@@ -857,34 +860,27 @@ export class TableFilter {
this.decimalSeparator = f.decimal_separator || '.';
/**
- * Determine whether table has columns with numeric formats
+ * Determine whether table has columns data types
* @type {Boolean}
* @private
*/
- this.hasColNbFormat = isArray(f.col_number_format);
+ this.hasColTypes = isArray(f.col_types);
/**
- * Define numeric format on a column basis, two possible values 'EU' and
- * 'US', ie:
- * col_number_format : [null, 'US', 'EU', null]
+ * Define data types on a column basis, possible values 'string',
+ * 'number', 'formatted-number', 'date', 'ipaddress' ie:
+ * col_types : [
+ * 'string', 'date', 'number',
+ * { type: 'formatted-number', decimal: ',', thousands: '.' },
+ * { type: 'date', locale: 'en-gb' },
+ * { type: 'date', format: ['{dd}-{months}-{yyyy|yy}'] }
+ * ]
+ *
+ * Refer to https://sugarjs.com/docs/#/DateParsing for exhaustive
+ * information on date parsing formats supported by Sugar Date
* @type {Array}
*/
- this.colNbFormat = this.hasColNbFormat ? f.col_number_format : null;
-
- /**
- * Determine whether table has columns with date types
- * @type {Boolean}
- * @private
- */
- this.hasColDateType = isArray(f.col_date_type);
-
- /**
- * Define date format on a column basis, possible values 'DMY', 'MDY',
- * 'YMD', 'DDMMMYYYY', ie:
- * col_date_type : [null, 'DMY', 'MDY', 'YMD', null, 'DDMMMYYYY']
- * @type {Array}
- */
- this.colDateType = this.hasColDateType ? f.col_date_type : null;
+ this.colTypes = this.hasColTypes ? f.col_types : [];
/*** ids prefixes ***/
/**
@@ -1018,6 +1014,12 @@ export class TableFilter {
this.loadThemes();
}
+ // Instanciate sugar date wrapper
+ if (!Mod.dateType) {
+ Mod.dateType = new DateType(this);
+ Mod.dateType.init();
+ }
+
// Instantiate help feature and initialise only if set true
if (!Mod.help) {
Mod.help = new Help(this);
@@ -1283,6 +1285,9 @@ export class TableFilter {
* Insert filters row at initialization
*/
_insertFiltersRow() {
+ // TODO: prevent filters row generation for popup filters too,
+ // to reduce and simplify headers row index adjusting across lib modules
+ // (GridLayout, PopupFilter etc)
if (this.gridLayout) {
return;
}
@@ -1738,8 +1743,8 @@ export class TableFilter {
// search args re-init
let searchArgs = this.getFiltersValue();
- let numCellData;
- let nbFormat;
+ let numData;
+ let decimal = this.decimalSeparator;
let re_le = new RegExp(this.leOperator),
re_ge = new RegExp(this.geOperator),
re_l = new RegExp(this.lwOperator),
@@ -1775,12 +1780,10 @@ export class TableFilter {
}
//looks for search argument in current row
- function hasArg(sA, cellData, j) {
+ function hasArg(sA, cellData, colIdx) {
sA = matchCase(sA, this.caseSensitive);
- let occurence;
- let dtType = this.hasColDateType ?
- this.colDateType[j] : this.defaultDateType;
+ let occurence = false;
//Search arg operator tests
let hasLO = re_l.test(sA),
@@ -1797,46 +1800,59 @@ export class TableFilter {
hasNM = (re_nm === sA),
hasRE = re_re.test(sA);
- //Search arg dates tests
- let isLDate = hasLO && isValidDate(sA.replace(re_l, ''), dtType);
- let isLEDate = hasLE && isValidDate(sA.replace(re_le, ''), dtType);
- let isGDate = hasGR && isValidDate(sA.replace(re_g, ''), dtType);
- let isGEDate = hasGE && isValidDate(sA.replace(re_ge, ''), dtType);
- let isDFDate = hasDF && isValidDate(sA.replace(re_d, ''), dtType);
- let isEQDate = hasEQ && isValidDate(sA.replace(re_eq, ''), dtType);
+ // Check for dates or resolve date type
+ if (this.hasType(colIdx, [DATE])) {
+ let dte1, dte2;
+
+ let dateType = this.Mod.dateType;
+ let isValidDate = dateType.isValid.bind(dateType);
+ let parseDate = dateType.parse.bind(dateType);
+ let locale = dateType.getOptions(colIdx).locale || this.locale;
+
+ // Search arg dates tests
+ let isLDate = hasLO &&
+ isValidDate(sA.replace(re_l, ''), locale);
+ let isLEDate = hasLE &&
+ isValidDate(sA.replace(re_le, ''), locale);
+ let isGDate = hasGR &&
+ isValidDate(sA.replace(re_g, ''), locale);
+ let isGEDate = hasGE &&
+ isValidDate(sA.replace(re_ge, ''), locale);
+ let isDFDate = hasDF &&
+ isValidDate(sA.replace(re_d, ''), locale);
+ let isEQDate = hasEQ &&
+ isValidDate(sA.replace(re_eq, ''), locale);
+
+ dte1 = parseDate(cellData, locale);
- let dte1, dte2;
- //dates
- if (isValidDate(cellData, dtType)) {
- dte1 = formatDate(cellData, dtType);
// lower date
if (isLDate) {
- dte2 = formatDate(sA.replace(re_l, ''), dtType);
+ dte2 = parseDate(sA.replace(re_l, ''), locale);
occurence = dte1 < dte2;
}
// lower equal date
else if (isLEDate) {
- dte2 = formatDate(sA.replace(re_le, ''), dtType);
+ dte2 = parseDate(sA.replace(re_le, ''), locale);
occurence = dte1 <= dte2;
}
// greater equal date
else if (isGEDate) {
- dte2 = formatDate(sA.replace(re_ge, ''), dtType);
+ dte2 = parseDate(sA.replace(re_ge, ''), locale);
occurence = dte1 >= dte2;
}
// greater date
else if (isGDate) {
- dte2 = formatDate(sA.replace(re_g, ''), dtType);
+ dte2 = parseDate(sA.replace(re_g, ''), locale);
occurence = dte1 > dte2;
}
// different date
else if (isDFDate) {
- dte2 = formatDate(sA.replace(re_d, ''), dtType);
+ dte2 = parseDate(sA.replace(re_d, ''), locale);
occurence = dte1.toString() !== dte2.toString();
}
// equal date
else if (isEQDate) {
- dte2 = formatDate(sA.replace(re_eq, ''), dtType);
+ dte2 = parseDate(sA.replace(re_eq, ''), locale);
occurence = dte1.toString() === dte2.toString();
}
// searched keyword with * operator doesn't have to be a date
@@ -1844,8 +1860,8 @@ export class TableFilter {
occurence = contains(sA.replace(re_lk, ''), cellData,
false, this.caseSensitive);
}
- else if (isValidDate(sA, dtType)) {
- dte2 = formatDate(sA, dtType);
+ else if (isValidDate(sA)) {
+ dte2 = parseDate(sA, locale);
occurence = dte1.toString() === dte2.toString();
}
//empty
@@ -1856,48 +1872,51 @@ export class TableFilter {
else if (hasNM) {
occurence = !isEmptyString(cellData);
} else {
- occurence = contains(sA, cellData, this.isExactMatch(j),
- this.caseSensitive);
+ occurence = contains(sA, cellData,
+ this.isExactMatch(colIdx), this.caseSensitive);
}
}
else {
- //first numbers need to be formated
- if (this.hasColNbFormat && this.colNbFormat[j]) {
- numCellData = removeNbFormat(cellData, this.colNbFormat[j]);
- nbFormat = this.colNbFormat[j];
- } else {
- if (this.thousandsSeparator === ',' &&
- this.decimalSeparator === '.') {
- numCellData = removeNbFormat(cellData, 'us');
- nbFormat = 'us';
- } else {
- numCellData = removeNbFormat(cellData, 'eu');
- nbFormat = 'eu';
+ if (this.hasType(colIdx, [FORMATTED_NUMBER])) {
+ let colType = this.colTypes[colIdx];
+ if (colType.hasOwnProperty('decimal')) {
+ decimal = colType.decimal;
}
}
+ // Convert to number anyways to auto-resolve type in case not
+ // defined by configuration
+ numData = Number(cellData) || parseNb(cellData, decimal);
// first checks if there is any operator (<,>,<=,>=,!,*,=,{,},
// rgx:)
// lower equal
if (hasLE) {
- occurence = numCellData <= removeNbFormat(
- sA.replace(re_le, ''), nbFormat);
+ occurence = numData <= parseNb(
+ sA.replace(re_le, ''),
+ decimal
+ );
}
//greater equal
else if (hasGE) {
- occurence = numCellData >= removeNbFormat(
- sA.replace(re_ge, ''), nbFormat);
+ occurence = numData >= parseNb(
+ sA.replace(re_ge, ''),
+ decimal
+ );
}
//lower
else if (hasLO) {
- occurence = numCellData < removeNbFormat(
- sA.replace(re_l, ''), nbFormat);
+ occurence = numData < parseNb(
+ sA.replace(re_l, ''),
+ decimal
+ );
}
//greater
else if (hasGR) {
- occurence = numCellData > removeNbFormat(
- sA.replace(re_g, ''), nbFormat);
+ occurence = numData > parseNb(
+ sA.replace(re_g, ''),
+ decimal
+ );
}
//different
else if (hasDF) {
@@ -1950,19 +1969,20 @@ export class TableFilter {
} else {
// If numeric type data, perform a strict equality test and
// fallback to unformatted number string comparison
- if (numCellData && this.hasColNbFormat &&
- this.colNbFormat[j] && !this.singleSearchFlt) {
- // removeNbFormat can return 0 for strings which are not
+ if (numData &&
+ this.hasType(colIdx, [NUMBER, FORMATTED_NUMBER]) &&
+ !this.singleSearchFlt) {
+ // parseNb can return 0 for strings which are not
// formatted numbers, in that case return the original
- // string. TODO: handle this in removeNbFormat
- sA = removeNbFormat(sA, nbFormat) || sA;
- occurence = numCellData === sA ||
- contains(sA.toString(), numCellData.toString(),
- this.isExactMatch(j), this.caseSensitive);
+ // string. TODO: handle this in parseNb
+ sA = parseNb(sA, decimal) || sA;
+ occurence = numData === sA ||
+ contains(sA.toString(), numData.toString(),
+ this.isExactMatch(colIdx), this.caseSensitive);
} else {
// Finally test search term is contained in cell data
- occurence = contains(sA, cellData, this.isExactMatch(j),
- this.caseSensitive);
+ occurence = contains(sA, cellData,
+ this.isExactMatch(colIdx), this.caseSensitive);
}
}
@@ -2111,11 +2131,17 @@ export class TableFilter {
if (j !== colIndex || row[i].style.display !== '') {
continue;
}
- let cellData = this.getCellData(cell[j]),
- nbFormat = this.colNbFormat ?
- this.colNbFormat[colIndex] : undefined,
- data = num ? removeNbFormat(cellData, nbFormat) :
- cellData;
+ let cellData = this.getCellData(cell[j]);
+ let decimal = this.decimalSeparator;
+ if (this.hasType(colIndex, [FORMATTED_NUMBER])) {
+ let colType = this.colTypes[colIndex];
+ if (colType.hasOwnProperty('decimal')) {
+ decimal = colType.decimal;
+ }
+ }
+ let data = num ?
+ Number(cellData) || parseNb(cellData, decimal) :
+ cellData;
colValues.push(data);
}
}
@@ -2823,6 +2849,23 @@ export class TableFilter {
return (nbRows - 1);
}
+ /**
+ * Determine whether the specified column has one of the passed types
+ * @param {Number} colIndex Column index
+ * @param {Array} [types=[]] List of column types
+ * @returns {Boolean}
+ */
+ hasType(colIndex, types = []) {
+ if (!this.hasColTypes) {
+ return false;
+ }
+ let colType = this.colTypes[colIndex];
+ if (isObj(colType)) {
+ colType = colType.type;
+ }
+ return types.indexOf(colType) !== -1;
+ }
+
/**
* Get the header DOM element for a given column index
* @param {Number} colIndex Column index
diff --git a/static/templates/columns-visibility.html b/static/templates/columns-visibility.html
index 8e73a7f5..b2f9c145 100644
--- a/static/templates/columns-visibility.html
+++ b/static/templates/columns-visibility.html
@@ -27,6 +27,10 @@
-Below an example of ISO date support (YMD). Use default_date_type
- to set a date type for a whole table ('DMY','MDY','YMD').
+
+ Below an example of ISO date support ({yyyy|yy}/{MM}/{dd}).
+ Use locale
to set a locale globally
+ (defaults to 'en').
+
diff --git a/static/templates/demo.html b/static/templates/demo.html
index 8684e947..d9981c1b 100644
--- a/static/templates/demo.html
+++ b/static/templates/demo.html
@@ -26,10 +26,10 @@
mark_active_columns: true,
no_results_message: true,
responsive: true,
- col_number_format: [
- null, null, 'US',
- 'US', 'US', 'US',
- 'US', 'US', 'US'
+ col_types: [
+ 'string', 'string', 'number',
+ 'number', 'number', 'number',
+ 'number', 'number', 'number'
],
custom_options: {
cols:[3],
diff --git a/static/templates/external-filters.html b/static/templates/external-filters.html
index 6ce01896..36c77f00 100644
--- a/static/templates/external-filters.html
+++ b/static/templates/external-filters.html
@@ -88,10 +88,10 @@ var tfConfig = {
status: true,
status_bar: true,
status_bar_target_id: 'statusDiv',
- col_number_format: [
- null, null, 'US',
- 'US', 'US', 'US',
- 'US', 'US', 'US'
+ col_types: [
+ 'string', 'string', 'number',
+ 'number', 'number', 'number',
+ 'number', 'number', 'number'
],
display_all_text: " [ Show all ] ",
col_0: "multiple",
diff --git a/static/templates/filter-images.html b/static/templates/filter-images.html
index c27d494f..3caa09ca 100644
--- a/static/templates/filter-images.html
+++ b/static/templates/filter-images.html
@@ -22,13 +22,9 @@ var tfConfig = {
base_path: '../dist/tablefilter/',
filters_row_index: 2,
headers_row_index: 1,
- col_number_format: [
- null, null, null,
- 'US', null, null, null
- ],
- col_date_type: [
- null, null, null,
- null, null, null, 'mdy'
+ col_types: [
+ 'string', 'string', 'string',
+ 'number', 'string', 'string', 'date'
],
rows_counter: true,
rows_counter_text: 'Books: ',
diff --git a/static/templates/grid-layout.html b/static/templates/grid-layout.html
index e5e44545..5c0fa5ed 100644
--- a/static/templates/grid-layout.html
+++ b/static/templates/grid-layout.html
@@ -29,13 +29,13 @@
'120px', '120px', '100px',
'100px', '100px', '100px'
],
+ col_types: [
+ 'string', 'string', 'number',
+ 'number', 'number', 'number',
+ 'number', 'number', 'number'
+ ],
extensions:[{
- name: 'sort',
- types: [
- 'string', 'string', 'number',
- 'number', 'number', 'number',
- 'number', 'number', 'number'
- ]
+ name: 'sort'
}]
};
diff --git a/static/templates/grouped-headers.html b/static/templates/grouped-headers.html
index 0a50dba1..7da57921 100644
--- a/static/templates/grouped-headers.html
+++ b/static/templates/grouped-headers.html
@@ -40,10 +40,10 @@ var tfConfig = {
col_0: 'multiple',
col_1: 'select',
col_2: 'checklist',
- col_number_format: [
- null, null, 'US',
- 'US', 'US', 'US',
- 'US', 'US', 'US'
+ col_types: [
+ 'string', 'string', 'number',
+ 'number', 'number', 'number',
+ 'number', 'number', 'number'
],
filters_row_index: 3,
headers_row_index: 2,
diff --git a/static/templates/starter.html b/static/templates/starter.html
index 3dde11fa..ae837e5d 100644
--- a/static/templates/starter.html
+++ b/static/templates/starter.html
@@ -24,10 +24,10 @@
status_bar: true,
mark_active_columns: true,
highlight_keywords: true,
- col_number_format: [
- null, null, 'US',
- 'US', 'US', 'US',
- 'US', 'US', 'US'
+ col_types: [
+ 'string', 'string', 'number',
+ 'number', 'number', 'number',
+ 'number', 'number', 'number'
],
custom_options: {
cols:[3],
diff --git a/static/templates/theme-roller.html b/static/templates/theme-roller.html
index dbdef3cc..5defe171 100644
--- a/static/templates/theme-roller.html
+++ b/static/templates/theme-roller.html
@@ -30,13 +30,9 @@ var tfConfig = {
filters_row_index: 2,
headers_row_index: 1,
sort: true,
- col_number_format: [
- null, null, 'US',
- null, null, null
- ],
- col_date_type: [
- null, null, null,
- null, null, 'mdy'
+ col_types: [
+ 'string', 'string', 'number',
+ 'string', 'string', 'date'
],
rows_counter: true,
rows_counter_text: 'Books: ',
diff --git a/test/test-data-types.js b/test/test-data-types.js
index 882be7fb..755ff4b3 100644
--- a/test/test-data-types.js
+++ b/test/test-data-types.js
@@ -2,17 +2,14 @@
// TODO: add sort to test it with different column types
var tf = new TableFilter('demo', {
base_path: '../dist/tablefilter/',
- col_number_format: [
- null, null, null,
- 'EU', 'US', null,
+ col_types: [
null, null, null,
+ { type: 'formatted-number', decimal: ',', thousands: ','},
+ 'formatted-number', null,
+ { type: 'date', locale: 'fr', },
+ { type: 'date', locale: 'en', format: '{dd}-{MM}-{yyyy|yy}' },
+ { type: 'date', locale: 'en', format: ['{dd}-{months}-{yyyy|yy}'] },
'IpAddress'
- ],
- col_date_type: [
- null, null, null,
- null, null, null,
- 'dmy', 'mdy', 'ddmmmyyyy',
- null
]
});
tf.init();
@@ -21,8 +18,17 @@
module('Sanity checks');
test('Data types', function() {
deepEqual(tf instanceof TableFilter, true, 'TableFilter instanciated');
- deepEqual(tf.hasColNbFormat, true, 'Has number column types');
- deepEqual(tf.hasColDateType, true, 'Has date column tyoes');
+ deepEqual(
+ tf.hasType(3, ['formatted-number']) &&
+ tf.hasType(4, ['formatted-number']),
+ true, 'Has number column types'
+ );
+ deepEqual(
+ tf.hasType(6, ['date']) &&
+ tf.hasType(7, ['date']) &&
+ tf.hasType(8, ['date']),
+ true, 'Has date column types'
+ );
});
module('Data types filtering');
@@ -86,7 +92,7 @@
deepEqual(tf.getValidRows(), [7], 'Expected rows');
});
- test('Can filter a US formatted number', function() {
+ test('Can filter a formatted number', function() {
// setup
tf.clearFilters();
@@ -98,7 +104,7 @@
deepEqual(tf.getValidRows(), [6], 'Expected rows');
});
- test('Can filter a US formatted number column with a number', function() {
+ test('Can filter a formatted number column with a number', function() {
// setup
tf.clearFilters();
@@ -110,7 +116,7 @@
deepEqual(tf.getValidRows(), [14], 'Expected rows');
});
- test('Can filter a US formatted number column with a number without ' +
+ test('Can filter a formatted number column with a number without ' +
'thousands separator', function() {
// setup
tf.clearFilters();
@@ -123,7 +129,7 @@
deepEqual(tf.getValidRows(), [13], 'Expected rows');
});
- test('Can filter a US formatted number column with a number without ' +
+ test('Can filter a formatted number column with a number without ' +
'decimals', function() {
// setup
tf.clearFilters();
@@ -161,7 +167,7 @@
deepEqual(tf.getValidRows(), [17], 'Expected rows');
});
- test('Can filter a US formatted date column', function() {
+ test('Can filter a formatted date column', function() {
// setup
tf.clearFilters();
@@ -173,7 +179,7 @@
deepEqual(tf.getValidRows(), [16], 'Expected rows');
});
- test('Can filter a US formatted date column with different date separator',
+ test('Can filter a formatted date column with different date separator',
function() {
// setup
tf.clearFilters();
diff --git a/test/test-empty-cells-filtering.js b/test/test-empty-cells-filtering.js
index 0b3d1cf0..dd0e9c67 100644
--- a/test/test-empty-cells-filtering.js
+++ b/test/test-empty-cells-filtering.js
@@ -2,7 +2,8 @@
// issue 162 - https://github.com/koalyptus/TableFilter/issues/162
var tf = new TableFilter('demo', {
base_path: '../dist/tablefilter/',
- col_date_type: ['DMY']
+ locale: 'en-GB',
+ col_types: ['date', 'string']
});
tf.init();
@@ -17,7 +18,7 @@
// assert
deepEqual(tf.getValidRows().length, 0, 'Expected filtered rows');
});
- test('Can filter DMY date type', function(){
+ test('Can filter dd.MM.yyyy date type', function(){
// setup
tf.clearFilters();
// act
diff --git a/test/test-filtering.js b/test/test-filtering.js
index 386102ea..a1977478 100644
--- a/test/test-filtering.js
+++ b/test/test-filtering.js
@@ -1,12 +1,12 @@
var tf = new TableFilter('demo', {
base_path: '../dist/tablefilter/',
- col_date_type: [
- null, null, 'ddmmmyyyy',
- null, null, null
- ],
- col_number_format: [
- null, null, null,
- null, null, 'US'
+ col_types: [
+ null,
+ { type: 'date', format: ['{dd}.{MM}.{yyyy|yy}'] },
+ { type: 'date', format: ['{dd}.{months}.{yyyy}'] },
+ null,
+ null,
+ 'formatted-number'
]
});
tf.init();