Files
pfadi-bussle/components/dateSelect.js
Thomas Ruoff 7dc8c71852 half way
2020-08-06 22:36:51 +02:00

133 lines
3.5 KiB
JavaScript

import React, { useContext, useState } from 'react'
import useSWR from 'swr'
import { WizardContext } from '../context/wizardStore'
import Form from 'react-bootstrap/Form'
import DayPicker, { DateUtils } from 'react-day-picker'
import Required from './required'
import { dateFormat } from '../helpers/date'
const fetcher = (path) => fetch(path).then((r) => r.json())
export default function DateSelect() {
// const [focusedInput, setFocusedInput] = useState(null)
const { state, onChange } = useContext(WizardContext)
const [range, setRange] = useState({ form: null, to: null })
const { data: daysBooked, error: fetchBookedOnError } = useSWR(
'/api/daysbooked',
fetcher
)
const prevBookedDay = range.from
? daysBooked
.reverse()
.find((dayBooked) => dayBooked < dateFormat(range.from))
: null
const nextBookedDay = range.from
? daysBooked.find((dayBooked) => dayBooked > dateFormat(range.from))
: null
console.log('from', dateFormat(range.from), 'to', dateFormat(range.to))
console.log('prev', prevBookedDay, 'next', nextBookedDay)
function dayBeforeToday(day) {
return new Date() > day
}
function dayBooked(day) {
return daysBooked && daysBooked.includes(dateFormat(day))
}
function dayDisabled(day) {
return (
dayBeforeToday(day) ||
dayBooked(day) ||
(prevBookedDay && day < new Date(prevBookedDay)) ||
(nextBookedDay && day > new Date(nextBookedDay))
)
}
const { multipleDays } = state.formData
const { from, to } = range
const disabledDays = [dayDisabled]
const modifiers = {
dayBooked,
start: from,
end: to,
}
if (fetchBookedOnError) {
return (
<div>
Entschuldige, aber die Buchungszeiten konnten nicht geladen werden.
Versuchen Sie es später nochmals.
</div>
)
}
return (
<>
<Form.Group controlId="dateSelect">
<Form.Label>
Willst du einen odere mehrere Tage buchen? <Required />
</Form.Label>
<Form.Check
type="radio"
id={'multipleDays-single'}
label="Einen Tag"
name="multipleDays"
value="single"
checked={multipleDays === false}
onChange={() => {
//setFocusedInput(null)
onChange({
multipleDays: false,
startDate: null,
endDate: null,
})
}}
/>
<Form.Check
type="radio"
id={'multipleDays-multiple'}
label="Mehrere Tage"
name="multipleDays"
value="multiple"
checked={multipleDays === true}
onChange={() => {
//setFocusedInput(null)
onChange({
multipleDays: true,
startDate: null,
endDate: null,
})
}}
/>
</Form.Group>
{multipleDays !== null && (
<Form.Group>
<Form.Label component="legend" style={{ display: 'block' }}>
Datum <Required />
</Form.Label>
{multipleDays === false && <p>not implemented</p>}
{multipleDays === true && (
<DayPicker
className="Selectable"
numberOfMonths={2}
selectedDays={[from, { from, to }]}
disabledDays={disabledDays}
modifiers={modifiers}
onDayClick={(day) => {
const newRange = DateUtils.addDayToRange(day, range)
setRange(newRange)
}}
/>
)}
</Form.Group>
)}
</>
)
}