index.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import { VantComponent } from '../common/component';
  2. import { isDef } from '../common/validator';
  3. import { pickerProps } from '../picker/shared';
  4. const currentYear = new Date().getFullYear();
  5. function isValidDate(date) {
  6. return isDef(date) && !isNaN(new Date(date).getTime());
  7. }
  8. function range(num, min, max) {
  9. return Math.min(Math.max(num, min), max);
  10. }
  11. function padZero(val) {
  12. return `00${val}`.slice(-2);
  13. }
  14. function times(n, iteratee) {
  15. let index = -1;
  16. const result = Array(n < 0 ? 0 : n);
  17. while (++index < n) {
  18. result[index] = iteratee(index);
  19. }
  20. return result;
  21. }
  22. function getTrueValue(formattedValue) {
  23. if (formattedValue === undefined) {
  24. formattedValue = '1';
  25. }
  26. while (isNaN(parseInt(formattedValue, 10))) {
  27. formattedValue = formattedValue.slice(1);
  28. }
  29. return parseInt(formattedValue, 10);
  30. }
  31. function getMonthEndDay(year, month) {
  32. return 32 - new Date(year, month - 1, 32).getDate();
  33. }
  34. const defaultFormatter = (type, value) => value;
  35. VantComponent({
  36. classes: ['active-class', 'toolbar-class', 'column-class'],
  37. props: Object.assign(Object.assign({}, pickerProps), { value: {
  38. type: null,
  39. observer: 'updateValue',
  40. }, filter: null, type: {
  41. type: String,
  42. value: 'datetime',
  43. observer: 'updateValue',
  44. }, showToolbar: {
  45. type: Boolean,
  46. value: true,
  47. }, formatter: {
  48. type: null,
  49. value: defaultFormatter,
  50. }, minDate: {
  51. type: Number,
  52. value: new Date(currentYear - 10, 0, 1).getTime(),
  53. observer: 'updateValue',
  54. }, maxDate: {
  55. type: Number,
  56. value: new Date(currentYear + 10, 11, 31).getTime(),
  57. observer: 'updateValue',
  58. }, minHour: {
  59. type: Number,
  60. value: 0,
  61. observer: 'updateValue',
  62. }, maxHour: {
  63. type: Number,
  64. value: 23,
  65. observer: 'updateValue',
  66. }, minMinute: {
  67. type: Number,
  68. value: 0,
  69. observer: 'updateValue',
  70. }, maxMinute: {
  71. type: Number,
  72. value: 59,
  73. observer: 'updateValue',
  74. } }),
  75. data: {
  76. innerValue: Date.now(),
  77. columns: [],
  78. },
  79. methods: {
  80. updateValue() {
  81. const { data } = this;
  82. const val = this.correctValue(data.value);
  83. const isEqual = val === data.innerValue;
  84. this.updateColumnValue(val).then(() => {
  85. if (!isEqual) {
  86. this.$emit('input', val);
  87. }
  88. });
  89. },
  90. getPicker() {
  91. if (this.picker == null) {
  92. this.picker = this.selectComponent('.van-datetime-picker');
  93. const { picker } = this;
  94. const { setColumnValues } = picker;
  95. picker.setColumnValues = (...args) => setColumnValues.apply(picker, [...args, false]);
  96. }
  97. return this.picker;
  98. },
  99. updateColumns() {
  100. const { formatter = defaultFormatter } = this.data;
  101. const results = this.getOriginColumns().map((column) => ({
  102. values: column.values.map((value) => formatter(column.type, value)),
  103. }));
  104. return this.set({ columns: results });
  105. },
  106. getOriginColumns() {
  107. const { filter } = this.data;
  108. const results = this.getRanges().map(({ type, range }) => {
  109. let values = times(range[1] - range[0] + 1, (index) => {
  110. const value = range[0] + index;
  111. return type === 'year' ? `${value}` : padZero(value);
  112. });
  113. if (filter) {
  114. values = filter(type, values);
  115. }
  116. return { type, values };
  117. });
  118. return results;
  119. },
  120. getRanges() {
  121. const { data } = this;
  122. if (data.type === 'time') {
  123. return [
  124. {
  125. type: 'hour',
  126. range: [data.minHour, data.maxHour],
  127. },
  128. {
  129. type: 'minute',
  130. range: [data.minMinute, data.maxMinute],
  131. },
  132. ];
  133. }
  134. const { maxYear, maxDate, maxMonth, maxHour, maxMinute, } = this.getBoundary('max', data.innerValue);
  135. const { minYear, minDate, minMonth, minHour, minMinute, } = this.getBoundary('min', data.innerValue);
  136. const result = [
  137. {
  138. type: 'year',
  139. range: [minYear, maxYear],
  140. },
  141. {
  142. type: 'month',
  143. range: [minMonth, maxMonth],
  144. },
  145. {
  146. type: 'day',
  147. range: [minDate, maxDate],
  148. },
  149. {
  150. type: 'hour',
  151. range: [minHour, maxHour],
  152. },
  153. {
  154. type: 'minute',
  155. range: [minMinute, maxMinute],
  156. },
  157. ];
  158. if (data.type === 'date')
  159. result.splice(3, 2);
  160. if (data.type === 'year-month')
  161. result.splice(2, 3);
  162. return result;
  163. },
  164. correctValue(value) {
  165. const { data } = this;
  166. // validate value
  167. const isDateType = data.type !== 'time';
  168. if (isDateType && !isValidDate(value)) {
  169. value = data.minDate;
  170. }
  171. else if (!isDateType && !value) {
  172. const { minHour } = data;
  173. value = `${padZero(minHour)}:00`;
  174. }
  175. // time type
  176. if (!isDateType) {
  177. let [hour, minute] = value.split(':');
  178. hour = padZero(range(hour, data.minHour, data.maxHour));
  179. minute = padZero(range(minute, data.minMinute, data.maxMinute));
  180. return `${hour}:${minute}`;
  181. }
  182. // date type
  183. value = Math.max(value, data.minDate);
  184. value = Math.min(value, data.maxDate);
  185. return value;
  186. },
  187. getBoundary(type, innerValue) {
  188. const value = new Date(innerValue);
  189. const boundary = new Date(this.data[`${type}Date`]);
  190. const year = boundary.getFullYear();
  191. let month = 1;
  192. let date = 1;
  193. let hour = 0;
  194. let minute = 0;
  195. if (type === 'max') {
  196. month = 12;
  197. date = getMonthEndDay(value.getFullYear(), value.getMonth() + 1);
  198. hour = 23;
  199. minute = 59;
  200. }
  201. if (value.getFullYear() === year) {
  202. month = boundary.getMonth() + 1;
  203. if (value.getMonth() + 1 === month) {
  204. date = boundary.getDate();
  205. if (value.getDate() === date) {
  206. hour = boundary.getHours();
  207. if (value.getHours() === hour) {
  208. minute = boundary.getMinutes();
  209. }
  210. }
  211. }
  212. }
  213. return {
  214. [`${type}Year`]: year,
  215. [`${type}Month`]: month,
  216. [`${type}Date`]: date,
  217. [`${type}Hour`]: hour,
  218. [`${type}Minute`]: minute,
  219. };
  220. },
  221. onCancel() {
  222. this.$emit('cancel');
  223. },
  224. onConfirm() {
  225. this.$emit('confirm', this.data.innerValue);
  226. },
  227. onChange() {
  228. const { data } = this;
  229. let value;
  230. const picker = this.getPicker();
  231. const originColumns = this.getOriginColumns();
  232. if (data.type === 'time') {
  233. const indexes = picker.getIndexes();
  234. value = `${+originColumns[0].values[indexes[0]]}:${+originColumns[1]
  235. .values[indexes[1]]}`;
  236. }
  237. else {
  238. const indexes = picker.getIndexes();
  239. const values = indexes.map((value, index) => originColumns[index].values[value]);
  240. const year = getTrueValue(values[0]);
  241. const month = getTrueValue(values[1]);
  242. const maxDate = getMonthEndDay(year, month);
  243. let date = getTrueValue(values[2]);
  244. if (data.type === 'year-month') {
  245. date = 1;
  246. }
  247. date = date > maxDate ? maxDate : date;
  248. let hour = 0;
  249. let minute = 0;
  250. if (data.type === 'datetime') {
  251. hour = getTrueValue(values[3]);
  252. minute = getTrueValue(values[4]);
  253. }
  254. value = new Date(year, month - 1, date, hour, minute);
  255. }
  256. value = this.correctValue(value);
  257. this.updateColumnValue(value).then(() => {
  258. this.$emit('input', value);
  259. this.$emit('change', picker);
  260. });
  261. },
  262. updateColumnValue(value) {
  263. let values = [];
  264. const { type } = this.data;
  265. const formatter = this.data.formatter || defaultFormatter;
  266. const picker = this.getPicker();
  267. if (type === 'time') {
  268. const pair = value.split(':');
  269. values = [formatter('hour', pair[0]), formatter('minute', pair[1])];
  270. }
  271. else {
  272. const date = new Date(value);
  273. values = [
  274. formatter('year', `${date.getFullYear()}`),
  275. formatter('month', padZero(date.getMonth() + 1)),
  276. ];
  277. if (type === 'date') {
  278. values.push(formatter('day', padZero(date.getDate())));
  279. }
  280. if (type === 'datetime') {
  281. values.push(formatter('day', padZero(date.getDate())), formatter('hour', padZero(date.getHours())), formatter('minute', padZero(date.getMinutes())));
  282. }
  283. }
  284. return this.set({ innerValue: value })
  285. .then(() => this.updateColumns())
  286. .then(() => picker.setValues(values));
  287. },
  288. },
  289. created() {
  290. const innerValue = this.correctValue(this.data.value);
  291. this.updateColumnValue(innerValue).then(() => {
  292. this.$emit('input', innerValue);
  293. });
  294. },
  295. });