1 | import moment from 'moment';
|
2 | import {creatorFactory} from '@form-create/core/src/index';
|
3 |
|
4 | const FORMAT_TYPE = {
|
5 | date: 'YYYY-MM-DD',
|
6 | month: 'YYYY-MM',
|
7 | week: 'YYYY-wo',
|
8 | range: 'YYYY-MM-DD HH:mm:ss'
|
9 | };
|
10 |
|
11 | const getType = function (ctx) {
|
12 | const type = ctx.prop.props.type;
|
13 | if (['date', 'month', 'week', 'range'].indexOf(type) === -1) return 'date';
|
14 | return type;
|
15 | };
|
16 |
|
17 | const toMoment = function (val) {
|
18 | return val instanceof moment ? val : moment(val);
|
19 | };
|
20 |
|
21 | function getFormat(ctx) {
|
22 | return ctx.prop.props.format || (ctx.el ? ctx.el.format : '') || FORMAT_TYPE[getType(ctx)];
|
23 | }
|
24 |
|
25 | const name = 'datePicker';
|
26 |
|
27 | export default {
|
28 | name,
|
29 | maker: (function () {
|
30 | return ['date', 'month', 'week'].reduce((initial, type) => {
|
31 | initial[type] = creatorFactory(name, {type});
|
32 | return initial
|
33 | }, {
|
34 | dateRange: creatorFactory(name, {type:'range'}),
|
35 | datetimeRange: creatorFactory(name, m => m.props({type: 'range', showTime: true}))
|
36 | })
|
37 | }()),
|
38 | toFormValue(value, ctx) {
|
39 | let parseValue, type = getType(ctx);
|
40 | const isArr = Array.isArray(value);
|
41 | if (type === 'range') {
|
42 | if (isArr) {
|
43 | parseValue = value.map(v => v ? toMoment(v) : null);
|
44 | } else {
|
45 | parseValue = []
|
46 | }
|
47 | } else {
|
48 | parseValue = isArr ? ((value[0] ? toMoment(value[0]) : null) || null) : (value ? toMoment(value) : null);
|
49 | }
|
50 | return parseValue;
|
51 | },
|
52 | toValue(formValue, ctx) {
|
53 | const format = getFormat(ctx);
|
54 | if (Array.isArray(formValue))
|
55 | return formValue.map(v => v ? v.format(format) : v);
|
56 | else
|
57 | return formValue ? formValue.format(format) : formValue;
|
58 | },
|
59 | render(children, ctx) {
|
60 | const type = getType(ctx) + 'Picker';
|
61 | return ctx.$render.vNode[type](ctx.prop, children);
|
62 | }
|
63 |
|
64 | }
|