calendar.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. /*!
  2. * Pikaday
  3. *
  4. * Copyright © 2014 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday
  5. */
  6. var pickers = {};
  7. var clLangs = {
  8. ua: {
  9. previousMonth : 'Попередній місяць',
  10. nextMonth : 'Наступний місяць',
  11. months : ['Січень','Лютий','Березень','Квітень','Травень','Червень','Липень','Серпень','Вересень','Жовтень','Листопад','Грудень'],
  12. weekdays : ['Неділя','Понеділок','Вівторок','Середа','Четвер','П’ятниця','Субота'],
  13. weekdaysShort : ['Нд','Пн','Вв','Ср','Чт','Пт','Сб']
  14. },
  15. ru: {
  16. previousMonth : 'Предыдущий месяц',
  17. nextMonth : 'Следующий месяц',
  18. months : ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
  19. weekdays : ['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'],
  20. weekdaysShort : ['Вс','Пн','Вт','Ср','Чт','Пт','Сб']
  21. },
  22. en: {
  23. previousMonth : 'Previous Month',
  24. nextMonth : 'Next Month',
  25. months : ['January','February','March','April','May','June','July','August','September','October','November','December'],
  26. weekdays : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
  27. weekdaysShort : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
  28. }
  29. };
  30. function getDateParamBySign(date,sign) {
  31. sign = sign.toUpperCase();
  32. var param;
  33. switch(sign) {
  34. case "YYYY":
  35. param = date.getFullYear().toString();break;
  36. case "YY":
  37. param = date.getFullYear().toString().substr(2,2);break;
  38. case "MM":
  39. param = (date.getMonth()+1);
  40. param = (param >= 10) ? param.toString() : ("0"+param.toString());
  41. break;
  42. case "DD":
  43. param = (date.getDate() >= 10) ? date.getDate().toString() : ("0"+date.getDate().toString());
  44. break;
  45. default:
  46. param = date.toDateString();
  47. }
  48. return param;
  49. }
  50. function formatter(date, format) {
  51. date = date || new Date();
  52. format = format || "DD.MM.YYYY";
  53. var signs = format.match(/(Y{2,4})|(M{2})|(D{2})/g);
  54. var params = [];
  55. var reStr = '';
  56. for(var i=0; i<signs.length; ++i) {
  57. params.push(getDateParamBySign(date,signs[i]));
  58. reStr += ((i+1) != signs.length) ? signs[i] + "(.)" : signs[i];
  59. }
  60. var re = new RegExp(reStr,'g');
  61. var delimiters = re.exec(format);
  62. delimiters.splice(0,1);
  63. var value = "";
  64. for(i=0; i<params.length; i++) {
  65. value += ((i+1) != params.length) ? (params[i] + delimiters[i]) : params[i];
  66. }
  67. return value;
  68. }
  69. function parser(str, format) {
  70. format = format || "DD.MM.YYYY";
  71. var signs = format.match(/(Y{2,4})|(M{2})|(D{2})/g);
  72. var reStr = "(";
  73. for(var i=0; i<signs.length; ++i) {
  74. reStr += ".".repeat(signs[i].length) + (((i+1) != signs.length) ? ").(" : ")");
  75. }
  76. var re = new RegExp(reStr,'g');
  77. var values = re.exec(str);
  78. var year, month, day;
  79. if (values && signs.length+1 == values.length) {
  80. values = values.slice(1);
  81. for(var i=0; i<signs.length; ++i) {
  82. switch(signs[i].slice(0,1)){
  83. case "Y": year = values[i]; break;
  84. case "M": month = values[i]; break;
  85. case "D": day = values[i]; break;
  86. }
  87. }
  88. const res = new Date(year, month-1, day);
  89. return res;
  90. }
  91. return null;
  92. }
  93. // function parseDateFromInput(value) {
  94. // if(isNaN(Date.parse(value))) {
  95. // var res = /^(\d{1,2})\.(\d{1,2})\.(\d{4})$/.exec(value);
  96. // if(res && res.length == 4) { return new Date(res[3],(res[2]-1),res[1]); }
  97. // else { return null; }
  98. // }else{ return new Date(Date.parse(value)); }
  99. // }
  100. (function (root, factory)
  101. {
  102. 'use strict';
  103. var moment;
  104. if (typeof exports === 'object') {
  105. // CommonJS module
  106. // Load moment.js as an optional dependency
  107. try { moment = require('moment'); } catch (e) {}
  108. module.exports = factory(moment);
  109. } else if (typeof define === 'function' && define.amd) {
  110. // AMD. Register as an anonymous module.
  111. define(function (req)
  112. {
  113. // Load moment.js as an optional dependency
  114. var id = 'moment';
  115. try { moment = req(id); } catch (e) {}
  116. return factory(moment);
  117. });
  118. } else {
  119. root.Pikaday = factory(root.moment);
  120. }
  121. }(this, function (moment)
  122. {
  123. 'use strict';
  124. /**
  125. * feature detection and helper functions
  126. */
  127. var hasMoment = typeof moment === 'function',
  128. hasEventListeners = !!window.addEventListener,
  129. document = window.document,
  130. sto = window.setTimeout,
  131. addEvent = function(el, e, callback, capture)
  132. {
  133. if (hasEventListeners) {
  134. el.addEventListener(e, callback, !!capture);
  135. } else {
  136. el.attachEvent('on' + e, callback);
  137. }
  138. },
  139. removeEvent = function(el, e, callback, capture)
  140. {
  141. if (hasEventListeners) {
  142. el.removeEventListener(e, callback, !!capture);
  143. } else {
  144. el.detachEvent('on' + e, callback);
  145. }
  146. },
  147. fireEvent = function(el, eventName, data)
  148. {
  149. var ev;
  150. if (document.createEvent) {
  151. ev = document.createEvent('HTMLEvents');
  152. ev.initEvent(eventName, true, false);
  153. ev = extend(ev, data);
  154. el.dispatchEvent(ev);
  155. } else if (document.createEventObject) {
  156. ev = document.createEventObject();
  157. ev = extend(ev, data);
  158. el.fireEvent('on' + eventName, ev);
  159. }
  160. },
  161. trim = function(str)
  162. {
  163. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g,'');
  164. },
  165. hasClass = function(el, cn)
  166. {
  167. return (' ' + el.className + ' ').indexOf(' ' + cn + ' ') !== -1;
  168. },
  169. addClass = function(el, cn)
  170. {
  171. if (!hasClass(el, cn)) {
  172. el.className = (el.className === '') ? cn : el.className + ' ' + cn;
  173. }
  174. },
  175. removeClass = function(el, cn)
  176. {
  177. el.className = trim((' ' + el.className + ' ').replace(' ' + cn + ' ', ' '));
  178. },
  179. isArray = function(obj)
  180. {
  181. return (/Array/).test(Object.prototype.toString.call(obj));
  182. },
  183. isDate = function(obj)
  184. {
  185. return (/Date/).test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());
  186. },
  187. isWeekend = function(date)
  188. {
  189. var day = date.getDay();
  190. return day === 0 || day === 6;
  191. },
  192. isLeapYear = function(year)
  193. {
  194. // solution by Matti Virkkunen: http://stackoverflow.com/a/4881951
  195. return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
  196. },
  197. getDaysInMonth = function(year, month)
  198. {
  199. return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
  200. },
  201. setToStartOfDay = function(date)
  202. {
  203. if (isDate(date)) date.setHours(0,0,0,0);
  204. },
  205. compareDates = function(a,b)
  206. {
  207. // weak date comparison (use setToStartOfDay(date) to ensure correct result)
  208. return a.getTime() === b.getTime();
  209. },
  210. extend = function(to, from, overwrite)
  211. {
  212. var prop, hasProp;
  213. for (prop in from) {
  214. hasProp = to[prop] !== undefined;
  215. if (hasProp && typeof from[prop] === 'object' && from[prop] !== null && from[prop].nodeName === undefined) {
  216. if (isDate(from[prop])) {
  217. if (overwrite) {
  218. to[prop] = new Date(from[prop].getTime());
  219. }
  220. }
  221. else if (isArray(from[prop])) {
  222. if (overwrite) {
  223. to[prop] = from[prop].slice(0);
  224. }
  225. } else {
  226. to[prop] = extend({}, from[prop], overwrite);
  227. }
  228. } else if (overwrite || !hasProp) {
  229. to[prop] = from[prop];
  230. }
  231. }
  232. return to;
  233. },
  234. adjustCalendar = function(calendar) {
  235. if (calendar.month < 0) {
  236. calendar.year -= Math.ceil(Math.abs(calendar.month)/12);
  237. calendar.month += 12;
  238. }
  239. if (calendar.month > 11) {
  240. calendar.year += Math.floor(Math.abs(calendar.month)/12);
  241. calendar.month -= 12;
  242. }
  243. return calendar;
  244. },
  245. /**
  246. * defaults and localisation
  247. */
  248. defaults = {
  249. // bind the picker to a form field
  250. field: null,
  251. // automatically show/hide the picker on `field` focus (default `true` if `field` is set)
  252. bound: undefined,
  253. // position of the datepicker, relative to the field (default to bottom & left)
  254. // ('bottom' & 'left' keywords are not used, 'top' & 'right' are modifier on the bottom/left position)
  255. position: 'bottom left',
  256. // automatically fit in the viewport even if it means repositioning from the position option
  257. reposition: true,
  258. // the default output format for `.toString()` and `field` value
  259. format: 'DD.MM.YYYY',
  260. // the initial date to view when first opened
  261. defaultDate: null,
  262. // make the `defaultDate` the initial selected value
  263. setDefaultDate: false,
  264. // first day of week (0: Sunday, 1: Monday etc)
  265. firstDay: 0,
  266. // the minimum/earliest date that can be selected
  267. minDate: null,
  268. // the maximum/latest date that can be selected
  269. maxDate: null,
  270. // number of years either side, or array of upper/lower range
  271. yearRange: 10,
  272. // show week numbers at head of row
  273. showWeekNumber: false,
  274. // used internally (don't config outside)
  275. minYear: 0,
  276. maxYear: 9999,
  277. minMonth: undefined,
  278. maxMonth: undefined,
  279. startRange: null,
  280. endRange: null,
  281. isRTL: false,
  282. // Additional text to append to the year in the calendar title
  283. yearSuffix: '',
  284. // Render the month after year in the calendar title
  285. showMonthAfterYear: false,
  286. // how many months are visible
  287. numberOfMonths: 1,
  288. // when numberOfMonths is used, this will help you to choose where the main calendar will be (default `left`, can be set to `right`)
  289. // only used for the first display or when a selected date is not visible
  290. mainCalendar: 'left',
  291. // Specify a DOM element to render the calendar in
  292. container: undefined,
  293. // internationalization
  294. i18n: clLangs.en,
  295. // Theme Classname
  296. theme: null,
  297. // callback function
  298. onSelect: null,
  299. onOpen: null,
  300. onClose: null,
  301. onDraw: null
  302. },
  303. /**
  304. * templating functions to abstract HTML rendering
  305. */
  306. renderDayName = function(opts, day, abbr)
  307. {
  308. day += opts.firstDay;
  309. while (day >= 7) {
  310. day -= 7;
  311. }
  312. return abbr ? opts.i18n.weekdaysShort[day] : opts.i18n.weekdays[day];
  313. },
  314. renderDay = function(opts)
  315. {
  316. if (opts.isEmpty) {
  317. return '<td class="is-empty"></td>';
  318. }
  319. var arr = [];
  320. if (opts.isDisabled) {
  321. arr.push('is-disabled');
  322. }
  323. if (opts.isToday) {
  324. arr.push('is-today');
  325. }
  326. if (opts.isSelected) {
  327. arr.push('is-selected');
  328. }
  329. if (opts.isInRange) {
  330. arr.push('is-inrange');
  331. }
  332. if (opts.isStartRange) {
  333. arr.push('is-startrange');
  334. }
  335. if (opts.isEndRange) {
  336. arr.push('is-endrange');
  337. }
  338. return '<td data-day="' + opts.day + '" class="' + arr.join(' ') + '">' +
  339. '<button class="pika-button pika-day" type="button" ' +
  340. 'data-pika-year="' + opts.year + '" data-pika-month="' + opts.month + '" data-pika-day="' + opts.day + '">' +
  341. opts.day +
  342. '</button>' +
  343. '</td>';
  344. },
  345. renderWeek = function (d, m, y) {
  346. // Lifted from http://javascript.about.com/library/blweekyear.htm, lightly modified.
  347. var onejan = new Date(y, 0, 1),
  348. weekNum = Math.ceil((((new Date(y, m, d) - onejan) / 86400000) + onejan.getDay()+1)/7);
  349. return '<td class="pika-week">' + weekNum + '</td>';
  350. },
  351. renderRow = function(days, isRTL)
  352. {
  353. return '<tr>' + (isRTL ? days.reverse() : days).join('') + '</tr>';
  354. },
  355. renderBody = function(rows)
  356. {
  357. return '<tbody>' + rows.join('') + '</tbody>';
  358. },
  359. renderHead = function(opts)
  360. {
  361. var i, arr = [];
  362. if (opts.showWeekNumber) {
  363. arr.push('<th></th>');
  364. }
  365. for (i = 0; i < 7; i++) {
  366. arr.push('<th scope="col"><abbr title="' + renderDayName(opts, i) + '">' + renderDayName(opts, i, true) + '</abbr></th>');
  367. }
  368. return '<thead>' + (opts.isRTL ? arr.reverse() : arr).join('') + '</thead>';
  369. },
  370. renderTitle = function(instance, c, year, month, refYear)
  371. {
  372. var i, j, arr,
  373. opts = instance._o,
  374. isMinYear = year === opts.minYear,
  375. isMaxYear = year === opts.maxYear,
  376. html = '<div class="pika-title">',
  377. monthHtml,
  378. yearHtml,
  379. prev = true,
  380. next = true;
  381. for (arr = [], i = 0; i < 12; i++) {
  382. arr.push('<option value="' + (year === refYear ? i - c : 12 + i - c) + '"' +
  383. (i === month ? ' selected': '') +
  384. ((isMinYear && i < opts.minMonth) || (isMaxYear && i > opts.maxMonth) ? 'disabled' : '') + '>' +
  385. opts.i18n.months[i] + '</option>');
  386. }
  387. monthHtml = '<div class="pika-label">' + opts.i18n.months[month] + '<select class="pika-select pika-select-month" tabindex="-1">' + arr.join('') + '</select></div>';
  388. if (isArray(opts.yearRange)) {
  389. i = opts.yearRange[0];
  390. j = opts.yearRange[1] + 1;
  391. } else {
  392. i = year - opts.yearRange;
  393. j = 1 + year + opts.yearRange;
  394. }
  395. for (arr = []; i < j && i <= opts.maxYear; i++) {
  396. if (i >= opts.minYear) {
  397. arr.push('<option value="' + i + '"' + (i === year ? ' selected': '') + '>' + (i) + '</option>');
  398. }
  399. }
  400. yearHtml = '<div class="pika-label">' + year + opts.yearSuffix + '<select class="pika-select pika-select-year" tabindex="-1">' + arr.join('') + '</select></div>';
  401. if (opts.showMonthAfterYear) {
  402. html += yearHtml + monthHtml;
  403. } else {
  404. html += monthHtml + yearHtml;
  405. }
  406. if (isMinYear && (month === 0 || opts.minMonth >= month)) {
  407. prev = false;
  408. }
  409. if (isMaxYear && (month === 11 || opts.maxMonth <= month)) {
  410. next = false;
  411. }
  412. if (c === 0) {
  413. html += '<button class="pika-prev' + (prev ? '' : ' is-disabled') + '" type="button">' + opts.i18n.previousMonth + '</button>';
  414. }
  415. if (c === (instance._o.numberOfMonths - 1) ) {
  416. html += '<button class="pika-next' + (next ? '' : ' is-disabled') + '" type="button">' + opts.i18n.nextMonth + '</button>';
  417. }
  418. return html += '</div>';
  419. },
  420. renderTable = function(opts, data)
  421. {
  422. return '<table cellpadding="0" cellspacing="0" class="pika-table">' + renderHead(opts) + renderBody(data) + '</table>';
  423. },
  424. /**
  425. * Pikaday constructor
  426. */
  427. Pikaday = function(options)
  428. {
  429. var self = this,
  430. opts = self.config(options);
  431. self._onMouseDown = function(e)
  432. {
  433. if (!self._v) {
  434. return;
  435. }
  436. e = e || window.event;
  437. var target = e.target || e.srcElement;
  438. console.log(target);
  439. if (!target) {
  440. return;
  441. }
  442. if (!hasClass(target.parentNode, 'is-disabled')) {
  443. if (hasClass(target, 'pika-button') && !hasClass(target, 'is-empty')) {
  444. self.setDate(new Date(target.getAttribute('data-pika-year'), target.getAttribute('data-pika-month'), target.getAttribute('data-pika-day')));
  445. if (opts.bound) {
  446. sto(function() {
  447. self.hide();
  448. if (opts.field) {
  449. opts.field.blur();
  450. }
  451. }, 100);
  452. }
  453. }
  454. else if (hasClass(target, 'pika-prev')) {
  455. self.prevMonth();
  456. }
  457. else if (hasClass(target, 'pika-next')) {
  458. self.nextMonth();
  459. }
  460. }
  461. if (!hasClass(target, 'pika-select')) {
  462. // if this is touch event prevent mouse events emulation
  463. if (e.preventDefault) {
  464. e.preventDefault();
  465. } else {
  466. e.returnValue = false;
  467. return false;
  468. }
  469. } else {
  470. self._c = true;
  471. }
  472. };
  473. self._onChange = function(e)
  474. {
  475. e = e || window.event;
  476. var target = e.target || e.srcElement;
  477. if (!target) {
  478. return;
  479. }
  480. if (hasClass(target, 'pika-select-month')) {
  481. self.gotoMonth(target.value);
  482. }
  483. else if (hasClass(target, 'pika-select-year')) {
  484. self.gotoYear(target.value);
  485. }
  486. };
  487. self._onInputChange = function(e)
  488. {
  489. var date;
  490. if (e.firedBy === self) {
  491. return;
  492. }
  493. if (hasMoment) {
  494. date = moment(opts.field.value, opts.format);
  495. date = (date && date.isValid()) ? date.toDate() : null;
  496. }
  497. else {
  498. // date = parseDateFromInput(opts.field.value);
  499. date = parser(opts.field.value, opts.format);
  500. }
  501. if (isDate(date)) {
  502. self.setDate(date);
  503. }else {
  504. self.setDate(null);
  505. }
  506. if (!self._v) {
  507. self.show();
  508. }
  509. };
  510. self._onInputFocus = function()
  511. {
  512. self.show();
  513. };
  514. self._onInputClick = function()
  515. {
  516. self.show();
  517. };
  518. self._onInputBlur = function()
  519. {
  520. // IE allows pika div to gain focus; catch blur the input field
  521. var pEl = document.activeElement;
  522. do {
  523. if (hasClass(pEl, 'pika-single')) {
  524. return;
  525. }
  526. }
  527. while ((pEl = pEl.parentNode));
  528. if (!self._c) {
  529. self._b = sto(function() {
  530. self.hide();
  531. }, 50);
  532. }
  533. self._c = false;
  534. };
  535. self._onClick = function(e)
  536. {
  537. e = e || window.event;
  538. var target = e.target || e.srcElement,
  539. pEl = target;
  540. if (!target) {
  541. return;
  542. }
  543. if (!hasEventListeners && hasClass(target, 'pika-select')) {
  544. if (!target.onchange) {
  545. target.setAttribute('onchange', 'return;');
  546. addEvent(target, 'change', self._onChange);
  547. }
  548. }
  549. do {
  550. if (hasClass(pEl, 'pika-single') || pEl === opts.trigger) {
  551. return;
  552. }
  553. }
  554. while ((pEl = pEl.parentNode));
  555. if (self._v && target !== opts.trigger && pEl !== opts.trigger) {
  556. self.hide();
  557. }
  558. };
  559. self.el = document.createElement('div');
  560. self.el.className = 'pika-single' + (opts.isRTL ? ' is-rtl' : '') + (opts.theme ? ' ' + opts.theme : '');
  561. addEvent(self.el, 'mousedown', self._onMouseDown, true);
  562. addEvent(self.el, 'touchend', self._onMouseDown, true);
  563. addEvent(self.el, 'change', self._onChange);
  564. if (opts.field) {
  565. if (opts.container) {
  566. opts.container.appendChild(self.el);
  567. } else if (opts.bound) {
  568. document.body.appendChild(self.el);
  569. } else {
  570. opts.field.parentNode.insertBefore(self.el, opts.field.nextSibling);
  571. }
  572. addEvent(opts.field, 'change', self._onInputChange);
  573. if (!opts.defaultDate) {
  574. if (hasMoment && opts.field.value) {
  575. opts.defaultDate = moment(opts.field.value, opts.format).toDate();
  576. } else {
  577. opts.defaultDate = new Date(Date.parse(opts.field.value));
  578. }
  579. opts.setDefaultDate = true;
  580. }
  581. }
  582. var defDate = opts.defaultDate;
  583. if (isDate(defDate)) {
  584. if (opts.setDefaultDate) {
  585. self.setDate(defDate, true);
  586. } else {
  587. self.gotoDate(defDate);
  588. }
  589. } else {
  590. self.gotoDate(new Date());
  591. }
  592. if (opts.bound) {
  593. this.hide();
  594. self.el.className += ' is-bound';
  595. addEvent(opts.trigger, 'click', self._onInputClick);
  596. addEvent(opts.trigger, 'focus', self._onInputFocus);
  597. addEvent(opts.trigger, 'blur', self._onInputBlur);
  598. } else {
  599. this.show();
  600. }
  601. };
  602. /**
  603. * public Pikaday API
  604. */
  605. Pikaday.prototype = {
  606. /**
  607. * configure functionality
  608. */
  609. config: function(options)
  610. {
  611. if (!this._o) {
  612. this._o = extend({}, defaults, true);
  613. }
  614. var opts = extend(this._o, options, true);
  615. opts.isRTL = !!opts.isRTL;
  616. opts.field = (opts.field && opts.field.nodeName) ? opts.field : null;
  617. opts.theme = (typeof opts.theme) === 'string' && opts.theme ? opts.theme : null;
  618. opts.bound = !!(opts.bound !== undefined ? opts.field && opts.bound : opts.field);
  619. opts.trigger = (opts.trigger && opts.trigger.nodeName) ? opts.trigger : opts.field;
  620. opts.disableWeekends = !!opts.disableWeekends;
  621. opts.disableDayFn = (typeof opts.disableDayFn) === 'function' ? opts.disableDayFn : null;
  622. var nom = parseInt(opts.numberOfMonths, 10) || 1;
  623. opts.numberOfMonths = nom > 4 ? 4 : nom;
  624. if (!isDate(opts.minDate)) {
  625. opts.minDate = false;
  626. }
  627. if (!isDate(opts.maxDate)) {
  628. opts.maxDate = false;
  629. }
  630. if ((opts.minDate && opts.maxDate) && opts.maxDate < opts.minDate) {
  631. opts.maxDate = opts.minDate = false;
  632. }
  633. if (opts.minDate) {
  634. this.setMinDate(opts.minDate);
  635. }
  636. if (opts.maxDate) {
  637. setToStartOfDay(opts.maxDate);
  638. opts.maxYear = opts.maxDate.getFullYear();
  639. opts.maxMonth = opts.maxDate.getMonth();
  640. }
  641. if (isArray(opts.yearRange)) {
  642. var fallback = new Date().getFullYear() - 10;
  643. opts.yearRange[0] = parseInt(opts.yearRange[0], 10) || fallback;
  644. opts.yearRange[1] = parseInt(opts.yearRange[1], 10) || fallback;
  645. } else {
  646. opts.yearRange = Math.abs(parseInt(opts.yearRange, 10)) || defaults.yearRange;
  647. if (opts.yearRange > 100) {
  648. opts.yearRange = 100;
  649. }
  650. }
  651. return opts;
  652. },
  653. /**
  654. * return a formatted string of the current selection (using Moment.js if available or default formatter)
  655. */
  656. toString: function(format) {
  657. return !isDate(this._d) ? '' : (hasMoment) ? moment(this._d).format(format || this._o.format) : formatter(this._d,this._o.format);
  658. },
  659. /**
  660. * return a Moment.js object of the current selection (if available)
  661. */
  662. getMoment: function()
  663. {
  664. return hasMoment ? moment(this._d) : null;
  665. },
  666. /**
  667. * set the current selection from a Moment.js object (if available)
  668. */
  669. setMoment: function(date, preventOnSelect)
  670. {
  671. if (hasMoment && moment.isMoment(date)) {
  672. this.setDate(date.toDate(), preventOnSelect);
  673. }
  674. },
  675. /**
  676. * return a Date object of the current selection
  677. */
  678. getDate: function()
  679. {
  680. return isDate(this._d) ? new Date(this._d.getTime()) : null;
  681. },
  682. /**
  683. * set the current selection
  684. */
  685. setDate: function(date, preventOnSelect)
  686. {
  687. if (!date) {
  688. this._d = null;
  689. if (this._o.field) {
  690. this._o.field.value = '';
  691. fireEvent(this._o.field, 'change', { firedBy: this });
  692. }
  693. return this.draw();
  694. }
  695. if (typeof date === 'string') {
  696. date = new Date(Date.parse(date));
  697. }
  698. if (!isDate(date)) {
  699. return;
  700. }
  701. var min = this._o.minDate,
  702. max = this._o.maxDate;
  703. if (isDate(min) && date < min) {
  704. date = min;
  705. } else if (isDate(max) && date > max) {
  706. date = max;
  707. }
  708. this._d = new Date(date.getTime());
  709. setToStartOfDay(this._d);
  710. this.gotoDate(this._d);
  711. if (this._o.field) {
  712. this._o.field.value = this.toString();
  713. fireEvent(this._o.field, 'change', { firedBy: this });
  714. }
  715. if (!preventOnSelect && typeof this._o.onSelect === 'function') {
  716. this._o.onSelect.call(this, this.getDate());
  717. }
  718. },
  719. /**
  720. * change view to a specific date
  721. */
  722. gotoDate: function(date)
  723. {
  724. var newCalendar = true;
  725. if (!isDate(date)) {
  726. return;
  727. }
  728. if (this.calendars) {
  729. var firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1),
  730. lastVisibleDate = new Date(this.calendars[this.calendars.length-1].year, this.calendars[this.calendars.length-1].month, 1),
  731. visibleDate = date.getTime();
  732. // get the end of the month
  733. lastVisibleDate.setMonth(lastVisibleDate.getMonth()+1);
  734. lastVisibleDate.setDate(lastVisibleDate.getDate()-1);
  735. newCalendar = (visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate);
  736. }
  737. if (newCalendar) {
  738. this.calendars = [{
  739. month: date.getMonth(),
  740. year: date.getFullYear()
  741. }];
  742. if (this._o.mainCalendar === 'right') {
  743. this.calendars[0].month += 1 - this._o.numberOfMonths;
  744. }
  745. }
  746. this.adjustCalendars();
  747. },
  748. adjustCalendars: function() {
  749. this.calendars[0] = adjustCalendar(this.calendars[0]);
  750. for (var c = 1; c < this._o.numberOfMonths; c++) {
  751. this.calendars[c] = adjustCalendar({
  752. month: this.calendars[0].month + c,
  753. year: this.calendars[0].year
  754. });
  755. }
  756. this.draw();
  757. },
  758. gotoToday: function()
  759. {
  760. this.gotoDate(new Date());
  761. },
  762. /**
  763. * change view to a specific month (zero-index, e.g. 0: January)
  764. */
  765. gotoMonth: function(month)
  766. {
  767. if (!isNaN(month)) {
  768. this.calendars[0].month = parseInt(month, 10);
  769. this.adjustCalendars();
  770. }
  771. },
  772. nextMonth: function()
  773. {
  774. this.calendars[0].month++;
  775. this.adjustCalendars();
  776. },
  777. prevMonth: function()
  778. {
  779. this.calendars[0].month--;
  780. this.adjustCalendars();
  781. },
  782. /**
  783. * change view to a specific full year (e.g. "2012")
  784. */
  785. gotoYear: function(year)
  786. {
  787. if (!isNaN(year)) {
  788. this.calendars[0].year = parseInt(year, 10);
  789. this.adjustCalendars();
  790. }
  791. },
  792. /**
  793. * change the minDate
  794. */
  795. setMinDate: function(value)
  796. {
  797. setToStartOfDay(value);
  798. this._o.minDate = value;
  799. this._o.minYear = value.getFullYear();
  800. this._o.minMonth = value.getMonth();
  801. },
  802. /**
  803. * change the maxDate
  804. */
  805. setMaxDate: function(value)
  806. {
  807. this._o.maxDate = value;
  808. },
  809. setStartRange: function(value)
  810. {
  811. this._o.startRange = value;
  812. },
  813. setEndRange: function(value)
  814. {
  815. this._o.endRange = value;
  816. },
  817. /**
  818. * refresh the HTML
  819. */
  820. draw: function(force)
  821. {
  822. if (!this._v && !force) {
  823. return;
  824. }
  825. var opts = this._o,
  826. minYear = opts.minYear,
  827. maxYear = opts.maxYear,
  828. minMonth = opts.minMonth,
  829. maxMonth = opts.maxMonth,
  830. html = '';
  831. if (this._y <= minYear) {
  832. this._y = minYear;
  833. if (!isNaN(minMonth) && this._m < minMonth) {
  834. this._m = minMonth;
  835. }
  836. }
  837. if (this._y >= maxYear) {
  838. this._y = maxYear;
  839. if (!isNaN(maxMonth) && this._m > maxMonth) {
  840. this._m = maxMonth;
  841. }
  842. }
  843. for (var c = 0; c < opts.numberOfMonths; c++) {
  844. html += '<div class="pika-lendar">' + renderTitle(this, c, this.calendars[c].year, this.calendars[c].month, this.calendars[0].year) + this.render(this.calendars[c].year, this.calendars[c].month) + '</div>';
  845. }
  846. this.el.innerHTML = html;
  847. if (opts.bound) {
  848. if(opts.field.type !== 'hidden') {
  849. sto(function() {
  850. opts.trigger.focus();
  851. }, 1);
  852. }
  853. }
  854. if (typeof this._o.onDraw === 'function') {
  855. var self = this;
  856. sto(function() {
  857. self._o.onDraw.call(self);
  858. }, 0);
  859. }
  860. },
  861. adjustPosition: function()
  862. {
  863. var field, pEl, width, height, viewportWidth, viewportHeight, scrollTop, left, top, clientRect;
  864. if (this._o.container) return;
  865. this.el.style.position = 'absolute';
  866. field = this._o.trigger;
  867. pEl = field;
  868. width = this.el.offsetWidth;
  869. height = this.el.offsetHeight;
  870. viewportWidth = window.innerWidth || document.documentElement.clientWidth;
  871. viewportHeight = window.innerHeight || document.documentElement.clientHeight;
  872. scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
  873. if (typeof field.getBoundingClientRect === 'function') {
  874. clientRect = field.getBoundingClientRect();
  875. left = clientRect.left + window.pageXOffset;
  876. top = clientRect.bottom + window.pageYOffset;
  877. } else {
  878. left = pEl.offsetLeft;
  879. top = pEl.offsetTop + pEl.offsetHeight;
  880. while((pEl = pEl.offsetParent)) {
  881. left += pEl.offsetLeft;
  882. top += pEl.offsetTop;
  883. }
  884. }
  885. // default position is bottom & left
  886. if ((this._o.reposition && left + width > viewportWidth) ||
  887. (
  888. this._o.position.indexOf('right') > -1 &&
  889. left - width + field.offsetWidth > 0
  890. )
  891. ) {
  892. left = left - width + field.offsetWidth;
  893. }
  894. if ((this._o.reposition && top + height > viewportHeight + scrollTop) ||
  895. (
  896. this._o.position.indexOf('top') > -1 &&
  897. top - height - field.offsetHeight > 0
  898. )
  899. ) {
  900. top = top - height - field.offsetHeight;
  901. }
  902. this.el.style.left = left + 'px';
  903. this.el.style.top = top + 'px';
  904. },
  905. /**
  906. * render HTML for a particular month
  907. */
  908. render: function(year, month)
  909. {
  910. var opts = this._o,
  911. now = new Date(),
  912. days = getDaysInMonth(year, month),
  913. before = new Date(year, month, 1).getDay(),
  914. data = [],
  915. row = [];
  916. setToStartOfDay(now);
  917. if (opts.firstDay > 0) {
  918. before -= opts.firstDay;
  919. if (before < 0) {
  920. before += 7;
  921. }
  922. }
  923. var cells = days + before,
  924. after = cells;
  925. while(after > 7) {
  926. after -= 7;
  927. }
  928. cells += 7 - after;
  929. for (var i = 0, r = 0; i < cells; i++)
  930. {
  931. var day = new Date(year, month, 1 + (i - before)),
  932. isSelected = isDate(this._d) ? compareDates(day, this._d) : false,
  933. isToday = compareDates(day, now),
  934. isEmpty = i < before || i >= (days + before),
  935. isStartRange = opts.startRange && compareDates(opts.startRange, day),
  936. isEndRange = opts.endRange && compareDates(opts.endRange, day),
  937. isInRange = opts.startRange && opts.endRange && opts.startRange < day && day < opts.endRange,
  938. isDisabled = (opts.minDate && day < opts.minDate) ||
  939. (opts.maxDate && day > opts.maxDate) ||
  940. (opts.disableWeekends && isWeekend(day)) ||
  941. (opts.disableDayFn && opts.disableDayFn(day)),
  942. dayConfig = {
  943. day: 1 + (i - before),
  944. month: month,
  945. year: year,
  946. isSelected: isSelected,
  947. isToday: isToday,
  948. isDisabled: isDisabled,
  949. isEmpty: isEmpty,
  950. isStartRange: isStartRange,
  951. isEndRange: isEndRange,
  952. isInRange: isInRange
  953. };
  954. row.push(renderDay(dayConfig));
  955. if (++r === 7) {
  956. if (opts.showWeekNumber) {
  957. row.unshift(renderWeek(i - before, month, year));
  958. }
  959. data.push(renderRow(row, opts.isRTL));
  960. row = [];
  961. r = 0;
  962. }
  963. }
  964. return renderTable(opts, data);
  965. },
  966. isVisible: function()
  967. {
  968. return this._v;
  969. },
  970. show: function()
  971. {
  972. if (!this._v) {
  973. removeClass(this.el, 'is-hidden');
  974. this._v = true;
  975. this.draw();
  976. if (this._o.bound) {
  977. addEvent(document, 'click', this._onClick);
  978. this.adjustPosition();
  979. }
  980. if (typeof this._o.onOpen === 'function') {
  981. this._o.onOpen.call(this);
  982. }
  983. }
  984. },
  985. hide: function()
  986. {
  987. var v = this._v;
  988. if (v !== false) {
  989. if (this._o.bound) {
  990. removeEvent(document, 'click', this._onClick);
  991. }
  992. this.el.style.position = 'static'; // reset
  993. this.el.style.left = 'auto';
  994. this.el.style.top = 'auto';
  995. addClass(this.el, 'is-hidden');
  996. this._v = false;
  997. if (v !== undefined && typeof this._o.onClose === 'function') {
  998. this._o.onClose.call(this);
  999. }
  1000. }
  1001. },
  1002. /**
  1003. * GAME OVER
  1004. */
  1005. destroy: function()
  1006. {
  1007. this.hide();
  1008. removeEvent(this.el, 'mousedown', this._onMouseDown, true);
  1009. removeEvent(this.el, 'touchend', this._onMouseDown, true);
  1010. removeEvent(this.el, 'change', this._onChange);
  1011. if (this._o.field) {
  1012. removeEvent(this._o.field, 'change', this._onInputChange);
  1013. if (this._o.bound) {
  1014. removeEvent(this._o.trigger, 'click', this._onInputClick);
  1015. removeEvent(this._o.trigger, 'focus', this._onInputFocus);
  1016. removeEvent(this._o.trigger, 'blur', this._onInputBlur);
  1017. }
  1018. }
  1019. if (this.el.parentNode) {
  1020. this.el.parentNode.removeChild(this.el);
  1021. }
  1022. }
  1023. };
  1024. return Pikaday;
  1025. }));