combodate ready

This commit is contained in:
vitalets 2013-01-10 22:13:28 +04:00
parent 1f61f27047
commit a3b21b8f4b
7 changed files with 715 additions and 3 deletions

@ -15,9 +15,22 @@
$.extend(this.containerOptions, {
trigger: 'manual',
selector: false,
content: ' '
content: ' ',
template: $.fn.popover.defaults.template
});
//as template property is used in inputs, hide it from popover
var t;
if(this.$element.data('template')) {
t = this.$element.data('template');
this.$element.removeData('template');
}
this.call(this.containerOptions);
if(t) {
this.$element.data('template', t);
}
},
setContainerOption: function(key, value) {

@ -0,0 +1,184 @@
/**
Combodate input - dropdown date and time picker.
Based on [combodate](http://vitalets.github.com/combodate) plugin.
To use it you should manually include [momentjs](http://momentjs.com).
Allows to enter:
* only date
* only time
* datetime
Please note, that format is taken from momentjs and not compatible with bootstrap-datepicker / jquery UI datepicker.
Internally value stored as Moment js object
@class combodate
@extends abstractinput
@final
@example
<a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-original-title="Select date"></a>
<script>
$(function(){
$('#dob').editable({
format: 'YYYY-MM-DD',
viewformat: 'YYYY-MM-DD',
template: 'D / MMMM / YYYY',
combodate: {
minYear: 2000,
maxYear: 2015,
minuteStep: 1
}
}
});
});
</script>
**/
(function ($) {
var Constructor = function (options) {
this.init('combodate', options, Constructor.defaults);
//by default viewformat equals to format
if(!this.options.viewformat) {
this.options.viewformat = this.options.format;
}
//overriding combodate config (as by default jQuery extend() is not recursive)
this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, {
format: this.options.format,
template: this.options.template
});
};
$.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);
$.extend(Constructor.prototype, {
render: function () {
this.$input.combodate(this.options.combodate);
//"clear" link
/*
if(this.options.clear) {
this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
e.preventDefault();
e.stopPropagation();
this.clear();
}, this));
this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));
}
*/
},
value2html: function(value, element) {
var text = value ? value.format(this.options.viewformat) : '';
$(element).text(text);
},
html2value: function(html) {
return html ? moment(html, this.options.viewformat) : null;
},
value2str: function(value) {
return value ? value.format(this.options.format) : '';
},
str2value: function(str) {
return str ? moment(str, this.options.format) : null;
},
value2submit: function(value) {
return this.value2str(value);
},
value2input: function(value) {
this.$input.combodate('setValue', value);
},
input2value: function() {
return this.$input.combodate('getValue', null);
},
activate: function() {
this.$input.siblings('.combodate').find('select').eq(0).focus();
},
/*
clear: function() {
this.$input.data('datepicker').date = null;
this.$input.find('.active').removeClass('active');
},
*/
autosubmit: function() {
}
});
Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <input type="text">
**/
tpl:'<input type="text">',
/**
@property inputclass
@default null
**/
inputclass: null,
/**
Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format)
@property format
@type string
@default YYYY-MM-DD
**/
format:'YYYY-MM-DD',
/**
Format used for displaying date. Also applied when converting date from element's text on init.
If not specified equals to `format`.
@property viewformat
@type string
@default null
**/
viewformat: null,
/**
Template used for displaying dropdowns.
@property template
@type string
@default D / MMM / YYYY
**/
template: 'D / MMM / YYYY',
/**
Configuration of combodate.
Full list of options: http://vitalets.github.com/combodate/#docs
@property datepicker
@type object
@default {
weekStart: 0,
startView: 0,
autoclose: false
}
**/
combodate: {
},
/*
(not implemented yet)
Text shown as clear date button.
If <code>false</code> clear button will not be rendered.
@property clear
@type boolean|string
@default 'x clear'
*/
//clear: '&times; clear'
});
$.fn.editabletypes.combodate = Constructor;
}(window.jQuery));

@ -0,0 +1,398 @@
/**
* Combodate - 1.0.0
* Dropdown date and time picker.
* Converts text input into dropdowns to pick day, month, year, hour, minute and second.
* Uses momentjs as datetime library http://momentjs.com.
* For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang
*
* Author: Vitaliy Potapov
* Project page: http://github.com/vitalets/combodate
* Copyright (c) 2012 Vitaliy Potapov. Released under MIT License.
**/
(function ($) {
var Combodate = function (element, options) {
this.$element = $(element);
if(!this.$element.is('input')) {
$.error('Combodate should be applied to INPUT element');
return;
}
this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data());
this.init();
};
Combodate.prototype = {
constructor: Combodate,
init: function () {
this.map = {
//key regexp moment.method
day: ['D', 'date'],
month: ['M', 'month'],
year: ['Y', 'year'],
hour: ['[Hh]', 'hours'],
minute: ['m', 'minutes'],
second: ['s', 'seconds'],
ampm: ['[Aa]', '']
};
this.$widget = $('<span class="combodate"></span>').html(this.getTemplate());
this.initCombos();
//update original input on change
this.$widget.on('change', 'select', $.proxy(function(){
this.$element.val(this.getValue());
}, this));
this.$widget.find('select').css('width', 'auto');
//hide original input and insert widget
this.$element.hide().after(this.$widget);
//set initial value
this.setValue(this.$element.val() || this.options.value);
},
/*
Replace tokens in template with <select> elements
*/
getTemplate: function() {
var tpl = this.options.template;
//first pass
$.each(this.map, function(k, v) {
var v = v[0],
r = new RegExp(v+'+'),
token = v.length > 1 ? v.substring(1, 2) : v;
tpl = tpl.replace(r, '{'+token+'}');
});
//replace spaces with &nbsp;
tpl = tpl.replace(/ /g, '&nbsp;');
//second pass
$.each(this.map, function(k, v) {
var v = v[0],
token = v.length > 1 ? v.substring(1, 2) : v;
tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>');
});
return tpl;
},
/*
Initialize combos that presents in template
*/
initCombos: function() {
var that = this;
$.each(this.map, function(k, v) {
var $c = that.$widget.find('.'+k), f, items;
if($c.length) {
that['$'+k] = $c; //set properties like this.$day, this.$month etc.
f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); //define method name to fill items, e.g `fillDays`
items = that[f]();
that['$'+k].html(that.renderItems(items));
}
});
},
/*
Initialize items of combos. Handles `firstItem` option
*/
initItems: function(key) {
var values = [];
if(this.options.firstItem === 'name') {
var header = typeof moment.relativeTime[key] === 'function' ? moment.relativeTime[key](1, true, key, false) : moment.relativeTime[key];
//take last entry (see momentjs lang files structure)
header = header.split(' ').reverse()[0];
values.push(['', header]);
} else if(this.options.firstItem === 'empty') {
values.push(['', '']);
}
return values;
},
/*
render items to string of <option> tags
*/
renderItems: function(items) {
var str = [];
for(var i=0; i<items.length; i++) {
str.push('<option value="'+items[i][0]+'">'+items[i][1]+'</option>');
}
return str.join("\n");
},
/*
fill day
*/
fillDay: function() {
var items = this.initItems('d'), name, i,
twoDigit = this.options.template.indexOf('DD') !== -1;
for(i=1; i<=31; i++) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill month
*/
fillMonth: function() {
var items = this.initItems('M'), name, i,
longNames = this.options.template.indexOf('MMMM') !== -1,
shortNames = this.options.template.indexOf('MMM') !== -1,
twoDigit = this.options.template.indexOf('MM') !== -1;
for(i=0; i<=11; i++) {
if(longNames) {
name = moment.months[i];
} else if(shortNames) {
name = moment.monthsShort[i];
} else if(twoDigit) {
name = this.leadZero(i+1);
} else {
name = i+1;
}
items.push([i, name]);
}
return items;
},
/*
fill year
*/
fillYear: function() {
var items = this.initItems('y'), name, i,
longNames = this.options.template.indexOf('YYYY') !== -1;
for(i=this.options.maxYear; i>=this.options.minYear; i--) {
name = longNames ? i : (i+'').substring(2);
items.push([i, name]);
}
return items;
},
/*
fill hour
*/
fillHour: function() {
var items = this.initItems('h'), name, i,
h12 = this.options.template.indexOf('h') !== -1,
h24 = this.options.template.indexOf('H') !== -1,
twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1,
max = h12 ? 12 : 23;
for(i=0; i<=max; i++) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill minute
*/
fillMinute: function() {
var items = this.initItems('m'), name, i,
twoDigit = this.options.template.indexOf('mm') !== -1;
for(i=0; i<=59; i+= this.options.minuteStep) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill second
*/
fillSecond: function() {
var items = this.initItems('s'), name, i,
twoDigit = this.options.template.indexOf('ss') !== -1;
for(i=0; i<=59; i+= this.options.secondStep) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill ampm
*/
fillAmpm: function() {
var ampmL = this.options.template.indexOf('a') !== -1,
ampmU = this.options.template.indexOf('A') !== -1,
items = [
['am', ampmL ? 'am' : 'AM'],
['pm', ampmL ? 'pm' : 'PM']
];
return items;
},
/*
Returns current date value.
If format not specified - `options.format` used.
If format = `null` - Moment object returned.
*/
getValue: function(format) {
var dt, values = {},
that = this,
notSelected = false;
//getting selected values
$.each(this.map, function(k, v) {
if(k === 'ampm') {
return;
}
var def = k === 'day' ? 1 : 0;
values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def;
if(isNaN(values[k])) {
notSelected = true;
return false;
}
});
//if at least one visible combo not selected - return empty string
if(notSelected) {
return '';
}
//convert hours if 12h format
if(this.$ampm) {
values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12;
if(values.hour === 24) {
values.hour = 0;
}
}
dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]);
//highlight invalid date
this.highlight(dt);
format = format === undefined ? this.options.format : format;
if(format === null) {
return dt.isValid() ? dt : null;
} else {
return dt.isValid() ? dt.format(format) : '';
}
},
setValue: function(value) {
if(!value) {
return;
}
var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value),
that = this,
values = {};
if(dt.isValid()) {
//read values from date object
$.each(this.map, function(k, v) {
if(k === 'ampm') {
return;
}
values[k] = dt[v[1]]();
});
if(this.$ampm) {
if(values.hour > 12) {
values.hour -= 12;
values.ampm = 'pm';
} else {
values.ampm = 'am';
}
}
$.each(values, function(k, v) {
if(that['$'+k]) {
that['$'+k].val(v);
}
});
this.$element.val(dt.format(this.options.format));
}
},
/*
highlight combos if date is invalid
*/
highlight: function(dt) {
if(!dt.isValid()) {
if(this.options.errorClass) {
this.$widget.addClass(this.options.errorClass);
} else {
//store original border color
if(!this.borderColor) {
this.borderColor = this.$widget.find('select').css('border-color');
}
this.$widget.find('select').css('border-color', 'red');
}
} else {
if(this.options.errorClass) {
this.$widget.removeClass(this.options.errorClass);
} else {
this.$widget.find('select').css('border-color', this.borderColor);
}
}
},
leadZero: function(v) {
return v <= 9 ? '0' + v : v;
},
destroy: function() {
this.$widget.remove();
this.$element.removeData('combodate').show();
}
//todo: clear method
};
$.fn.combodate = function ( option ) {
var d, args = Array.apply(null, arguments);
args.shift();
//getValue returns date as string / object (not jQuery object)
if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) {
return d.getValue.apply(d, args);
}
return this.each(function () {
var $this = $(this),
data = $this.data('combodate'),
options = typeof option == 'object' && option;
if (!data) {
$this.data('combodate', (data = new Combodate(this, options)));
}
if (typeof option == 'string' && typeof data[option] == 'function') {
data[option].apply(data, args);
}
});
};
$.fn.combodate.defaults = {
//in this format value stored in original input
format: 'DD-MM-YYYY HH:mm',
//in this format items in dropdowns are displayed
template: 'D / MMM / YYYY H : mm',
//initial value, can be `new Date()`
value: null,
minYear: 1970,
maxYear: 2015,
minuteStep: 5,
secondStep: 1,
firstItem: 'empty', //'name', 'empty', 'none'
errorClass: null
};
}(window.jQuery));

File diff suppressed because one or more lines are too long

@ -31,6 +31,7 @@ define(function () {
loadCss(require.toUrl("./editable-element.css"));
}
},
//default inputs
'editable-form/editable-form': {
deps: ['require',
'inputs/text',
@ -38,6 +39,7 @@ define(function () {
'inputs/select',
'inputs/checklist',
'inputs/html5types',
'inputs/combodate/combodate',
'inputs-ext/address/address'],
init: function(require) {
loadCss(require.toUrl("./editable-form.css"));
@ -49,7 +51,8 @@ define(function () {
'inputs/text': ['inputs/abstract'],
'inputs/textarea': ['inputs/abstract'],
'inputs/abstract': ['editable-form/editable-form-utils'],
'inputs/html5types': ['inputs/text'],
'inputs/html5types': ['inputs/text'],
'inputs/combodate/combodate': ['inputs/abstract', 'inputs/combodate/lib/combodate', 'inputs/combodate/lib/moment.min'],
/*
bootstrap

@ -44,7 +44,8 @@ require(["loader", jqurl], function(loader) {
'test/unit/text',
'test/unit/textarea',
'test/unit/select',
'test/unit/checklist'
'test/unit/checklist',
'test/unit/combodate'
];
tests = tests.concat(custom);
tests.push('test/unit/api');

107
test/unit/combodate.js Normal file

@ -0,0 +1,107 @@
$(function () {
//formats
var
fd = 'DD.MM.YYYY', vfd = 'DD-MM-YYYY', vd = '15-05-1984',
fdt = 'DD-MM-YYYY hh:mm:ss A', vfdt = 'DD MMM YYYY h:m:s a', vdt = '15-05-1984 08:20:30 PM';
module("combodate", {
setup: function(){
fx = $('#async-fixture');
$.support.transition = false;
}
});
asyncTest("container should contain combodate and save new value (date)", function () {
var e = $('<a href="#" data-type="combodate" data-pk="1" data-url="/combodate">'+vd+'</a>').appendTo(fx).editable({
format: fd,
viewformat: vfd,
template: fd
}),
m = moment(vd, vfd);
$.mockjax({
url: '/combodate',
response: function(settings) {
equal(settings.data.value, m.format(fd), 'submitted value correct');
}
});
equal(e.data('editable').value.format(fd), m.format(fd), 'init value correct');
e.click();
var p = tip(e);
ok(p.find('.combodate').is(':visible'), 'combodate exists');
equal(p.find('.day, .month, .year, .hour, .minute').length, 3, 'combos correct');
equal(p.find('.day').val(), m.date(), 'day set correct');
equal(p.find('.month').val(), m.month(), 'month set correct');
equal(p.find('.year').val(), m.year(), 'year set correct');
//set new day
p.find('.day').val(16).trigger('change');
m.date(16);
p.find('form').submit();
setTimeout(function() {
ok(!p.is(':visible'), 'container closed');
equal(e.data('editable').value.format(fd), m.format(fd), 'new value correct');
equal(e.text(), m.format(vfd), 'new text correct');
e.remove();
start();
}, timeout);
});
asyncTest("container should contain combodate and save new value (datetime)", function () {
var e = $('<a href="#" data-type="combodate" data-pk="1" data-url="/combodate-dt" data-value="'+vdt+'"></a>').appendTo(fx).editable({
format: fdt,
viewformat: vfdt,
template: fdt
}),
m = moment(vdt, fdt);
$.mockjax({
url: '/combodate-dt',
response: function(settings) {
equal(settings.data.value, m.format(fdt), 'submitted value correct');
}
});
equal(e.data('editable').value.format(fdt), m.format(fdt), 'init value correct');
equal(e.text(), m.format(vfdt), 'init text correct');
e.click();
var p = tip(e);
ok(p.find('.combodate').is(':visible'), 'combodate exists');
equal(p.find('.day, .month, .year, .hour, .minute, .second, .ampm').length, 7, 'combos correct');
equal(p.find('.day').val(), m.date(), 'day set correct');
equal(p.find('.month').val(), m.month(), 'month set correct');
equal(p.find('.year').val(), m.year(), 'year set correct');
equal(p.find('.hour').val(), m.hours()-12, 'hour set correct');
equal(p.find('.minute').val(), m.minutes(), 'minute set correct');
equal(p.find('.second').val(), m.seconds(), 'second set correct');
equal(p.find('.ampm').val(), 'pm', 'ampm set correct');
//set new day
p.find('.day').val(16).trigger('change');
p.find('.hour').val(9).trigger('change');
m.date(16);
m.hours(21);
p.find('form').submit();
setTimeout(function() {
ok(!p.is(':visible'), 'container closed');
equal(e.data('editable').value.format(fdt), m.format(fdt), 'new value correct');
equal(e.text(), m.format(vfdt), 'new text correct');
e.remove();
start();
}, timeout);
});
});