ab7a018d8e6aadb7e4b90067626cb9556a070849b2bc96afbe3f536d4b50757d7aa273f726a965cfd048d8b635eb2b039c52999a703383840ed39d1ab26526 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. <template>
  2. <table
  3. cellspacing="0"
  4. cellpadding="0"
  5. class="el-date-table"
  6. @click="handleClick"
  7. @mousemove="handleMouseMove"
  8. :class="{ 'is-week-mode': selectionMode === 'week' }">
  9. <tbody>
  10. <tr>
  11. <th v-if="showWeekNumber">{{ t('el.datepicker.week') }}</th>
  12. <th v-for="(week, key) in WEEKS" :key="key">{{ t('el.datepicker.weeks.' + week) }}</th>
  13. </tr>
  14. <tr
  15. class="el-date-table__row"
  16. v-for="(row, key) in rows"
  17. :class="{ current: isWeekActive(row[1]) }"
  18. :key="key">
  19. <td
  20. v-for="(cell, key) in row"
  21. :class="getCellClasses(cell)"
  22. :key="key">
  23. <div>
  24. <span>
  25. {{ cell.text }}
  26. </span>
  27. </div>
  28. </td>
  29. </tr>
  30. </tbody>
  31. </table>
  32. </template>
  33. <script>
  34. import { getFirstDayOfMonth, getDayCountOfMonth, getWeekNumber, getStartDateOfMonth, prevDate, nextDate, isDate, clearTime as _clearTime} from 'element-ui/src/utils/date-util';
  35. import Locale from 'element-ui/src/mixins/locale';
  36. import { arrayFindIndex, arrayFind, coerceTruthyValueToArray } from 'element-ui/src/utils/util';
  37. const WEEKS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
  38. const getDateTimestamp = function(time) {
  39. if (typeof time === 'number' || typeof time === 'string') {
  40. return _clearTime(new Date(time)).getTime();
  41. } else if (time instanceof Date) {
  42. return _clearTime(time).getTime();
  43. } else {
  44. return NaN;
  45. }
  46. };
  47. // remove the first element that satisfies `pred` from arr
  48. // return a new array if modification occurs
  49. // return the original array otherwise
  50. const removeFromArray = function(arr, pred) {
  51. const idx = typeof pred === 'function' ? arrayFindIndex(arr, pred) : arr.indexOf(pred);
  52. return idx >= 0 ? [...arr.slice(0, idx), ...arr.slice(idx + 1)] : arr;
  53. };
  54. export default {
  55. mixins: [Locale],
  56. props: {
  57. firstDayOfWeek: {
  58. default: 7,
  59. type: Number,
  60. validator: val => val >= 1 && val <= 7
  61. },
  62. value: {},
  63. defaultValue: {
  64. validator(val) {
  65. // either: null, valid Date object, Array of valid Date objects
  66. return val === null || isDate(val) || (Array.isArray(val) && val.every(isDate));
  67. }
  68. },
  69. date: {},
  70. selectionMode: {
  71. default: 'day'
  72. },
  73. showWeekNumber: {
  74. type: Boolean,
  75. default: false
  76. },
  77. disabledDate: {},
  78. cellClassName: {},
  79. minDate: {},
  80. maxDate: {},
  81. rangeState: {
  82. default() {
  83. return {
  84. endDate: null,
  85. selecting: false
  86. };
  87. }
  88. }
  89. },
  90. computed: {
  91. offsetDay() {
  92. const week = this.firstDayOfWeek;
  93. // 周日为界限,左右偏移的天数,3217654 例如周一就是 -1,目的是调整前两行日期的位置
  94. return week > 3 ? 7 - week : -week;
  95. },
  96. WEEKS() {
  97. const week = this.firstDayOfWeek;
  98. return WEEKS.concat(WEEKS).slice(week, week + 7);
  99. },
  100. year() {
  101. return this.date.getFullYear();
  102. },
  103. month() {
  104. return this.date.getMonth();
  105. },
  106. startDate() {
  107. return getStartDateOfMonth(this.year, this.month);
  108. },
  109. rows() {
  110. // TODO: refactory rows / getCellClasses
  111. const date = new Date(this.year, this.month, 1);
  112. let day = getFirstDayOfMonth(date); // day of first day
  113. const dateCountOfMonth = getDayCountOfMonth(date.getFullYear(), date.getMonth());
  114. const dateCountOfLastMonth = getDayCountOfMonth(date.getFullYear(), (date.getMonth() === 0 ? 11 : date.getMonth() - 1));
  115. day = (day === 0 ? 7 : day);
  116. const offset = this.offsetDay;
  117. const rows = this.tableRows;
  118. let count = 1;
  119. const startDate = this.startDate;
  120. const disabledDate = this.disabledDate;
  121. const cellClassName = this.cellClassName;
  122. const selectedDate = this.selectionMode === 'dates' ? coerceTruthyValueToArray(this.value) : [];
  123. const now = getDateTimestamp(new Date());
  124. for (let i = 0; i < 6; i++) {
  125. const row = rows[i];
  126. if (this.showWeekNumber) {
  127. if (!row[0]) {
  128. row[0] = { type: 'week', text: getWeekNumber(nextDate(startDate, i * 7 + 1)) };
  129. }
  130. }
  131. for (let j = 0; j < 7; j++) {
  132. let cell = row[this.showWeekNumber ? j + 1 : j];
  133. if (!cell) {
  134. cell = { row: i, column: j, type: 'normal', inRange: false, start: false, end: false };
  135. }
  136. cell.type = 'normal';
  137. const index = i * 7 + j;
  138. const time = nextDate(startDate, index - offset).getTime();
  139. cell.inRange = time >= getDateTimestamp(this.minDate) && time <= getDateTimestamp(this.maxDate);
  140. cell.start = this.minDate && time === getDateTimestamp(this.minDate);
  141. cell.end = this.maxDate && time === getDateTimestamp(this.maxDate);
  142. const isToday = time === now;
  143. if (isToday) {
  144. cell.type = 'today';
  145. }
  146. if (i >= 0 && i <= 1) {
  147. const numberOfDaysFromPreviousMonth = day + offset < 0 ? 7 + day + offset : day + offset;
  148. if (j + i * 7 >= numberOfDaysFromPreviousMonth) {
  149. cell.text = count++;
  150. } else {
  151. cell.text = dateCountOfLastMonth - (numberOfDaysFromPreviousMonth - j % 7) + 1 + i * 7;
  152. cell.type = 'prev-month';
  153. }
  154. } else {
  155. if (count <= dateCountOfMonth) {
  156. cell.text = count++;
  157. } else {
  158. cell.text = count++ - dateCountOfMonth;
  159. cell.type = 'next-month';
  160. }
  161. }
  162. let cellDate = new Date(time);
  163. cell.disabled = typeof disabledDate === 'function' && disabledDate(cellDate);
  164. cell.selected = arrayFind(selectedDate, date => date.getTime() === cellDate.getTime());
  165. cell.customClass = typeof cellClassName === 'function' && cellClassName(cellDate);
  166. this.$set(row, this.showWeekNumber ? j + 1 : j, cell);
  167. }
  168. if (this.selectionMode === 'week') {
  169. const start = this.showWeekNumber ? 1 : 0;
  170. const end = this.showWeekNumber ? 7 : 6;
  171. const isWeekActive = this.isWeekActive(row[start + 1]);
  172. row[start].inRange = isWeekActive;
  173. row[start].start = isWeekActive;
  174. row[end].inRange = isWeekActive;
  175. row[end].end = isWeekActive;
  176. }
  177. }
  178. return rows;
  179. }
  180. },
  181. watch: {
  182. 'rangeState.endDate'(newVal) {
  183. this.markRange(this.minDate, newVal);
  184. },
  185. minDate(newVal, oldVal) {
  186. if (getDateTimestamp(newVal) !== getDateTimestamp(oldVal)) {
  187. this.markRange(this.minDate, this.maxDate);
  188. }
  189. },
  190. maxDate(newVal, oldVal) {
  191. if (getDateTimestamp(newVal) !== getDateTimestamp(oldVal)) {
  192. this.markRange(this.minDate, this.maxDate);
  193. }
  194. }
  195. },
  196. data() {
  197. return {
  198. tableRows: [ [], [], [], [], [], [] ],
  199. lastRow: null,
  200. lastColumn: null
  201. };
  202. },
  203. methods: {
  204. cellMatchesDate(cell, date) {
  205. const value = new Date(date);
  206. return this.year === value.getFullYear() &&
  207. this.month === value.getMonth() &&
  208. Number(cell.text) === value.getDate();
  209. },
  210. getCellClasses(cell) {
  211. const selectionMode = this.selectionMode;
  212. const defaultValue = this.defaultValue ? Array.isArray(this.defaultValue) ? this.defaultValue : [this.defaultValue] : [];
  213. let classes = [];
  214. if ((cell.type === 'normal' || cell.type === 'today') && !cell.disabled) {
  215. classes.push('available');
  216. if (cell.type === 'today') {
  217. classes.push('today');
  218. }
  219. } else {
  220. classes.push(cell.type);
  221. }
  222. if (cell.type === 'normal' && defaultValue.some(date => this.cellMatchesDate(cell, date))) {
  223. classes.push('default');
  224. }
  225. if (selectionMode === 'day' && (cell.type === 'normal' || cell.type === 'today') && this.cellMatchesDate(cell, this.value)) {
  226. classes.push('current');
  227. }
  228. if (cell.inRange && ((cell.type === 'normal' || cell.type === 'today') || this.selectionMode === 'week')) {
  229. classes.push('in-range');
  230. if (cell.start) {
  231. classes.push('start-date');
  232. }
  233. if (cell.end) {
  234. classes.push('end-date');
  235. }
  236. }
  237. if (cell.disabled) {
  238. classes.push('disabled');
  239. }
  240. if (cell.selected) {
  241. classes.push('selected');
  242. }
  243. if (cell.customClass) {
  244. classes.push(cell.customClass);
  245. }
  246. return classes.join(' ');
  247. },
  248. getDateOfCell(row, column) {
  249. const offsetFromStart = row * 7 + (column - (this.showWeekNumber ? 1 : 0)) - this.offsetDay;
  250. return nextDate(this.startDate, offsetFromStart);
  251. },
  252. isWeekActive(cell) {
  253. if (this.selectionMode !== 'week') return false;
  254. const newDate = new Date(this.year, this.month, 1);
  255. const year = newDate.getFullYear();
  256. const month = newDate.getMonth();
  257. if (cell.type === 'prev-month') {
  258. newDate.setMonth(month === 0 ? 11 : month - 1);
  259. newDate.setFullYear(month === 0 ? year - 1 : year);
  260. }
  261. if (cell.type === 'next-month') {
  262. newDate.setMonth(month === 11 ? 0 : month + 1);
  263. newDate.setFullYear(month === 11 ? year + 1 : year);
  264. }
  265. newDate.setDate(parseInt(cell.text, 10));
  266. if (isDate(this.value)) {
  267. const dayOffset = (this.value.getDay() - this.firstDayOfWeek + 7) % 7 - 1;
  268. const weekDate = prevDate(this.value, dayOffset);
  269. return weekDate.getTime() === newDate.getTime();
  270. }
  271. return false;
  272. },
  273. markRange(minDate, maxDate) {
  274. minDate = getDateTimestamp(minDate);
  275. maxDate = getDateTimestamp(maxDate) || minDate;
  276. [minDate, maxDate] = [Math.min(minDate, maxDate), Math.max(minDate, maxDate)];
  277. const startDate = this.startDate;
  278. const rows = this.rows;
  279. for (let i = 0, k = rows.length; i < k; i++) {
  280. const row = rows[i];
  281. for (let j = 0, l = row.length; j < l; j++) {
  282. if (this.showWeekNumber && j === 0) continue;
  283. const cell = row[j];
  284. const index = i * 7 + j + (this.showWeekNumber ? -1 : 0);
  285. const time = nextDate(startDate, index - this.offsetDay).getTime();
  286. cell.inRange = minDate && time >= minDate && time <= maxDate;
  287. cell.start = minDate && time === minDate;
  288. cell.end = maxDate && time === maxDate;
  289. }
  290. }
  291. },
  292. handleMouseMove(event) {
  293. if (!this.rangeState.selecting) return;
  294. let target = event.target;
  295. if (target.tagName === 'SPAN') {
  296. target = target.parentNode.parentNode;
  297. }
  298. if (target.tagName === 'DIV') {
  299. target = target.parentNode;
  300. }
  301. if (target.tagName !== 'TD') return;
  302. const row = target.parentNode.rowIndex - 1;
  303. const column = target.cellIndex;
  304. // can not select disabled date
  305. if (this.rows[row][column].disabled) return;
  306. // only update rangeState when mouse moves to a new cell
  307. // this avoids frequent Date object creation and improves performance
  308. if (row !== this.lastRow || column !== this.lastColumn) {
  309. this.lastRow = row;
  310. this.lastColumn = column;
  311. this.$emit('changerange', {
  312. minDate: this.minDate,
  313. maxDate: this.maxDate,
  314. rangeState: {
  315. selecting: true,
  316. endDate: this.getDateOfCell(row, column)
  317. }
  318. });
  319. }
  320. },
  321. handleClick(event) {
  322. let target = event.target;
  323. if (target.tagName === 'SPAN') {
  324. target = target.parentNode.parentNode;
  325. }
  326. if (target.tagName === 'DIV') {
  327. target = target.parentNode;
  328. }
  329. if (target.tagName !== 'TD') return;
  330. const row = target.parentNode.rowIndex - 1;
  331. const column = this.selectionMode === 'week' ? 1 : target.cellIndex;
  332. const cell = this.rows[row][column];
  333. if (cell.disabled || cell.type === 'week') return;
  334. const newDate = this.getDateOfCell(row, column);
  335. if (this.selectionMode === 'range') {
  336. if (!this.rangeState.selecting) {
  337. this.$emit('pick', {minDate: newDate, maxDate: null});
  338. this.rangeState.selecting = true;
  339. } else {
  340. if (newDate >= this.minDate) {
  341. this.$emit('pick', {minDate: this.minDate, maxDate: newDate});
  342. } else {
  343. this.$emit('pick', {minDate: newDate, maxDate: this.minDate});
  344. }
  345. this.rangeState.selecting = false;
  346. }
  347. } else if (this.selectionMode === 'day') {
  348. this.$emit('pick', newDate);
  349. } else if (this.selectionMode === 'week') {
  350. const weekNumber = getWeekNumber(newDate);
  351. const value = newDate.getFullYear() + 'w' + weekNumber;
  352. this.$emit('pick', {
  353. year: newDate.getFullYear(),
  354. week: weekNumber,
  355. value: value,
  356. date: newDate
  357. });
  358. } else if (this.selectionMode === 'dates') {
  359. const value = this.value || [];
  360. const newValue = cell.selected
  361. ? removeFromArray(value, date => date.getTime() === newDate.getTime())
  362. : [...value, newDate];
  363. this.$emit('pick', newValue);
  364. }
  365. }
  366. }
  367. };
  368. </script>