Skip to content

Instantly share code, notes, and snippets.

@StephanHoyer
Created October 13, 2015 06:53
Show Gist options
  • Save StephanHoyer/85068ae7b0a174216d00 to your computer and use it in GitHub Desktop.
Save StephanHoyer/85068ae7b0a174216d00 to your computer and use it in GitHub Desktop.
'use strict';
var m = require('mithril');
var t = require('client/utils/translate');
var vagueTime = require('vague-time');
var l16n = require('client/utils/l16n');
function assignValue(obj, objAttr) {
return function (event) {
var currentValue = obj[objAttr];
var newValue = event.currentTarget.value;
obj[objAttr] = newValue;
if (obj.onChange && obj.onChange.dispatch) {
obj.onChange.dispatch(objAttr, newValue, currentValue);
}
};
}
function setFocus(element, isInitialized) {
if (!isInitialized) {
element.focus();
}
}
function toOptions(collection, valueAttribute, labelAttribute) {
return collection.map(function (item) {
return [item[valueAttribute], item[labelAttribute]];
});
}
function stopPropagation(event) {
event.stopPropagation();
}
function removeHtmlTags(text) {
return text ? text.replace(/<(?:.|\n)*?>/gm, '') : text;
}
function elipsis(length) {
return function(text) {
if (text.length <= length) {
return text;
}
return text.substring(0, length) + '...';
};
}
function wrapInRedraw(fn) {
return function() {
m.startComputation();
fn.apply(null, arguments);
m.endComputation();
};
}
/**
* Returns a css className for all keys which valueStatements are truthy
*/
function classy(def) {
return Object.keys(def).filter(function(className) {
return def[className];
}).join(' ');
}
function getTimeDifference(fromDateTime, toDateTime) {
fromDateTime = new Date(fromDateTime);
//Set current datetime if to datetime is not given
toDateTime = toDateTime || new Date();
return vagueTime.get({
from: toDateTime.getTime(),
to: fromDateTime.getTime(),
lang: 'de'
});
}
var redrawInterval;
function fuzzyTime(date) {
if (!redrawInterval) {
redrawInterval = setInterval(function() {
m.startComputation();
m.endComputation();
}, 60 * 1000);
}
var withTooltip = require('client/components/tooltip').withTooltip;
if (!date) {
return t('global.never');
}
return withTooltip(
m('a.dateDifference', getTimeDifference(date)),
l16n.date.YMDHI(date),
{ dark: true, delay: 100 }
);
}
function deferEmpty(viewFn, timeout) {
var oldResult = '';
return function() {
var result = viewFn.apply(null, arguments);
if (!result && oldResult !== result) {
setTimeout(function() {
m.startComputation();
oldResult = result;
m.endComputation();
}, timeout);
return oldResult;
}
oldResult = result;
return result;
};
}
module.exports = {
assignValue: assignValue,
setFocus: setFocus,
toOptions: toOptions,
stopPropagation: stopPropagation,
removeHtmlTags: removeHtmlTags,
elipsis: elipsis,
wrapInRedraw: wrapInRedraw,
classy: classy,
fuzzyTime: fuzzyTime,
deferEmpty: deferEmpty
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment