-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathFormDatePicker.vue
More file actions
344 lines (325 loc) · 9.97 KB
/
FormDatePicker.vue
File metadata and controls
344 lines (325 loc) · 9.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
<template>
<div class="form-group position-relative">
<required-asterisk /><label v-uni-for="name" class="mr-2">{{ label }}</label>
<date-pick
v-model="date"
v-bind="datePickerConfig"
:format="format"
:data-test="dataTest"
:input-attributes="inputAttributes"
class="datePicker"
@input="submitDate"
>
<template v-slot:default="{ open, inputValue }">
<input
type="text"
v-bind="inputAttributes"
:value="inputValue"
:class="[classList, 'form-control']"
@focus="onOpen(open)"
@click="onOpen(open)"
@change="onChangeHandler($event.target.value)"
/>
<button
v-if="date && !isReadOnly"
type="button"
@click="clear"
class="vdpClearInput"
></button>
</template>
</date-pick>
<div v-if="errors.length > 0" class="invalid-feedback d-block">
<div v-for="(err, index) in errors" :key="index">{{ err }}</div>
</div>
<small v-if="helper" class="form-text text-muted">{{
helper
}}</small>
</div>
</template>
<script>
import { createUniqIdsMixin } from "vue-uniq-ids";
import moment from "moment-timezone";
import Mustache from "mustache";
import DatePicker from "./DatePicker.vue";
import ValidationMixin from "./mixins/validation";
import DataFormatMixin from "./mixins/DataFormat";
import { getUserDateFormat, getUserDateTimeFormat, getTimezone } from "../dateUtils";
import "vue-date-pick/dist/vueDatePick.css";
import RequiredAsterisk from './common/RequiredAsterisk';
import Validator from "@chantouchsek/validatorjs";
const uniqIdsMixin = createUniqIdsMixin();
const checkFormats = ["YYYY-MM-DD", "MM/DD/YYYY", moment.ISO_8601];
Validator.register(
"date_or_mustache",
function (value, requirement, attribute) {
let rendered = null;
try {
// Clear out any mustache statements
rendered = Mustache.render(value, {});
} catch (e) {
rendered = value;
}
if (value !== rendered) {
// contains mustache, so just give them the benefit of the doubt here
return true;
}
if (value === "") {
// Empty is ok, it just disables min/max
return true;
}
return moment(value, checkFormats, true).isValid();
},
"Must be YYYY-MM-DD, ISO8601, or mustache syntax"
);
export default {
components: {
"date-pick": DatePicker,
RequiredAsterisk,
},
mixins: [uniqIdsMixin, ValidationMixin, DataFormatMixin],
props: {
name: String,
placeholder: String,
label: String,
error: [String, Boolean],
helper: String,
dataFormat: String,
value: [String, Boolean, Date],
ariaLabel: String,
tabIndex: Number,
inputClass: { type: [String, Array, Object], default: "form-control" },
dataTest: {
type: String,
default: "date-picker"
},
disabled: {
type: Boolean,
default: false
},
minDate: { type: [String, Boolean], default: false },
maxDate: { type: [String, Boolean], default: false }
},
data() {
// set to the browser's timezone because the vue-date-pick always works
// with the browser's timezone
moment.tz.setDefault(getTimezone());
return {
validatorErrors: [],
date: "",
onChangeDate: ""
};
},
computed: {
datePickerConfig() {
return {
format: this.format,
displayFormat: this.format,
pickTime: this.datepicker,
parseDate: this.parsingInputDate,
editable: !this.disabled,
use12HourClock: this.datepicker,
isDateDisabled: this.checkMinMaxDateDisabled
};
},
inputAttributes() {
return {
class: `${this.inputClass}`,
placeholder: this.placeholder,
name: this.name,
"aria-label": this.ariaLabel,
"tab-index": this.tabIndex,
disabled: this.disabled,
readonly: this.isReadOnly
};
},
datepicker() {
return this.dataFormat === "datetime";
},
format() {
return this.datepicker ? getUserDateTimeFormat() : getUserDateFormat();
},
classList() {
return {
"is-invalid":
(this.validator && this.validator.errorCount) || this.error
};
},
errors() {
if (this.error) {
return [...this.validatorErrors, this.error];
}
return this.validatorErrors;
}
},
watch: {
validator: {
deep: true,
handler() {
this.validatorErrors =
this.validator && this.validator.errors.get(this.name)
? this.validator.errors.get(this.name)
: [];
}
},
value(newValue) {
this.updateValue(newValue);
}
},
created() {
Validator.register(
"after_min_date",
(value, requirement, attribute) => {
return (
this.parseDate(value) >=
this.parseDate(this.minDate)
);
},
"Must be after or equal Minimum Date"
);
this.updateValue(this.value);
},
methods: {
updateValue(newValue) {
// allow to send empty value or null to Date and Datetime fields
if (newValue === null || newValue === undefined) {
this.$set(this, "date", '');
return;
}
if (!!newValue && newValue.length > 0) {
const date = moment.tz(newValue, checkFormats, true, getTimezone());
if (!date.isValid()) return "";
this.date = date.format(this.format);
}
},
parseDate(val) {
let date = false;
if (typeof val === "string" && val !== "") {
try {
date = Mustache.render(val, this.validationData);
} catch (error) {
date = val;
}
date = moment(date, checkFormats, true);
if (!date.isValid()) {
date = false;
}
}
return date;
},
parseDateToDate(val) {
let date = "";
if (typeof val === "string" && val !== "") {
try {
date = Mustache.render(val, this.validationData);
} catch (error) {
date = val;
}
date = moment(date, checkFormats, true);
if (!date.isValid()) {
date = "";
} else {
date = date.toDate();
}
}
return date;
},
parsingInputDate(val) {
const date = moment(val, this.format).local(true);
// Check if user is typing, if the date is not valid, let the user continue
if (!date.isValid()) return "";
return date.toDate();
},
/*
Function to be used for the DatePicker, to see if minDate and maxDate are
1. Valid
2. Within the range
In the datepicker itself, this goes through a for loop to check if the dates that the user is seeing, are valid and
acceptable
@param {string, Date} date
@returns {boolean}
*/
checkMinMaxDateDisabled(date) {
date = moment(date.toLocaleDateString() + ' ' + moment().format('hh:mm:ss a')).toDate();
const minDate = !!this.minDate ? this.parseDateToDate(this.minDate) : "";
const maxDate = !!this.maxDate ? this.parseDateToDate(this.maxDate) : "";
// If minDate and maxDate are not defined, return. This would be the default case
if (minDate.length === 0 && maxDate.length === 0) return;
if (!!minDate && !!maxDate) {
if (this.config.dataFormat === 'date') {
return !(moment(date).isSameOrAfter(minDate, 'day') && moment(date).isSameOrBefore(this.maxDate, 'day'));
}
return !(date >= minDate && date <= maxDate);
}
// If minDate is defined but maxDate not defined, block the dates before minDate is defined
if (!!minDate && maxDate.length === 0) return date < minDate;
// If maxDate is defined but minDate not defined, block the dates after maxDate is defined
if (minDate.length === 0 && !!maxDate) return date > maxDate;
},
isDateAndValueTheSame() {
if (!this.date && !this.value) {
return true;
}
const currentDate = moment(this.date, this.datePickerConfig.format);
const currentValue = this.value ? moment(this.value) : null;
const comparatorString = this.dataFormat !== "datetime" ? "day" : null;
return currentDate.isSame(currentValue, comparatorString);
},
submitDate() {
if (this.onChangeDate !== "") {
this.date = this.onChangeDate;
}
if (this.value && !this.date) {
this.$emit("input", "");
}
if (this.isDateAndValueTheSame()) return;
const newDate =
this.dataFormat === "date"
? moment.utc(this.date, this.datePickerConfig.format)
: moment(this.date, this.datePickerConfig.format);
// Check if the date that the user inputted, is valid against the minDate set
if (newDate.isBefore(this.parseDateToDate(this.minDate))) return null;
// Check if the date that the user inputted, is valid against the maxDate set
if (newDate.isAfter(moment(this.parseDateToDate(this.maxDate)))) return null;
if (this.dataFormat === "datetime") {
// we must change the date timezone to the user timezone, then convert it to ISOString
// e.g. browser at UTC-4, newDate is 2023-03-17 12:16:00, we must convert it to 2023-03-17 12:16:00 UTC-7
// then convert it to ISOString
const fixedDate = moment.tz(newDate, getTimezone()); // user tz
this.$emit("input", fixedDate.toISOString());
} else {
this.$emit("input", newDate.toISOString());
}
},
onOpen(open) {
this.onChangeDate = "";
if (typeof open === "function") {
open();
}
},
clear() {
this.date = "";
this.$emit("input", "");
},
onChangeHandler(userText) {
if (userText) {
const userDate = moment(userText, [...checkFormats, this.format], true);
if (userDate.isValid()) {
this.onChangeDate = userDate.format(this.format);
this.submitDate();
}
}
}
}
};
</script>
<style>
.vdpHeadCell {
padding: 0.3em 0.4em 1.8em;
}
.datePicker {
display: block !important;
}
.vdpOuterWrap.vdpFloating {
z-index: 5;
}
</style>