ldx-widgets
Version:
widgets
617 lines (594 loc) • 19.5 kB
JavaScript
(function() {
var React, a, assign, createClass, div, isNumeric, moment, ref1, span;
React = require('react');
createClass = require('create-react-class');
moment = require('moment');
assign = require('lodash/assign');
ref1 = require('react-dom-factories'), div = ref1.div, a = ref1.a, span = ref1.span;
isNumeric = require('./validation').isNumeric;
/*&
@general
## updateFormValue(newData, key, value)
Upstream method used for updating a single value, returning an object created based on a key definition
@param newData - [Object] - Optional
Default data object. This is the base object used to iterate upon and build the sub-properties according to the key definition
@param key - [String] - Required
The key definition is provided in order to create the object structure. There are multiple ways to structure a key:
**propertyName**
```javascript
{
propertyName: 'value'
}
```
**propertyName.[0]**
```javascript
{
propertyName: [
'value',
...
...
]
}
```
**propertyName.nestedProperty**
```javascript
{
propertyName: {
nestedProperty: 'value'
}
}
```
**propertyName.nestedProperty.doubleNestedProperty**
```javascript
{
propertyName: {
nestedProperty: {
doubleNestedProperty: 'value'
}
}
}
```
**Filtering collections and injecting state properties**
You can also inject properties from the component's local state.
This can be useful when you want to filter a collection by a state variable:
**Local component state:**
```javascript
this.state = {
currentValueFilter: 888
}
```
**arrayOfValues.[{value: $currentValueFilter}]**
```javascript
arrayOfValues = [
{
value: 11
},
{
value: 888
},
{
value: 512
}
]
```
To use local state variable injection, make sure to call `updateFormValue` with the proper context applied, so state can be found: `updateFormValue.call(@, data, jsonPath, value)`
Collections can also be filtered by literal values, e.g. `55` or `'stringValue'`.
@param value - [Any] - Required
The value to be assigned to the JSON object once the destination is reached
&
*/
module.exports = {
formatAge: function(datestring, includeMonth, datestringDeceased) {
var age, birthDate, days, deceasedDate, months, now, years;
now = moment().utc();
birthDate = moment(datestring).utc();
age = '';
if (datestringDeceased != null) {
deceasedDate = moment(datestringDeceased).utc();
days = deceasedDate.diff(birthDate, 'days');
months = deceasedDate.diff(birthDate, 'months');
years = deceasedDate.diff(birthDate, 'years');
} else {
days = now.diff(birthDate, 'days');
months = now.diff(birthDate, 'months');
years = now.diff(birthDate, 'years');
}
if (months < 1) {
age = days + " DO";
} else if (months < 48) {
age = months + " MO";
} else {
age = years + " YO";
if (includeMonth) {
months = months - (years * 12);
if (months) {
age = years + " yrs " + months + " mnth";
}
}
}
return age;
},
formatAgeInYearsOnly: function(datestring) {
var age, birthDate, now, years;
now = moment().utc();
birthDate = moment(datestring).utc();
years = now.diff(birthDate, 'years');
age = "" + years;
return age;
},
calculateDobFromAge: function(age) {
var dob, month, now, year;
now = moment().utc();
month = now.format('MM');
year = now.year() - age;
dob = "" + year + month + "01";
return dob;
},
formatAgeWithEls: function(datestring, datestringDeceased) {
var age, birthDate, days, deceasedDate, months, now, title, years;
age = [];
now = moment().utc();
birthDate = moment(datestring).utc();
if (datestringDeceased != null) {
deceasedDate = moment(datestringDeceased).utc();
days = now.diff(birthDate, 'days');
months = now.diff(birthDate, 'months');
years = now.diff(birthDate, 'years');
} else {
days = now.diff(birthDate, 'days');
months = now.diff(birthDate, 'months');
years = now.diff(birthDate, 'years');
}
if (months < 1) {
title = days + " DO";
age.push(span({
key: 'label',
className: 'pat-value',
title: title
}, "" + days));
age.push(span({
key: 'value',
className: 'pat-label',
title: title
}, "DO"));
} else if (months < 48) {
title = months + " MO";
age.push(span({
key: 'label',
className: 'pat-value',
title: title
}, "" + months));
age.push(span({
key: 'value',
className: 'pat-label',
title: title
}, "MO"));
} else {
title = years + " YO";
age.push(span({
key: 'label',
className: 'pat-value',
title: title
}, "" + years));
age.push(span({
key: 'value',
className: 'pat-label',
title: title
}, "YO"));
}
return age;
},
formatNHS: function(nhs) {
var nhs1, nhs2, nhs3, rv;
if (nhs == null) {
nhs = '';
}
nhs = nhs.replace(/[^0-9]/g, "");
nhs1 = nhs.substr(0, 3);
nhs2 = nhs.substr(3, 3);
nhs3 = nhs.substr(6, 4);
rv = "" + nhs1;
if (nhs2) {
rv += " " + nhs2;
}
if (nhs3) {
rv += " " + nhs3;
}
return rv;
},
formatPhoneNumber: function(phone) {
var phoneClone;
if (phone != null) {
phone = "" + phone;
phoneClone = phone;
phoneClone = phoneClone.replace(/[^0-9]/g, '');
if (phoneClone.length === 10) {
phoneClone = phoneClone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
return phoneClone;
}
if (phoneClone.length === 7) {
phoneClone = phoneClone.replace(/(\d{3})(\d{4})/, "$1-$2");
return phoneClone;
} else {
return phone;
}
} else {
return "";
}
},
formatSource: function(options) {
var facilityName, orgName, sourceName, systemName;
orgName = options.orgName, facilityName = options.facilityName, systemName = options.systemName;
sourceName = '';
if (orgName != null) {
sourceName += orgName;
}
if ((facilityName != null) && (facilityName !== orgName && facilityName !== '')) {
if (sourceName !== '') {
sourceName += ' - ';
}
sourceName += facilityName;
}
if (((facilityName != null) || (orgName != null)) && (systemName != null) && systemName !== '') {
if (sourceName !== '') {
sourceName += ' - ';
}
sourceName += systemName;
}
return sourceName;
},
formatTimezoneForAPI: function(relevantDate) {
var hours, minutes, minutestring, negative;
minutes = moment(relevantDate).utcOffset();
if (minutes < 0) {
negative = "-";
} else {
negative = "+";
}
minutes = Math.abs(minutes);
hours = Math.floor(minutes / 60);
if (hours < 10) {
hours = "0" + hours;
}
minutestring = minutes % 60;
if (minutestring < 10) {
minutestring = "0" + minutestring;
}
return "" + negative + hours + ":" + minutestring;
},
escapeRegExp: function(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
},
bytesToSize: function(bytes, precision) {
var gigabyte, kilobyte, megabyte, terabyte;
if (bytes == null) {
return '';
}
kilobyte = 1024;
megabyte = kilobyte * 1024;
gigabyte = megabyte * 1024;
terabyte = gigabyte * 1024;
if (bytes >= 0 && bytes < kilobyte) {
return bytes + ' B';
} else if (bytes >= kilobyte && bytes < megabyte) {
return (bytes / kilobyte).toFixed(precision) + ' KB';
} else if (bytes >= megabyte && bytes < gigabyte) {
return (bytes / megabyte).toFixed(precision) + ' MB';
} else if (bytes >= gigabyte && bytes < terabyte) {
return (bytes / gigabyte).toFixed(precision) + ' GB';
} else if (bytes >= terabyte) {
return (bytes / terabyte).toFixed(precision) + ' TB';
} else {
return bytes + ' B';
}
},
measureScrollBarWidth: function() {
var $tester, scrollBarWidth;
$tester = $("<div id='outer' style='overflow: scroll; height: 500px; width: 500px; position: absolute; top: 100px; left: 100px;'><div id='inner' style='position: absolute; height: 100%; width: 100%;'></div><div style='height: 600px; width: 600px;'></div></div>");
$('body').append($tester);
scrollBarWidth = $tester.height() - $tester.find('#inner').height();
$tester.remove();
return scrollBarWidth;
},
formatFileName: function(name, targetLength) {
var charactersFromEnd, endRemove, fileEnd, fileLength, fileStart, removeCount, startRemove;
fileLength = name.length;
if (fileLength <= targetLength) {
return name;
}
removeCount = (fileLength + 3) - targetLength;
if ((targetLength - removeCount) <= 6) {
charactersFromEnd = 4;
} else {
charactersFromEnd = 6;
}
endRemove = fileLength - charactersFromEnd;
startRemove = endRemove - removeCount;
fileStart = name.substr(0, startRemove);
fileEnd = name.substr(endRemove);
return fileStart + "…" + fileEnd;
},
parseFileExtension: function(filename) {
var filenameSplit, name;
filenameSplit = filename.split('.');
return name = filenameSplit.length > 1 ? filenameSplit[filenameSplit.length - 1] : '';
},
makeGuid: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r, v;
r = Math.random() * 16 | 0;
v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
},
idsMatch: function(itemA, itemB) {
if (!((itemA != null) && (itemB != null))) {
return false;
}
if ((itemA.id != null) && (itemB.id != null)) {
return itemA.id === itemB.id;
} else if ((itemA.guid != null) && (itemB.guid != null)) {
return itemA.guid === itemB.guid;
} else {
return false;
}
},
synthesizeMouseEvent: function(target, type, options) {
var event, opts;
if (options == null) {
options = {};
}
event = target.ownerDocument.createEvent('MouseEvents');
opts = {
type: type,
canBubble: false,
cancelable: true,
view: target.ownerDocument.defaultView,
detail: 1,
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
button: 0,
relatedTarget: null
};
assign(opts, options);
event.initMouseEvent(opts.type, opts.canBubble, opts.cancelable, opts.view, opts.detail, opts.screenX, opts.screenY, opts.clientX, opts.clientY, opts.ctrlKey, opts.altKey, opts.shiftKey, opts.metaKey, opts.button, opts.relatedTarget);
return target.dispatchEvent(event);
},
toFixed: function(value, decimalPlaces) {
var multiplier;
if (decimalPlaces == null) {
decimalPlaces = 2;
}
if (!isNumeric(value)) {
return value;
}
multiplier = Math.pow(10, decimalPlaces);
return Math.round(value * multiplier) / multiplier;
},
measureDOMProp: function(el, DOMProp) {
var measurer, prop;
measurer = document.getElementById('measurer');
measurer.appendChild(el);
prop = el[DOMProp];
measurer.removeChild(el);
return prop;
},
checkHTTPS: function(url) {
var checkString;
checkString = url.slice(0, 5);
return checkString === "https";
},
alphaNumericKeyCode: function(code) {
if (!(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) {
return false;
}
return true;
},
buildFormData: function(context, newData) {
var getValue, iterate, key, keyParts, ref, refs;
if (context == null) {
context = this;
}
if (newData == null) {
newData = {};
}
refs = context['refs'];
if (refs == null) {
throw Error("Form Data Builder: No 'refs' object found on context " + context);
}
iterate = (function(_this) {
return function(data, keyParts, getValue) {
var arrayKey, collectionKey, collectionRecord, cur, d, i, j, k, len, matchArray, matchCollection, next, nextIsArray, obj, subKeys, v, val, valRef;
cur = keyParts[0];
next = data;
matchArray = cur.match(/\[(\d+)\]/);
matchCollection = cur.match(/\[\{(.+)\}\]/);
if (keyParts[1] != null) {
nextIsArray = keyParts[1].match(/\[(.+)\]/);
}
if (matchArray != null) {
arrayKey = +matchArray[1];
}
if (matchCollection != null) {
collectionKey = matchCollection[1].split(':');
}
if (arrayKey != null) {
if (data == null) {
data = [];
}
next = data[arrayKey];
cur = arrayKey;
} else if (collectionKey) {
if (data == null) {
data = [];
}
collectionRecord = null;
k = collectionKey[0];
v = collectionKey[1];
valRef = v.match(/\$(\w+)/);
if (valRef != null) {
val = context['state'];
if (val == null) {
throw Error("Form Data Builder: unable to pull state properties when local state is undefined");
}
subKeys = v.replace(/^\s?\$/, '').split('.');
while (subKeys.length) {
val = val[subKeys.shift()];
}
v = val;
}
for (i = j = 0, len = data.length; j < len; i = ++j) {
obj = data[i];
if (obj != null) {
if ((obj[k] != null) && String(obj[k]) === String(v)) {
collectionRecord = next = data[i];
break;
}
}
}
if (collectionRecord == null) {
d = {};
d[k] = v;
data.push(d);
next = data[data.length - 1];
}
} else if (data[cur] == null) {
next = data[cur] = nextIsArray ? [] : {};
} else {
next = data[cur];
}
if (!(keyParts.length > 1)) {
data[cur] = getValue();
return data;
}
keyParts.shift();
return iterate(next, keyParts, getValue);
};
})(this);
for (key in refs) {
ref = refs[key];
if (key[0] !== '!' && (ref.getValue != null)) {
if (key.match(/\.(?![^[\]]*])/)) {
keyParts = key.split(/\.(?![^[\]]*])/g);
getValue = ref.getValue;
if (getValue == null) {
throw Error("Ref " + key + " does not have a getValue method defined");
}
iterate(newData, keyParts, getValue);
} else {
newData[key] = ref.getValue();
}
}
}
return newData;
},
updateFormValue: function(newData, key, value) {
var iterate, keyParts;
if (newData == null) {
newData = {};
}
iterate = (function(_this) {
return function(data, keyParts) {
var arrayKey, collectionKey, collectionRecord, cur, d, i, j, k, len, matchArray, matchCollection, next, nextIsArray, obj, subKeys, v, val, valRef;
cur = keyParts[0];
next = data;
matchArray = cur.match(/\[(\d+)\]/);
matchCollection = cur.match(/\[\{(.+)\}\]/);
if (keyParts[1] != null) {
nextIsArray = keyParts[1].match(/\[(.+)\]/);
}
if (matchArray != null) {
arrayKey = +matchArray[1];
}
if (matchCollection != null) {
collectionKey = matchCollection[1].split(':');
}
if (arrayKey != null) {
if (data == null) {
data = [];
}
next = data[arrayKey];
cur = arrayKey;
} else if (collectionKey) {
if (data == null) {
data = [];
}
collectionRecord = null;
k = collectionKey[0];
v = collectionKey[1];
valRef = v.match(/\$(\w+)/);
if (valRef != null) {
val = _this.state;
if (val == null) {
throw Error("Form Data Builder: unable to pull state properties when local state is undefined");
}
subKeys = v.replace(/^\s?\$/, '').split('.');
while (subKeys.length) {
val = val[subKeys.shift()];
}
v = val;
}
for (i = j = 0, len = data.length; j < len; i = ++j) {
obj = data[i];
if (obj != null) {
if ((obj[k] != null) && String(obj[k]) === String(v)) {
collectionRecord = next = data[i];
break;
}
}
}
if (collectionRecord == null) {
d = {};
d[k] = v;
data.push(d);
next = data[data.length - 1];
}
} else if (data[cur] == null) {
next = data[cur] = nextIsArray ? [] : {};
} else {
next = data[cur];
}
if (!(keyParts.length > 1)) {
data[cur] = value;
return data;
}
keyParts.shift();
return iterate(next, keyParts);
};
})(this);
if (key.match(/\.(?![^[\]]*])/)) {
keyParts = key.split(/\.(?![^[\]]*])/g);
iterate(newData, keyParts);
} else {
newData[key] = value;
}
return assign({}, newData);
},
isValidEmail: function(addr) {
return /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.test(addr);
},
stripTags: function(text) {
var el;
el = document.createElement('div');
el.innerHTML = text;
return el.innerText;
},
stripScriptTags: function(text) {
var el, j, script, scripts;
el = document.createElement('div');
el.innerHTML = text;
scripts = el.getElementsByTagName('script');
for (j = scripts.length - 1; j >= 0; j += -1) {
script = scripts[j];
script.parentElement.removeChild(script);
}
return el.innerHTML;
}
};
}).call(this);