datetime.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import Field, { getValidationRules } from './_field';
  2. import DatePicker from 'app/ui/atoms/date-picker'
  3. import { useFormField } from 'app/lib/form/use-form-field';
  4. import { datetimeInitialValue } from 'app/lib/form/field-initial-values';
  5. export default function FormFieldDatetime({ name, value = '', type, ...props }) {
  6. const defaultValue = datetimeInitialValue({ value, type, required: props.required });
  7. const { field } = useFormField(
  8. { name, value, type, ...props },
  9. {
  10. defaultValue,
  11. rules: getValidationRules({ type, ...props }),
  12. syncValue: false,
  13. }
  14. );
  15. // UNA passes the lower bound as the input's `min` attr (unix ts or date string)
  16. const min = props?.attrs?.min;
  17. let minDate = min ? new Date(/^\d+$/.test(String(min)) ? Number(min) * 1000 : String(min).replace(' ', 'T')) : undefined;
  18. if (minDate && isNaN(minDate)) minDate = undefined;
  19. const setParamValue = (next) => {
  20. const date = new Date(next * 1000);
  21. if (props?.db?.pass == 'Date' || props?.db?.pass == 'DateTs') {
  22. field.onChange(
  23. `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  24. );
  25. return;
  26. }
  27. field.onChange(
  28. `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:00Z`
  29. );
  30. };
  31. return (
  32. <Field {...props} name={name} type={type}>
  33. <DatePicker value={field.value} type={type} name={name} minDate={minDate} disabled={!!props?.attrs?.disabled} onChange={setParamValue} />
  34. </Field>
  35. );
  36. }