2021-11-03 21:30:11 +01:00
|
|
|
import { format, isAfter, parse, sub, subYears } from "date-fns";
|
2021-10-26 17:08:03 +02:00
|
|
|
import { h, VNode } from "preact";
|
|
|
|
import { useLayoutEffect, useRef, useState } from "preact/hooks";
|
|
|
|
import { DatePicker } from "../picker/DatePicker";
|
|
|
|
|
|
|
|
export interface DateInputProps {
|
|
|
|
label: string;
|
|
|
|
grabFocus?: boolean;
|
|
|
|
tooltip?: string;
|
|
|
|
error?: string;
|
2021-10-27 20:13:35 +02:00
|
|
|
years?: Array<number>;
|
2021-10-26 17:08:03 +02:00
|
|
|
bind: [string, (x: string) => void];
|
|
|
|
}
|
|
|
|
|
|
|
|
export function DateInput(props: DateInputProps): VNode {
|
|
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
|
|
useLayoutEffect(() => {
|
|
|
|
if (props.grabFocus) {
|
|
|
|
inputRef.current?.focus();
|
|
|
|
}
|
|
|
|
}, [props.grabFocus]);
|
2021-11-03 21:30:11 +01:00
|
|
|
const [opened, setOpened] = useState(false)
|
2021-10-26 17:08:03 +02:00
|
|
|
|
2021-11-01 20:10:49 +01:00
|
|
|
const value = props.bind[0] || "";
|
2021-10-26 17:08:03 +02:00
|
|
|
const [dirty, setDirty] = useState(false)
|
|
|
|
const showError = dirty && props.error
|
|
|
|
|
2021-11-03 21:30:11 +01:00
|
|
|
const calendar = subYears(new Date(), 30)
|
|
|
|
|
2021-10-26 17:08:03 +02:00
|
|
|
return <div class="field">
|
|
|
|
<label class="label">
|
|
|
|
{props.label}
|
|
|
|
{props.tooltip && <span class="icon has-tooltip-right" data-tooltip={props.tooltip}>
|
|
|
|
<i class="mdi mdi-information" />
|
|
|
|
</span>}
|
|
|
|
</label>
|
2021-11-03 21:30:11 +01:00
|
|
|
<div class="control">
|
|
|
|
<div class="field has-addons">
|
|
|
|
<p class="control">
|
|
|
|
<input
|
|
|
|
type="text"
|
|
|
|
class={showError ? 'input is-danger' : 'input'}
|
|
|
|
value={value}
|
2021-11-04 19:17:57 +01:00
|
|
|
onInput={(e) => {
|
2021-11-03 21:30:11 +01:00
|
|
|
const text = e.currentTarget.value
|
|
|
|
setDirty(true)
|
|
|
|
props.bind[1](text);
|
|
|
|
}}
|
|
|
|
ref={inputRef} />
|
|
|
|
</p>
|
|
|
|
<p class="control">
|
|
|
|
<a class="button" onClick={() => { setOpened(true) }}>
|
|
|
|
<span class="icon"><i class="mdi mdi-calendar" /></span>
|
|
|
|
</a>
|
|
|
|
</p>
|
|
|
|
</div>
|
2021-10-26 17:08:03 +02:00
|
|
|
</div>
|
2021-11-03 21:30:11 +01:00
|
|
|
<p class="help">Using the format yyyy-mm-dd</p>
|
2021-10-26 17:08:03 +02:00
|
|
|
{showError && <p class="help is-danger">{props.error}</p>}
|
|
|
|
<DatePicker
|
|
|
|
opened={opened}
|
2021-11-03 21:30:11 +01:00
|
|
|
initialDate={calendar}
|
2021-10-27 20:13:35 +02:00
|
|
|
years={props.years}
|
2021-10-26 17:08:03 +02:00
|
|
|
closeFunction={() => setOpened(false)}
|
|
|
|
dateReceiver={(d) => {
|
|
|
|
setDirty(true)
|
2021-11-03 21:30:11 +01:00
|
|
|
const v = format(d, 'yyyy-MM-dd')
|
2021-10-26 17:08:03 +02:00
|
|
|
props.bind[1](v);
|
|
|
|
}}
|
|
|
|
/>
|
|
|
|
</div>
|
|
|
|
;
|
|
|
|
|
|
|
|
}
|