import { Dispatch, SetStateAction, useCallback, useState } from 'react'; import { createEvent } from './api'; import { toggleBit } from './bits'; import { green, lightgrey } from './colors'; import { IGroup } from './Group'; import UIButton from './UIButton'; import UIDateInput from './UIDateInput'; import UIDatetimeInput from './UIDatetimeInput'; import UIPlacesAutocomplete from './UIPlacesAutocomplete'; import UISecondaryBox from './UISecondaryBox'; import UITextInput from './UITextInput'; import useToggle from './useToggle'; const noop = () => {}; const DAY_NAMES = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; function DaysOfWeekSelector({ daysOfWeek, update, disabled = false, }: { daysOfWeek: number; update: Dispatch>; disabled?: boolean; }) { const toggleDayOfWeek = useCallback( function (idx: 1 | 2 | 3 | 4 | 5 | 6 | 7) { update((daysOfWeek) => toggleBit(daysOfWeek, idx)); }, [update] ); return (
{DAY_NAMES.map((name, idx) => { const mask = 0b1000_0000 >> (idx + 1); const active = (daysOfWeek & mask) !== 0; return (
{ if (!disabled) { toggleDayOfWeek( // @ts-ignore idx + 1 ); } }} key={name} > {name.charAt(0)}
); })}
); } export default function EventCreator({ group }: { group: IGroup }) { const [name, setName] = useState(''); const [startTime, setStartTime] = useState(null); const [endTime, setEndTime] = useState(null); const [placeId, setPlaceId] = useState(null); const [creating, setCreating] = useState(false); const [createdEventId, setCreatedEventId] = useState(-1); const [recurring, toggleRecurring] = useToggle(false); const [daysOfWeek, setDaysOfWeek] = useState(0); const [endDate, setEndDate] = useState(null); const durationIsNegative = endTime && startTime && endTime.getTime() < startTime.getTime(); const buttonEnabled = name.length > 0 && startTime != null && endTime != null && placeId != null && (!recurring || daysOfWeek || endDate !== null) && !durationIsNegative && !creating; const onClickedCreateEvent = useCallback(() => { if (!creating) { if (startTime === null) { console.warn( 'Tried to create an event where the start time was unspecified.' ); return; } if (placeId === null) { console.warn( 'Tried tro create an event where the placeId was unspecified.' ); return; } const duration = endTime !== null ? (endTime.getTime() - startTime.getTime()) / 60 : 0; setCreating(true); createEvent({ name, startTime, duration, endDate, groupId: group.id, placeId, daysOfWeek, }) .then(({ id }) => { setCreatedEventId(id); }) .finally(() => setCreating(false)); } }, [ creating, name, startTime, endTime, group.id, placeId, daysOfWeek, endDate, ]); return (

Create Event

{group.name}

Name
Start time
End time
Location { setPlaceId(placeId); }} /> Recurring event {recurring && ( <> Days of week Date of last occurence )} {durationIsNegative && ( The start time can't be after the end time. )} {createdEventId === -1 ? ( {creating ? 'Creating event' : 'Create event'} ) : ( Created {name}. )}
); }