Picker.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import {hasProperty, lastItemOf, isInRange, limitToRange} from '../lib/utils.js';
  2. import {today} from '../lib/date.js';
  3. import {parseHTML, showElement, hideElement, emptyChildNodes} from '../lib/dom.js';
  4. import {registerListeners} from '../lib/event.js';
  5. import pickerTemplate from './templates/pickerTemplate.js';
  6. import DaysView from './views/DaysView.js';
  7. import MonthsView from './views/MonthsView.js';
  8. import YearsView from './views/YearsView.js';
  9. import {triggerDatepickerEvent} from '../events/functions.js';
  10. import {
  11. onClickTodayBtn,
  12. onClickClearBtn,
  13. onClickViewSwitch,
  14. onClickPrevBtn,
  15. onClickNextBtn,
  16. onClickView,
  17. onClickPicker,
  18. } from '../events/pickerListeners.js';
  19. function processPickerOptions(picker, options) {
  20. if (options.title !== undefined) {
  21. if (options.title) {
  22. picker.controls.title.textContent = options.title;
  23. showElement(picker.controls.title);
  24. } else {
  25. picker.controls.title.textContent = '';
  26. hideElement(picker.controls.title);
  27. }
  28. }
  29. if (options.prevArrow) {
  30. const prevBtn = picker.controls.prevBtn;
  31. emptyChildNodes(prevBtn);
  32. options.prevArrow.forEach((node) => {
  33. prevBtn.appendChild(node.cloneNode(true));
  34. });
  35. }
  36. if (options.nextArrow) {
  37. const nextBtn = picker.controls.nextBtn;
  38. emptyChildNodes(nextBtn);
  39. options.nextArrow.forEach((node) => {
  40. nextBtn.appendChild(node.cloneNode(true));
  41. });
  42. }
  43. if (options.locale) {
  44. picker.controls.todayBtn.textContent = options.locale.today;
  45. picker.controls.clearBtn.textContent = options.locale.clear;
  46. }
  47. if (options.todayBtn !== undefined) {
  48. if (options.todayBtn) {
  49. showElement(picker.controls.todayBtn);
  50. } else {
  51. hideElement(picker.controls.todayBtn);
  52. }
  53. }
  54. if (hasProperty(options, 'minDate') || hasProperty(options, 'maxDate')) {
  55. const {minDate, maxDate} = picker.datepicker.config;
  56. picker.controls.todayBtn.disabled = !isInRange(today(), minDate, maxDate);
  57. }
  58. if (options.clearBtn !== undefined) {
  59. if (options.clearBtn) {
  60. showElement(picker.controls.clearBtn);
  61. } else {
  62. hideElement(picker.controls.clearBtn);
  63. }
  64. }
  65. }
  66. // Compute view date to reset, which will be...
  67. // - the last item of the selected dates or defaultViewDate if no selection
  68. // - limitted to minDate or maxDate if it exceeds the range
  69. function computeResetViewDate(datepicker) {
  70. const {dates, config} = datepicker;
  71. const viewDate = dates.length > 0 ? lastItemOf(dates) : config.defaultViewDate;
  72. return limitToRange(viewDate, config.minDate, config.maxDate);
  73. }
  74. // Change current view's view date
  75. function setViewDate(picker, newDate) {
  76. const oldViewDate = new Date(picker.viewDate);
  77. const newViewDate = new Date(newDate);
  78. const {id, year, first, last} = picker.currentView;
  79. const viewYear = newViewDate.getFullYear();
  80. picker.viewDate = newDate;
  81. if (viewYear !== oldViewDate.getFullYear()) {
  82. triggerDatepickerEvent(picker.datepicker, 'changeYear');
  83. }
  84. if (newViewDate.getMonth() !== oldViewDate.getMonth()) {
  85. triggerDatepickerEvent(picker.datepicker, 'changeMonth');
  86. }
  87. // return whether the new date is in different period on time from the one
  88. // displayed in the current view
  89. // when true, the view needs to be re-rendered on the next UI refresh.
  90. switch (id) {
  91. case 0:
  92. return newDate < first || newDate > last;
  93. case 1:
  94. return viewYear !== year;
  95. default:
  96. return viewYear < first || viewYear > last;
  97. }
  98. }
  99. function getTextDirection(el) {
  100. return window.getComputedStyle(el).direction;
  101. }
  102. // Class representing the picker UI
  103. export default class Picker {
  104. constructor(datepicker) {
  105. this.datepicker = datepicker;
  106. const template = pickerTemplate.replace(/%buttonClass%/g, datepicker.config.buttonClass);
  107. const element = this.element = parseHTML(template).firstChild;
  108. const [header, main, footer] = element.firstChild.children;
  109. const title = header.firstElementChild;
  110. const [prevBtn, viewSwitch, nextBtn] = header.lastElementChild.children;
  111. const [todayBtn, clearBtn] = footer.firstChild.children;
  112. const controls = {
  113. title,
  114. prevBtn,
  115. viewSwitch,
  116. nextBtn,
  117. todayBtn,
  118. clearBtn,
  119. };
  120. this.main = main;
  121. this.controls = controls;
  122. const elementClass = datepicker.inline ? 'inline' : 'dropdown';
  123. element.classList.add(`datepicker-${elementClass}`);
  124. processPickerOptions(this, datepicker.config);
  125. this.viewDate = computeResetViewDate(datepicker);
  126. // set up event listeners
  127. registerListeners(datepicker, [
  128. [element, 'click', onClickPicker.bind(null, datepicker), {capture: true}],
  129. [main, 'click', onClickView.bind(null, datepicker)],
  130. [controls.viewSwitch, 'click', onClickViewSwitch.bind(null, datepicker)],
  131. [controls.prevBtn, 'click', onClickPrevBtn.bind(null, datepicker)],
  132. [controls.nextBtn, 'click', onClickNextBtn.bind(null, datepicker)],
  133. [controls.todayBtn, 'click', onClickTodayBtn.bind(null, datepicker)],
  134. [controls.clearBtn, 'click', onClickClearBtn.bind(null, datepicker)],
  135. ]);
  136. // set up views
  137. this.views = [
  138. new DaysView(this),
  139. new MonthsView(this),
  140. new YearsView(this, {id: 2, name: 'years', cellClass: 'year', step: 1}),
  141. new YearsView(this, {id: 3, name: 'decades', cellClass: 'decade', step: 10}),
  142. ];
  143. this.currentView = this.views[datepicker.config.startView];
  144. this.currentView.render();
  145. this.main.appendChild(this.currentView.element);
  146. datepicker.config.container.appendChild(this.element);
  147. }
  148. setOptions(options) {
  149. processPickerOptions(this, options);
  150. this.views.forEach((view) => {
  151. view.init(options, false);
  152. });
  153. this.currentView.render();
  154. }
  155. detach() {
  156. this.datepicker.config.container.removeChild(this.element);
  157. }
  158. show() {
  159. if (this.active) {
  160. return;
  161. }
  162. this.element.classList.add('active');
  163. this.active = true;
  164. const datepicker = this.datepicker;
  165. if (!datepicker.inline) {
  166. // ensure picker's direction matches input's
  167. const inputDirection = getTextDirection(datepicker.inputField);
  168. if (inputDirection !== getTextDirection(datepicker.config.container)) {
  169. this.element.dir = inputDirection;
  170. } else if (this.element.dir) {
  171. this.element.removeAttribute('dir');
  172. }
  173. this.place();
  174. if (datepicker.config.disableTouchKeyboard) {
  175. datepicker.inputField.blur();
  176. }
  177. }
  178. triggerDatepickerEvent(datepicker, 'show');
  179. }
  180. hide() {
  181. if (!this.active) {
  182. return;
  183. }
  184. this.datepicker.exitEditMode();
  185. this.element.classList.remove('active');
  186. this.active = false;
  187. triggerDatepickerEvent(this.datepicker, 'hide');
  188. }
  189. place() {
  190. const {classList, style} = this.element;
  191. const {config, inputField} = this.datepicker;
  192. const container = config.container;
  193. const {
  194. width: calendarWidth,
  195. height: calendarHeight,
  196. } = this.element.getBoundingClientRect();
  197. const {
  198. left: containerLeft,
  199. top: containerTop,
  200. width: containerWidth,
  201. } = container.getBoundingClientRect();
  202. const {
  203. left: inputLeft,
  204. top: inputTop,
  205. width: inputWidth,
  206. height: inputHeight
  207. } = inputField.getBoundingClientRect();
  208. let {x: orientX, y: orientY} = config.orientation;
  209. let scrollTop;
  210. let left;
  211. let top;
  212. if (container === document.body) {
  213. scrollTop = window.scrollY;
  214. left = inputLeft + window.scrollX;
  215. top = inputTop + scrollTop;
  216. } else {
  217. scrollTop = container.scrollTop;
  218. left = inputLeft - containerLeft;
  219. top = inputTop - containerTop + scrollTop;
  220. }
  221. if (orientX === 'auto') {
  222. if (left < 0) {
  223. // align to the left and move into visible area if input's left edge < window's
  224. orientX = 'left';
  225. left = 10;
  226. } else if (left + calendarWidth > containerWidth) {
  227. // align to the right if canlendar's right edge > container's
  228. orientX = 'right';
  229. } else {
  230. orientX = getTextDirection(inputField) === 'rtl' ? 'right' : 'left';
  231. }
  232. }
  233. if (orientX === 'right') {
  234. left -= calendarWidth - inputWidth;
  235. }
  236. if (orientY === 'auto') {
  237. orientY = top - calendarHeight < scrollTop ? 'bottom' : 'top';
  238. }
  239. if (orientY === 'top') {
  240. top -= calendarHeight;
  241. } else {
  242. top += inputHeight;
  243. }
  244. classList.remove(
  245. 'datepicker-orient-top',
  246. 'datepicker-orient-bottom',
  247. 'datepicker-orient-right',
  248. 'datepicker-orient-left'
  249. );
  250. classList.add(`datepicker-orient-${orientY}`, `datepicker-orient-${orientX}`);
  251. style.top = top ? `${top}px` : top;
  252. style.left = left ? `${left}px` : left;
  253. }
  254. setViewSwitchLabel(labelText) {
  255. this.controls.viewSwitch.textContent = labelText;
  256. }
  257. setPrevBtnDisabled(disabled) {
  258. this.controls.prevBtn.disabled = disabled;
  259. }
  260. setNextBtnDisabled(disabled) {
  261. this.controls.nextBtn.disabled = disabled;
  262. }
  263. changeView(viewId) {
  264. const oldView = this.currentView;
  265. const newView = this.views[viewId];
  266. if (newView.id !== oldView.id) {
  267. this.currentView = newView;
  268. this._renderMethod = 'render';
  269. triggerDatepickerEvent(this.datepicker, 'changeView');
  270. this.main.replaceChild(newView.element, oldView.element);
  271. }
  272. return this;
  273. }
  274. // Change the focused date (view date)
  275. changeFocus(newViewDate) {
  276. this._renderMethod = setViewDate(this, newViewDate) ? 'render' : 'refreshFocus';
  277. this.views.forEach((view) => {
  278. view.updateFocus();
  279. });
  280. return this;
  281. }
  282. // Apply the change of the selected dates
  283. update() {
  284. const newViewDate = computeResetViewDate(this.datepicker);
  285. this._renderMethod = setViewDate(this, newViewDate) ? 'render' : 'refresh';
  286. this.views.forEach((view) => {
  287. view.updateFocus();
  288. view.updateSelection();
  289. });
  290. return this;
  291. }
  292. // Refresh the picker UI
  293. render(quickRender = true) {
  294. const renderMethod = (quickRender && this._renderMethod) || 'render';
  295. delete this._renderMethod;
  296. this.currentView[renderMethod]();
  297. }
  298. }