datetime.js (2425B)
1 ( function ( $, _, rwmb, i18n ) { 2 'use strict'; 3 4 /** 5 * Transform an input into a datetime picker. 6 */ 7 function transform() { 8 var $this = $( this ), 9 options = $this.data( 'options' ), 10 $inline = $this.siblings( '.rwmb-datetime-inline' ), 11 $timestamp = $this.siblings( '.rwmb-datetime-timestamp' ), 12 current = $this.val(), 13 $picker = $inline.length ? $inline : $this; 14 15 $this.siblings( '.ui-datepicker-append' ).remove(); // Remove appended text 16 17 options.onSelect = function() { 18 $this.trigger( 'change' ); 19 } 20 options.beforeShow = function( i ) { 21 if ( $( i ).prop( 'readonly' ) ) { 22 return false; 23 } 24 } 25 26 if ( $timestamp.length ) { 27 options.onClose = options.onSelect = function () { 28 $timestamp.val( getTimestamp( $picker.datetimepicker( 'getDate' ) ) ); 29 $this.trigger( 'change' ); 30 }; 31 } 32 33 if ( ! $inline.length ) { 34 $this.removeClass( 'hasDatepicker' ).datetimepicker( options ); 35 return; 36 } 37 38 options.altField = '#' + $this.attr( 'id' ); 39 $this.on( 'keydown', _.debounce( function () { 40 // if val is empty, return to allow empty datepicker input. 41 if ( ! $this.val() ) { 42 return; 43 } 44 $picker 45 .datepicker( 'setDate', $this.val() ) 46 .find( '.ui-datepicker-current-day' ) 47 .trigger( 'click' ); 48 }, 600 ) ); 49 50 $inline 51 .removeClass( 'hasDatepicker' ) 52 .empty() 53 .prop( 'id', '' ) 54 .datetimepicker( options ) 55 .datetimepicker( 'setDate', current ); 56 } 57 58 /** 59 * Convert date to Unix timestamp in milliseconds 60 * @link http://stackoverflow.com/a/14006555/556258 61 * @param date 62 * @return number 63 */ 64 function getTimestamp( date ) { 65 if ( date === null ) { 66 return ''; 67 } 68 var milliseconds = Date.UTC( date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds() ); 69 return Math.floor( milliseconds / 1000 ); 70 } 71 72 // Set language if available 73 function setTimeI18n() { 74 if ( $.timepicker.regional.hasOwnProperty( i18n.locale ) ) { 75 $.timepicker.setDefaults( $.timepicker.regional[i18n.locale] ); 76 } else if ( $.timepicker.regional.hasOwnProperty( i18n.localeShort ) ) { 77 $.timepicker.setDefaults( $.timepicker.regional[i18n.localeShort] ); 78 } 79 } 80 81 function init( e ) { 82 $( e.target ).find( '.rwmb-datetime' ).each( transform ); 83 } 84 85 setTimeI18n(); 86 rwmb.$document 87 .on( 'mb_ready', init ) 88 .on( 'clone', '.rwmb-datetime', transform ); 89 } )( jQuery, _, rwmb, RWMB_Datetime );