move all wizard specific stuff to components/wizard

This commit is contained in:
Thomas Ruoff
2020-08-22 00:25:14 +02:00
parent 1df26814ba
commit 1bf7c7b801
9 changed files with 23 additions and 16 deletions

View File

@@ -0,0 +1,85 @@
import React, { useContext } from 'react'
import { WizardContext } from './context/wizardStore'
import Required from './required'
export default function Contact() {
const { state, onChangeEvent } = useContext(WizardContext)
const { name, email, street, zip, city } = state.formData
return (
<>
<div className="fsw">
<div className="fs">
<label className="flabel">
Name <Required />
</label>
<input
type="text"
name="name"
value={name}
onChange={onChangeEvent}
required
className="input-text"
/>
</div>
</div>
<div className="fsw">
<div className="fs">
<label className="flabel">
E-Mail <Required />
</label>
<input
type="email"
name="email"
value={email}
onChange={onChangeEvent}
required
className="input-text"
/>
</div>
</div>
<div className="fsw">
<div className="fs">
<label className="flabel">
Straße <Required />
</label>
<input
type="text"
name="street"
value={street}
onChange={onChangeEvent}
required
className="input-text"
/>
</div>
</div>
<div className="fsw">
<div className="fs">
<label className="flabel">
PLZ <Required />
</label>
<input
type="text"
name="zip"
value={zip}
onChange={onChangeEvent}
required
className="input-text"
/>
<label className="flabel">
Stadt <Required />
</label>
<input
type="text"
name="city"
value={city}
onChange={onChangeEvent}
required
className="input-text"
/>
</div>
</div>
</>
)
}

View File

@@ -0,0 +1,193 @@
import React, { useReducer, useEffect } from 'react'
import {
storeBookingData,
loadBookingData,
clearBookingData,
} from '../../../helpers/storage'
export const WizardContext = React.createContext()
export const ACTIONS = {
SET_FORM_DATA: 'setFormData',
POST_DATA: 'postData',
POST_DATA_ERROR: 'postDataError',
POST_DATA_SUCCESS: 'postDataSuccess',
DATA_STORED: 'dataStored',
DATA_STORED_LOADED: 'dataStoredLoaded',
DATA_STORED_FORGOTTEN: 'dataStoredForgotten',
}
function reducer(state, action) {
switch (action.type) {
case ACTIONS.SET_FORM_DATA:
return {
...state,
formData: {
...state.formData,
...action.payload,
},
formDataChanged: [
...state.formDataChanged,
...Object.keys(action.payload),
],
}
case ACTIONS.POST_DATA:
return {
...state,
postData: true,
postDataError: null,
postDataSuccess: null,
}
case ACTIONS.POST_DATA_ERROR:
return {
...state,
postData: false,
postDataError: action.payload,
postDataSuccess: null,
}
case ACTIONS.POST_DATA_SUCCESS:
return {
...state,
formData: {
...state.formData,
},
booking: { ...action.payload },
postData: false,
postDataError: null,
postDataSuccess: true,
}
case ACTIONS.DATA_STORED_LOADED:
return {
...state,
dataStoredLoaded: true,
formData: {
...state.formData,
...action.payload,
},
}
case ACTIONS.DATA_STORED_FORGOTTEN:
return {
...state,
dataStored: undefined,
dataStoredLoaded: undefined,
formData: { ...initialState.formData },
}
case ACTIONS.DATA_STORED:
return {
...state,
dataStored: action.payload,
}
default:
throw new Error(`Unkown Action type ${action.type}`)
}
}
function debugReducer(state, action) {
console.debug('applying action', action)
const newState = reducer(state, action)
console.debug(newState)
return newState
}
const initialState = {
postData: false,
postDataError: null,
postDataSuccess: null,
formData: {
startDate: '',
endDate: '',
purpose: '',
org: '',
destination: '',
name: '',
email: '',
street: '',
zip: '',
city: '',
},
formDataChanged: [],
}
async function createBooking(formData) {
const response = await fetch('/api/booking', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
referrerPolicy: 'no-referrer',
body: JSON.stringify(formData),
})
return response.json()
}
export default function WizardStore({ children }) {
const [state, dispatch] = useReducer(debugReducer, initialState)
useEffect(() => {
const data = loadBookingData()
if (data !== null) {
dispatch({ type: ACTIONS.DATA_STORED_LOADED, payload: data })
}
}, [])
const onChangeEvent = (event) => {
const { name, value } = event.target
dispatch({
type: ACTIONS.SET_FORM_DATA,
payload: { [name]: value },
})
}
const onChange = (data) => {
dispatch({
type: ACTIONS.SET_FORM_DATA,
payload: data,
})
}
const onSubmit = async () => {
dispatch({ type: ACTIONS.POST_DATA })
try {
const booking = await createBooking(state.formData)
dispatch({ type: ACTIONS.POST_DATA_SUCCESS, payload: booking })
} catch (error) {
console.error(error)
dispatch({ type: ACTIONS.POST_DATA_ERROR, payload: error.message })
}
}
const storeData = (value) => {
if (value) {
storeBookingData(state.booking)
}
dispatch({ type: ACTIONS.DATA_STORED, payload: value })
}
const forgetData = () => {
clearBookingData()
dispatch({ type: ACTIONS.DATA_STORED_FORGOTTEN })
}
return (
<WizardContext.Provider
value={{
state,
dispatch,
onChangeEvent,
onChange,
onSubmit,
storeData,
forgetData,
}}
>
{children}
</WizardContext.Provider>
)
}

View File

@@ -0,0 +1,134 @@
import React, { useContext, useState, useRef, useEffect } from 'react'
import useSWR from 'swr'
import { WizardContext } from './context/wizardStore'
import { DateUtils } from 'react-day-picker'
import DayPickerInput from 'react-day-picker/DayPickerInput'
import Required from './required'
import { dateFormatBackend } from '../../helpers/date'
import { getNextSmaller, getNextBigger } from '../../helpers/array'
import MomentLocaleUtils, {
formatDate,
parseDate,
} from 'react-day-picker/moment'
import 'moment/locale/de'
const fetcher = (path) => fetch(path).then((r) => r.json())
export default function DateSelect() {
const { state, onChange } = useContext(WizardContext)
const [range, setRange] = useState({
form: state.startDate && new Date(state.startDate),
to: state.endDate && new Date(state.endDate),
})
const { from, to } = range
const { data: daysBooked, error: fetchBookedOnError } = useSWR(
'/api/daysbooked',
fetcher
)
const prevBookedDay = getNextSmaller(
daysBooked,
dateFormatBackend(from || to)
)
const nextBookedDay = getNextBigger(daysBooked, dateFormatBackend(from || to))
const fromRef = useRef()
const toRef = useRef()
function dayBooked(day) {
return daysBooked && daysBooked.includes(dateFormatBackend(day))
}
function dayDisabled(day) {
return (
DateUtils.isPastDay(day) ||
dayBooked(day) ||
(prevBookedDay && day < new Date(prevBookedDay)) ||
(nextBookedDay && day > new Date(nextBookedDay)) ||
day < from
)
}
useEffect(() => {
toRef.current?.getInput().focus()
}, [from])
useEffect(() => {
onChange({ startDate: from?.toISOString(), endDate: to?.toISOString() })
}, [from, to])
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 (
<div className="fsw">
<div className="fs">
<label className="flabel">
Datum <Required />
</label>
<DayPickerInput
ref={fromRef}
inputProps={{ className: 'input-text' }}
value={from}
placeholder="Von"
formatDate={formatDate}
parseDate={parseDate}
dayPickerProps={{
locale: 'de',
localeUtils: MomentLocaleUtils,
className: 'datepicker',
disabledDays,
modifiers,
numberOfMonths: 1,
}}
onDayChange={(from) => setRange({ ...range, from })}
/>
{' - '}
<DayPickerInput
ref={toRef}
inputProps={{ className: 'input-text', disabled: !from }}
value={to}
placeholder="Bis"
formatDate={formatDate}
parseDate={parseDate}
dayPickerProps={{
locale: 'de',
localeUtils: MomentLocaleUtils,
className: 'datepicker',
selectedDays: [from, { from, to }],
disabledDays,
modifiers,
numberOfMonths: 1,
month: from,
fromMonth: from,
}}
onDayChange={(to) => setRange({ ...range, to })}
/>
<button onClick={() => setRange({})} className="ibtn">
<svg className="w-full" viewBox="0 0 352 512">
<path
fill="currentColor"
d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"
></path>
</svg>
</button>
</div>
</div>
)
}

View File

@@ -0,0 +1,93 @@
import React, { useContext } from 'react'
import Link from 'next/link'
import WizardStore, { WizardContext } from './context/wizardStore'
import DateSelect from './dateSelect'
import Reason from './reason'
import Contact from './contact'
//import Driver from './driver'
function WizardInternal() {
const { onSubmit, state, forgetData, storeData } = useContext(WizardContext)
const {
postData,
postDataSuccess,
postDataError,
dataStoredLoaded,
dataStored,
booking,
} = state
if (postDataSuccess) {
return (
<>
<h3>Vielen Dank für die Buchungsanfrage!</h3>
<p>Nach Prüfung bestätigen wir die Buchung bald per E-Mail!</p>
<p>
<Link href={`/booking/${booking.uuid}`}>
<a className="link">Buchungstatus einsehen</a>
</Link>
</p>
{!dataStoredLoaded && typeof dataStored !== 'boolean' && (
<>
<p>
Sollen die eingegebenen Daten in <strong>Deinem Browser</strong>{' '}
für die nächste Buchung gespeichert werden?
</p>
<button onClick={() => storeData(true)} className="btn btn-blue">
Ja, bitte speichern
</button>
<button
onClick={() => storeData(false)}
className="btn btn-grey ml-2"
>
Nein danke
</button>
</>
)}
{dataStored === true && (
<p>Ok, die Daten wurden für die nächste Buchung gespeichert.</p>
)}
</>
)
}
return (
<form
className="w-full max-w-lg"
onSubmit={(event) => {
event.preventDefault()
onSubmit()
}}
>
{dataStoredLoaded && (
<p className="my-12">
Gespeicherte Daten wurden aus Deinem Browser geladen.{' '}
<a className="link" onClick={forgetData} href="">
Daten wieder vergessen
</a>
</p>
)}
<DateSelect />
<Reason />
<Contact />
<div>{postDataError}</div>
<div>
<button type="submit" disabled={postData} className="btn btn-blue">
{postData ? 'Speichern...' : 'Absenden'}
</button>
</div>
</form>
)
}
export default function Wizard() {
return (
<WizardStore>
<WizardInternal />
</WizardStore>
)
}

View File

@@ -0,0 +1,59 @@
import React, { useContext } from 'react'
import { WizardContext } from './context/wizardStore'
import Required from './required'
export default function Contact() {
const { state, onChangeEvent } = useContext(WizardContext)
const { formDataChanged } = state
const { purpose, destination, org } = state.formData
return (
<>
<div className="fsw">
<div className="fs">
<label className="flabel">
Zweck der Fahrt <Required />
</label>
<input
type="text"
name="purpose"
value={purpose}
onChange={onChangeEvent}
required
className={`input-text ${
formDataChanged.includes('purpose') && 'input-changed'
}`}
/>
</div>
</div>
<div className="fsw">
<div className="fs">
<label className="flabel">
Ziel der Fahrt <Required />
</label>
<input
type="text"
name="destination"
value={destination}
onChange={onChangeEvent}
required
className="input-text"
/>
</div>
</div>
<div className="fsw">
<div className="fs">
<label className="flabel">Verein</label>
<input
type="text"
name="org"
value={org}
onChange={onChangeEvent}
className="input-text"
/>
</div>
</div>
</>
)
}

View File

@@ -0,0 +1,4 @@
import React from 'react'
const Required = () => <span>*</span>
export default Required