DateTimeShortcuts.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /*global Calendar, findPosX, findPosY, getStyle, get_format, gettext, gettext_noop, interpolate, ngettext, quickElement*/
  2. // Inserts shortcut buttons after all of the following:
  3. // <input type="text" class="vDateField">
  4. // <input type="text" class="vTimeField">
  5. (function() {
  6. 'use strict';
  7. var DateTimeShortcuts = {
  8. calendars: [],
  9. calendarInputs: [],
  10. clockInputs: [],
  11. clockHours: {
  12. default_: [
  13. [gettext_noop('Now'), -1],
  14. [gettext_noop('Midnight'), 0],
  15. [gettext_noop('6 a.m.'), 6],
  16. [gettext_noop('Noon'), 12],
  17. [gettext_noop('6 p.m.'), 18]
  18. ]
  19. },
  20. dismissClockFunc: [],
  21. dismissCalendarFunc: [],
  22. calendarDivName1: 'calendarbox', // name of calendar <div> that gets toggled
  23. calendarDivName2: 'calendarin', // name of <div> that contains calendar
  24. calendarLinkName: 'calendarlink',// name of the link that is used to toggle
  25. clockDivName: 'clockbox', // name of clock <div> that gets toggled
  26. clockLinkName: 'clocklink', // name of the link that is used to toggle
  27. shortCutsClass: 'datetimeshortcuts', // class of the clock and cal shortcuts
  28. timezoneWarningClass: 'timezonewarning', // class of the warning for timezone mismatch
  29. timezoneOffset: 0,
  30. init: function() {
  31. var body = document.getElementsByTagName('body')[0];
  32. var serverOffset = body.getAttribute('data-admin-utc-offset');
  33. if (serverOffset) {
  34. var localOffset = new Date().getTimezoneOffset() * -60;
  35. DateTimeShortcuts.timezoneOffset = localOffset - serverOffset;
  36. }
  37. var inputs = document.getElementsByTagName('input');
  38. for (var i = 0; i < inputs.length; i++) {
  39. var inp = inputs[i];
  40. if (inp.getAttribute('type') === 'text' && inp.className.match(/vTimeField/)) {
  41. DateTimeShortcuts.addClock(inp);
  42. DateTimeShortcuts.addTimezoneWarning(inp);
  43. }
  44. else if (inp.getAttribute('type') === 'text' && inp.className.match(/vDateField/)) {
  45. DateTimeShortcuts.addCalendar(inp);
  46. DateTimeShortcuts.addTimezoneWarning(inp);
  47. }
  48. }
  49. },
  50. // Return the current time while accounting for the server timezone.
  51. now: function() {
  52. var body = document.getElementsByTagName('body')[0];
  53. var serverOffset = body.getAttribute('data-admin-utc-offset');
  54. if (serverOffset) {
  55. var localNow = new Date();
  56. var localOffset = localNow.getTimezoneOffset() * -60;
  57. localNow.setTime(localNow.getTime() + 1000 * (serverOffset - localOffset));
  58. return localNow;
  59. } else {
  60. return new Date();
  61. }
  62. },
  63. // Add a warning when the time zone in the browser and backend do not match.
  64. addTimezoneWarning: function(inp) {
  65. var $ = django.jQuery;
  66. var warningClass = DateTimeShortcuts.timezoneWarningClass;
  67. var timezoneOffset = DateTimeShortcuts.timezoneOffset / 3600;
  68. // Only warn if there is a time zone mismatch.
  69. if (!timezoneOffset) {
  70. return;
  71. }
  72. // Check if warning is already there.
  73. if ($(inp).siblings('.' + warningClass).length) {
  74. return;
  75. }
  76. var message;
  77. if (timezoneOffset > 0) {
  78. message = ngettext(
  79. 'Note: You are %s hour ahead of server time.',
  80. 'Note: You are %s hours ahead of server time.',
  81. timezoneOffset
  82. );
  83. }
  84. else {
  85. timezoneOffset *= -1;
  86. message = ngettext(
  87. 'Note: You are %s hour behind server time.',
  88. 'Note: You are %s hours behind server time.',
  89. timezoneOffset
  90. );
  91. }
  92. message = interpolate(message, [timezoneOffset]);
  93. var $warning = $('<span>');
  94. $warning.attr('class', warningClass);
  95. $warning.text(message);
  96. $(inp).parent()
  97. .append($('<br>'))
  98. .append($warning);
  99. },
  100. // Add clock widget to a given field
  101. addClock: function(inp) {
  102. var num = DateTimeShortcuts.clockInputs.length;
  103. DateTimeShortcuts.clockInputs[num] = inp;
  104. DateTimeShortcuts.dismissClockFunc[num] = function() { DateTimeShortcuts.dismissClock(num); return true; };
  105. // Shortcut links (clock icon and "Now" link)
  106. var shortcuts_span = document.createElement('span');
  107. shortcuts_span.className = DateTimeShortcuts.shortCutsClass;
  108. inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);
  109. var now_link = document.createElement('a');
  110. now_link.setAttribute('href', "#");
  111. now_link.appendChild(document.createTextNode(gettext('Now')));
  112. now_link.addEventListener('click', function(e) {
  113. e.preventDefault();
  114. DateTimeShortcuts.handleClockQuicklink(num, -1);
  115. });
  116. var clock_link = document.createElement('a');
  117. clock_link.setAttribute('href', '#');
  118. clock_link.id = DateTimeShortcuts.clockLinkName + num;
  119. clock_link.addEventListener('click', function(e) {
  120. e.preventDefault();
  121. // avoid triggering the document click handler to dismiss the clock
  122. e.stopPropagation();
  123. DateTimeShortcuts.openClock(num);
  124. });
  125. quickElement(
  126. 'span', clock_link, '',
  127. 'class', 'clock-icon',
  128. 'title', gettext('Choose a Time')
  129. );
  130. shortcuts_span.appendChild(document.createTextNode('\u00A0'));
  131. shortcuts_span.appendChild(now_link);
  132. shortcuts_span.appendChild(document.createTextNode('\u00A0|\u00A0'));
  133. shortcuts_span.appendChild(clock_link);
  134. // Create clock link div
  135. //
  136. // Markup looks like:
  137. // <div id="clockbox1" class="clockbox module">
  138. // <h2>Choose a time</h2>
  139. // <ul class="timelist">
  140. // <li><a href="#">Now</a></li>
  141. // <li><a href="#">Midnight</a></li>
  142. // <li><a href="#">6 a.m.</a></li>
  143. // <li><a href="#">Noon</a></li>
  144. // <li><a href="#">6 p.m.</a></li>
  145. // </ul>
  146. // <p class="calendar-cancel"><a href="#">Cancel</a></p>
  147. // </div>
  148. var clock_box = document.createElement('div');
  149. clock_box.style.display = 'none';
  150. clock_box.style.position = 'absolute';
  151. clock_box.className = 'clockbox module';
  152. clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num);
  153. document.body.appendChild(clock_box);
  154. clock_box.addEventListener('click', function(e) { e.stopPropagation(); });
  155. quickElement('h2', clock_box, gettext('Choose a time'));
  156. var time_list = quickElement('ul', clock_box);
  157. time_list.className = 'timelist';
  158. // The list of choices can be overridden in JavaScript like this:
  159. // DateTimeShortcuts.clockHours.name = [['3 a.m.', 3]];
  160. // where name is the name attribute of the <input>.
  161. var name = typeof DateTimeShortcuts.clockHours[inp.name] === 'undefined' ? 'default_' : inp.name;
  162. DateTimeShortcuts.clockHours[name].forEach(function(element) {
  163. var time_link = quickElement('a', quickElement('li', time_list), gettext(element[0]), 'href', '#');
  164. time_link.addEventListener('click', function(e) {
  165. e.preventDefault();
  166. DateTimeShortcuts.handleClockQuicklink(num, element[1]);
  167. });
  168. });
  169. var cancel_p = quickElement('p', clock_box);
  170. cancel_p.className = 'calendar-cancel';
  171. var cancel_link = quickElement('a', cancel_p, gettext('Cancel'), 'href', '#');
  172. cancel_link.addEventListener('click', function(e) {
  173. e.preventDefault();
  174. DateTimeShortcuts.dismissClock(num);
  175. });
  176. document.addEventListener('keyup', function(event) {
  177. if (event.which === 27) {
  178. // ESC key closes popup
  179. DateTimeShortcuts.dismissClock(num);
  180. event.preventDefault();
  181. }
  182. });
  183. },
  184. openClock: function(num) {
  185. var clock_box = document.getElementById(DateTimeShortcuts.clockDivName + num);
  186. var clock_link = document.getElementById(DateTimeShortcuts.clockLinkName + num);
  187. // Recalculate the clockbox position
  188. // is it left-to-right or right-to-left layout ?
  189. if (getStyle(document.body, 'direction') !== 'rtl') {
  190. clock_box.style.left = findPosX(clock_link) + 17 + 'px';
  191. }
  192. else {
  193. // since style's width is in em, it'd be tough to calculate
  194. // px value of it. let's use an estimated px for now
  195. // TODO: IE returns wrong value for findPosX when in rtl mode
  196. // (it returns as it was left aligned), needs to be fixed.
  197. clock_box.style.left = findPosX(clock_link) - 110 + 'px';
  198. }
  199. clock_box.style.top = Math.max(0, findPosY(clock_link) - 30) + 'px';
  200. // Show the clock box
  201. clock_box.style.display = 'block';
  202. document.addEventListener('click', DateTimeShortcuts.dismissClockFunc[num]);
  203. },
  204. dismissClock: function(num) {
  205. document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none';
  206. document.removeEventListener('click', DateTimeShortcuts.dismissClockFunc[num]);
  207. },
  208. handleClockQuicklink: function(num, val) {
  209. var d;
  210. if (val === -1) {
  211. d = DateTimeShortcuts.now();
  212. }
  213. else {
  214. d = new Date(1970, 1, 1, val, 0, 0, 0);
  215. }
  216. DateTimeShortcuts.clockInputs[num].value = d.strftime(get_format('TIME_INPUT_FORMATS')[0]);
  217. DateTimeShortcuts.clockInputs[num].focus();
  218. DateTimeShortcuts.dismissClock(num);
  219. },
  220. // Add calendar widget to a given field.
  221. addCalendar: function(inp) {
  222. var num = DateTimeShortcuts.calendars.length;
  223. DateTimeShortcuts.calendarInputs[num] = inp;
  224. DateTimeShortcuts.dismissCalendarFunc[num] = function() { DateTimeShortcuts.dismissCalendar(num); return true; };
  225. // Shortcut links (calendar icon and "Today" link)
  226. var shortcuts_span = document.createElement('span');
  227. shortcuts_span.className = DateTimeShortcuts.shortCutsClass;
  228. inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);
  229. var today_link = document.createElement('a');
  230. today_link.setAttribute('href', '#');
  231. today_link.appendChild(document.createTextNode(gettext('Today')));
  232. today_link.addEventListener('click', function(e) {
  233. e.preventDefault();
  234. DateTimeShortcuts.handleCalendarQuickLink(num, 0);
  235. });
  236. var cal_link = document.createElement('a');
  237. cal_link.setAttribute('href', '#');
  238. cal_link.id = DateTimeShortcuts.calendarLinkName + num;
  239. cal_link.addEventListener('click', function(e) {
  240. e.preventDefault();
  241. // avoid triggering the document click handler to dismiss the calendar
  242. e.stopPropagation();
  243. DateTimeShortcuts.openCalendar(num);
  244. });
  245. quickElement(
  246. 'span', cal_link, '',
  247. 'class', 'date-icon',
  248. 'title', gettext('Choose a Date')
  249. );
  250. shortcuts_span.appendChild(document.createTextNode('\u00A0'));
  251. shortcuts_span.appendChild(today_link);
  252. shortcuts_span.appendChild(document.createTextNode('\u00A0|\u00A0'));
  253. shortcuts_span.appendChild(cal_link);
  254. // Create calendarbox div.
  255. //
  256. // Markup looks like:
  257. //
  258. // <div id="calendarbox3" class="calendarbox module">
  259. // <h2>
  260. // <a href="#" class="link-previous">&lsaquo;</a>
  261. // <a href="#" class="link-next">&rsaquo;</a> February 2003
  262. // </h2>
  263. // <div class="calendar" id="calendarin3">
  264. // <!-- (cal) -->
  265. // </div>
  266. // <div class="calendar-shortcuts">
  267. // <a href="#">Yesterday</a> | <a href="#">Today</a> | <a href="#">Tomorrow</a>
  268. // </div>
  269. // <p class="calendar-cancel"><a href="#">Cancel</a></p>
  270. // </div>
  271. var cal_box = document.createElement('div');
  272. cal_box.style.display = 'none';
  273. cal_box.style.position = 'absolute';
  274. cal_box.className = 'calendarbox module';
  275. cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num);
  276. document.body.appendChild(cal_box);
  277. cal_box.addEventListener('click', function(e) { e.stopPropagation(); });
  278. // next-prev links
  279. var cal_nav = quickElement('div', cal_box);
  280. var cal_nav_prev = quickElement('a', cal_nav, '<', 'href', '#');
  281. cal_nav_prev.className = 'calendarnav-previous';
  282. cal_nav_prev.addEventListener('click', function(e) {
  283. e.preventDefault();
  284. DateTimeShortcuts.drawPrev(num);
  285. });
  286. var cal_nav_next = quickElement('a', cal_nav, '>', 'href', '#');
  287. cal_nav_next.className = 'calendarnav-next';
  288. cal_nav_next.addEventListener('click', function(e) {
  289. e.preventDefault();
  290. DateTimeShortcuts.drawNext(num);
  291. });
  292. // main box
  293. var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num);
  294. cal_main.className = 'calendar';
  295. DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num));
  296. DateTimeShortcuts.calendars[num].drawCurrent();
  297. // calendar shortcuts
  298. var shortcuts = quickElement('div', cal_box);
  299. shortcuts.className = 'calendar-shortcuts';
  300. var day_link = quickElement('a', shortcuts, gettext('Yesterday'), 'href', '#');
  301. day_link.addEventListener('click', function(e) {
  302. e.preventDefault();
  303. DateTimeShortcuts.handleCalendarQuickLink(num, -1);
  304. });
  305. shortcuts.appendChild(document.createTextNode('\u00A0|\u00A0'));
  306. day_link = quickElement('a', shortcuts, gettext('Today'), 'href', '#');
  307. day_link.addEventListener('click', function(e) {
  308. e.preventDefault();
  309. DateTimeShortcuts.handleCalendarQuickLink(num, 0);
  310. });
  311. shortcuts.appendChild(document.createTextNode('\u00A0|\u00A0'));
  312. day_link = quickElement('a', shortcuts, gettext('Tomorrow'), 'href', '#');
  313. day_link.addEventListener('click', function(e) {
  314. e.preventDefault();
  315. DateTimeShortcuts.handleCalendarQuickLink(num, +1);
  316. });
  317. // cancel bar
  318. var cancel_p = quickElement('p', cal_box);
  319. cancel_p.className = 'calendar-cancel';
  320. var cancel_link = quickElement('a', cancel_p, gettext('Cancel'), 'href', '#');
  321. cancel_link.addEventListener('click', function(e) {
  322. e.preventDefault();
  323. DateTimeShortcuts.dismissCalendar(num);
  324. });
  325. django.jQuery(document).on('keyup', function(event) {
  326. if (event.which === 27) {
  327. // ESC key closes popup
  328. DateTimeShortcuts.dismissCalendar(num);
  329. event.preventDefault();
  330. }
  331. });
  332. },
  333. openCalendar: function(num) {
  334. var cal_box = document.getElementById(DateTimeShortcuts.calendarDivName1 + num);
  335. var cal_link = document.getElementById(DateTimeShortcuts.calendarLinkName + num);
  336. var inp = DateTimeShortcuts.calendarInputs[num];
  337. // Determine if the current value in the input has a valid date.
  338. // If so, draw the calendar with that date's year and month.
  339. if (inp.value) {
  340. var format = get_format('DATE_INPUT_FORMATS')[0];
  341. var selected = inp.value.strptime(format);
  342. var year = selected.getUTCFullYear();
  343. var month = selected.getUTCMonth() + 1;
  344. var re = /\d{4}/;
  345. if (re.test(year.toString()) && month >= 1 && month <= 12) {
  346. DateTimeShortcuts.calendars[num].drawDate(month, year, selected);
  347. }
  348. }
  349. // Recalculate the clockbox position
  350. // is it left-to-right or right-to-left layout ?
  351. if (getStyle(document.body, 'direction') !== 'rtl') {
  352. cal_box.style.left = findPosX(cal_link) + 17 + 'px';
  353. }
  354. else {
  355. // since style's width is in em, it'd be tough to calculate
  356. // px value of it. let's use an estimated px for now
  357. // TODO: IE returns wrong value for findPosX when in rtl mode
  358. // (it returns as it was left aligned), needs to be fixed.
  359. cal_box.style.left = findPosX(cal_link) - 180 + 'px';
  360. }
  361. cal_box.style.top = Math.max(0, findPosY(cal_link) - 75) + 'px';
  362. cal_box.style.display = 'block';
  363. document.addEventListener('click', DateTimeShortcuts.dismissCalendarFunc[num]);
  364. },
  365. dismissCalendar: function(num) {
  366. document.getElementById(DateTimeShortcuts.calendarDivName1 + num).style.display = 'none';
  367. document.removeEventListener('click', DateTimeShortcuts.dismissCalendarFunc[num]);
  368. },
  369. drawPrev: function(num) {
  370. DateTimeShortcuts.calendars[num].drawPreviousMonth();
  371. },
  372. drawNext: function(num) {
  373. DateTimeShortcuts.calendars[num].drawNextMonth();
  374. },
  375. handleCalendarCallback: function(num) {
  376. var format = get_format('DATE_INPUT_FORMATS')[0];
  377. // the format needs to be escaped a little
  378. format = format.replace('\\', '\\\\');
  379. format = format.replace('\r', '\\r');
  380. format = format.replace('\n', '\\n');
  381. format = format.replace('\t', '\\t');
  382. format = format.replace("'", "\\'");
  383. return function(y, m, d) {
  384. DateTimeShortcuts.calendarInputs[num].value = new Date(y, m - 1, d).strftime(format);
  385. DateTimeShortcuts.calendarInputs[num].focus();
  386. document.getElementById(DateTimeShortcuts.calendarDivName1 + num).style.display = 'none';
  387. };
  388. },
  389. handleCalendarQuickLink: function(num, offset) {
  390. var d = DateTimeShortcuts.now();
  391. d.setDate(d.getDate() + offset);
  392. DateTimeShortcuts.calendarInputs[num].value = d.strftime(get_format('DATE_INPUT_FORMATS')[0]);
  393. DateTimeShortcuts.calendarInputs[num].focus();
  394. DateTimeShortcuts.dismissCalendar(num);
  395. }
  396. };
  397. window.addEventListener('load', DateTimeShortcuts.init);
  398. window.DateTimeShortcuts = DateTimeShortcuts;
  399. })();