diff --git a/@app/client/src/pages/admin/event/update/[id]/index.tsx b/@app/client/src/pages/admin/event/update/[id]/index.tsx index ce1be1708..56991c7a3 100644 --- a/@app/client/src/pages/admin/event/update/[id]/index.tsx +++ b/@app/client/src/pages/admin/event/update/[id]/index.tsx @@ -1,3 +1,4 @@ +import { useMemo } from "react" import { AdminLayout, EventForm, @@ -108,6 +109,9 @@ const Admin_UpdateEvent: NextPage = () => { }) const { data, fetching, error, stale } = query const event = data?.event + // EventForm resets its fields whenever initialValues changes, so a new + // object on every render (e.g. on a locale switch) would discard edits + const initialValues = useMemo(() => constructInitialValues(event), [event]) // If event is not found redirect to index if (!fetching && !error && !stale && !event) { @@ -126,7 +130,7 @@ const Admin_UpdateEvent: NextPage = () => { data={data} eventId={eventId} formRedirect="/admin/event/list" - initialValues={constructInitialValues(event)} + initialValues={initialValues} type="update" /> diff --git a/@app/client/src/translations/en/events.json b/@app/client/src/translations/en/events.json index 89617606a..4a70a1315 100644 --- a/@app/client/src/translations/en/events.json +++ b/@app/client/src/translations/en/events.json @@ -11,7 +11,6 @@ "eventCategoryCreationFailed": "Creating event category failed", "eventCreateFailed": "Creating event failed", "eventUpdateFailed": "Updating event failed", - "formTabErrors": "Other errors", "mustProvideEventQuota": "Must provide at least one quota for the event" }, "eventName": "Event", @@ -19,6 +18,7 @@ "eventSignupNotOpen": "Event signup is not open", "forms": { "eventTime": "Event time", + "fillRequiredToSave": "Fill in all required fields to save", "highlightEvent": "Highlighted event", "isDraft": "Draft", "isHighlighted": "Highlighted", diff --git a/@app/client/src/translations/fi/events.json b/@app/client/src/translations/fi/events.json index d0f131eeb..8a9ae7529 100644 --- a/@app/client/src/translations/fi/events.json +++ b/@app/client/src/translations/fi/events.json @@ -11,7 +11,6 @@ "eventCategoryCreationFailed": "Tapahtumakategorian luonti epäonnistui", "eventCreateFailed": "Tapahtuman luonti epäonnistui", "eventUpdateFailed": "Tapahtuman päivittäminen epäonnistui", - "formTabErrors": "Muut virheet", "mustProvideEventQuota": "Tapahtumalle on määritettävä vähintään yksi kiintiö" }, "eventName": "Tapahtuma", @@ -19,6 +18,7 @@ "eventSignupNotOpen": "Tapahtuman ilmoittautuminen ei ole auki", "forms": { "eventTime": "Tapahtuman ajankohta", + "fillRequiredToSave": "Täytä kaikki pakolliset kentät tallentaaksesi", "highlightEvent": "Korostettu tapahtuma", "isDraft": "Luonnos", "isHighlighted": "Korostettu", diff --git a/@app/client/src/translations/se/events.json b/@app/client/src/translations/se/events.json index d30ac729a..5e9be3df6 100644 --- a/@app/client/src/translations/se/events.json +++ b/@app/client/src/translations/se/events.json @@ -11,7 +11,6 @@ "eventCategoryCreationFailed": "Det gick inte att skapa händelsekategori", "eventCreateFailed": "Det gick inte att skapa händelse", "eventUpdateFailed": "Uppdateringen misslyckades", - "formTabErrors": "Andra fel", "mustProvideEventQuota": "Måste tillhandahålla minst en kvot för evenemanget" }, "eventName": "Händelse", @@ -19,6 +18,7 @@ "eventSignupNotOpen": "Händelseregistreringen är inte öppen", "forms": { "eventTime": "Händelsetid", + "fillRequiredToSave": "Fyll i alla obligatoriska fält för att spara", "highlightEvent": "Markerad händelse", "isDraft": "Utkast", "isHighlighted": "Markerad", diff --git a/@app/components/src/Editor/index.tsx b/@app/components/src/Editor/index.tsx index 226b89c0a..d1a4e20fd 100644 --- a/@app/components/src/Editor/index.tsx +++ b/@app/components/src/Editor/index.tsx @@ -86,7 +86,16 @@ export const Editor: React.FC = ({ ] // See https://github.com/ianstormtaylor/slate/pull/4540#issuecomment-951380551 - editor.children = newValue + if (editor.children !== newValue) { + editor.children = newValue + // The document was replaced from outside the editor (language switch or + // form reset); drop the cursor, pending marks and undo history that + // point into the previous one. Edits made in the editor come back as the + // same array, so typing doesn't reset anything. + editor.selection = null + editor.marks = null + editor.history = { undos: [], redos: [] } + } useEffect(() => { const textValue = newValue.map((val) => serialize(val)).join("") diff --git a/@app/components/src/EventForm/EventFormFooter.tsx b/@app/components/src/EventForm/EventFormFooter.tsx new file mode 100644 index 000000000..13aac21e7 --- /dev/null +++ b/@app/components/src/EventForm/EventFormFooter.tsx @@ -0,0 +1,227 @@ +import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react" +import { LeftOutlined, RightOutlined } from "@ant-design/icons" +import { css } from "@emotion/css" +import { + Alert, + Button, + Form, + Space, + Switch, + theme, + Tooltip, + Typography, +} from "antd" + +import { ErrorAlert, useTranslation } from "../." + +interface FooterTab { + key: string + label: string +} + +interface EventFormFooterProps { + type: "update" | "create" + // Tabs the arrow buttons move between, in order + tabs: FooterTab[] + activeTab: string + setActiveTab: (tab: string) => void + // Hides the footer without unmounting it, so the isDraft field stays + // registered in the form while another tab is open + hidden: boolean + canSubmit: boolean + // What still keeps the form from being saved + missingFields: string[] | null + formSubmitting: boolean + formError: any + // Field errors from the last save attempt + submitErrors: string[] | null + isDraft: boolean + setIsDraft: Dispatch> +} + +// Bar fixed to the bottom of the window with tab navigation on the left +// and the draft switch and submit button on the right +export const EventFormFooter: React.FC = ({ + type, + tabs, + activeTab, + setActiveTab, + hidden, + canSubmit, + missingFields, + formSubmitting, + formError, + submitErrors, + isDraft, + setIsDraft, +}) => { + const { t } = useTranslation("events") + const { token } = theme.useToken() + const index = tabs.findIndex(({ key }) => key === activeTab) + const previous = tabs[index - 1] + const next = tabs[index + 1] + + // The bar is fixed to the window, so it follows the placeholder left in + // its place for its horizontal position (the admin side menu collapses), + // and the placeholder takes the bar's height so the end of the form can + // be scrolled above it + const placeholder = useRef(null) + const bar = useRef(null) + const [box, setBox] = useState({ left: 0, width: 0 }) + const [height, setHeight] = useState(0) + + useEffect(() => { + if (!placeholder.current || !bar.current) return + const updateBox = () => { + const rect = placeholder.current?.getBoundingClientRect() + if (rect) setBox({ left: rect.left, width: rect.width }) + } + const boxObserver = new ResizeObserver(updateBox) + boxObserver.observe(placeholder.current) + const heightObserver = new ResizeObserver(([entry]) => + setHeight(entry.borderBoxSize?.[0]?.blockSize ?? 0) + ) + heightObserver.observe(bar.current) + window.addEventListener("resize", updateBox) + return () => { + boxObserver.disconnect() + heightObserver.disconnect() + window.removeEventListener("resize", updateBox) + } + }, []) + + return ( + + ) +} diff --git a/@app/components/src/EventForm/MainTab.tsx b/@app/components/src/EventForm/MainTab.tsx index dc3fd23ad..fa3de887f 100644 --- a/@app/components/src/EventForm/MainTab.tsx +++ b/@app/components/src/EventForm/MainTab.tsx @@ -1,30 +1,151 @@ -import { Dispatch, SetStateAction } from "react" +import { Dispatch, SetStateAction, useRef, useState } from "react" import { CreateEventPageQuery, UpdateEventPageQuery } from "@app/graphql" -import { range, tailFormItemLayout } from "@app/lib" -import { Button, DatePicker, Form, Input, Row, Select, Switch } from "antd" -import dayjs from "dayjs" +import { range } from "@app/lib" +import { css } from "@emotion/css" +import { DatePicker, Form, Input, InputRef, Select, Space, Switch } from "antd" +import dayjs, { Dayjs } from "dayjs" -import { Editor, ErrorAlert, FileUpload, useTranslation } from "../." +import { Editor, FileUpload, useTranslation } from "../." import { FormValues } from "." +import type { RangePickerProps } from "antd/es/date-picker" import type { UploadFile } from "antd/lib/upload/interface" const { Option } = Select const { Group } = Input const { RangePicker } = DatePicker +// Typing a time can store a half-filled range, so require both ends +const bothEndsSet = (_: unknown, value?: Array) => + value?.[0] && value?.[1] ? Promise.resolve() : Promise.reject() + +const timeUnits = ["hour", "minute", "second"] as const +// Hide the time scroll columns and put the time boxes on the OK button's row +const timePopup = css` + .ant-picker-time-panel { + display: none; + } + && .ant-picker-footer { + display: flex; + align-items: center; + } + && .ant-picker-footer-extra { + flex: 1; + border-bottom: none; + } +` + +// RangePicker whose time is typed into HH : mm : ss boxes below the calendar +// instead of picked from scroll columns +const TimeRangePicker: React.FC = ({ + value, + onChange, + ...props +}) => { + const [active, setActive] = useState(0) + // Dates picked in the open popup before OK is pressed + const [pending, setPending] = useState(null) + // Digits typed so far in the focused box, shown unpadded while typing + const [draft, setDraft] = useState<{ box: number; text: string } | null>(null) + const boxes = useRef>([]) + const current = pending ?? value + const date = current?.[active] + + function typeDigits(i: number, input: string) { + if (!date) return + const unit = timeUnits[i] + const text = input.replace(/\D/g, "").slice(0, 2) + setDraft({ box: i, text }) + if (!text) return + + const max = unit === "hour" ? 23 : 59 + const next = [...(current ?? [null, null])] as [Dayjs | null, Dayjs | null] + next[active] = date[unit](Math.min(Number(text), max)) + setPending(next) + onChange?.(next, ["", ""]) + + // Two digits fill the box: continue with the next one + if (text.length === 2 && i < timeUnits.length - 1) focusBox(i + 1) + } + + // Deferred so the boxes are enabled before they get focus + function focusBox(i: number) { + setTimeout(() => boxes.current[i]?.focus()) + } + + return ( + ( + + {timeUnits.map((unit, i) => ( + { + boxes.current[i] = el + }} + data-cy={`eventform-input-time-${unit}`} + disabled={!date} + inputMode="numeric" + maxLength={2} + size="small" + style={{ width: 40, textAlign: "center" }} + value={ + draft?.box === i + ? draft.text + : date + ? String(date[unit]()).padStart(2, "0") + : "" + } + onBlur={() => setDraft(null)} + onChange={(e) => typeDigits(i, e.target.value)} + onFocus={(e) => { + setDraft(null) + e.target.select() + }} + onKeyDown={(e) => { + if (e.key === "ArrowRight" && i < timeUnits.length - 1) { + e.preventDefault() + focusBox(i + 1) + } else if (e.key === "ArrowLeft" && i > 0) { + e.preventDefault() + focusBox(i - 1) + } + }} + /> + ))} + + )} + value={value} + onCalendarChange={(dates, _, info) => { + const changed = info.range === "end" ? 1 : 0 + let next = dates + // A start moved past the end clears the end (order={false} keeps + // the picker from swapping them instead) + if (changed === 0 && dates?.[0] && dates[1]?.isBefore(dates[0])) { + next = [dates[0], null] + onChange?.(next, ["", ""]) + } + setPending(next) + // A date was picked: continue with its hours + if (next?.[changed]) focusBox(0) + }} + onChange={onChange} + onFocus={(_, info) => setActive(info.range === "end" ? 1 : 0)} + onOpenChange={(open) => !open && setPending(null)} + /> + ) +} + interface MainTabProps { type: "update" | "create" formValues: FormValues data: CreateEventPageQuery | UpdateEventPageQuery - formSubmitting: boolean selectedLanguages: string[] setSelectedLanguages: Dispatch> - isDraft: boolean - setIsDraft: Dispatch> - tabErrors: string[] | null - formError: any supportedLanguages: Array | null | undefined } @@ -35,11 +156,6 @@ export const MainTab: React.FC = (props) => { formValues, selectedLanguages, setSelectedLanguages, - isDraft, - setIsDraft, - formError, - tabErrors, - formSubmitting, supportedLanguages, } = props const { t, lang } = useTranslation("events") @@ -227,13 +343,13 @@ export const MainTab: React.FC = (props) => { name="eventTime" rules={[ { - type: "array", required: true, message: t("forms.rules.event.provideEventTime"), + validator: bothEndsSet, }, ]} > - = (props) => { name="registrationTime" rules={[ { - type: "array", required: true, message: t("forms.rules.event.provideRegistrationTime"), + validator: bothEndsSet, }, ]} > - @@ -279,48 +399,6 @@ export const MainTab: React.FC = (props) => { maxCount={1} /> - - setIsDraft(checked)} - /> - - {formError && ( - - - - )} - {tabErrors ? ( - - {tabErrors?.map((e, i) => ( - - {e} - - ))} - - ) : null} - - - ) } diff --git a/@app/components/src/EventForm/QuestionsTab.tsx b/@app/components/src/EventForm/QuestionsTab.tsx index 44e33658f..d1c435c57 100644 --- a/@app/components/src/EventForm/QuestionsTab.tsx +++ b/@app/components/src/EventForm/QuestionsTab.tsx @@ -45,6 +45,9 @@ type QuestionData = { interface QuestionsTabProps { form: FormInstance selectedLanguages: string[] + // Only compared by memo: without it a language switch doesn't re-render + // the tab, which leaves its texts and field messages in the old language + lang: string } const colSpan = { md: { span: 6 }, sm: { span: 12 }, xs: { span: 24 } } @@ -303,7 +306,11 @@ export const QuestionsTab: React.FC = memo( key={key} id={key} index={index} - move={move} + move={(from, to) => { + move(from, to) + // Re-read questions so type and options follow the moved row + forceUpdate() + }} > @@ -370,7 +377,10 @@ export const QuestionsTab: React.FC = memo( remove(name)} + onClick={() => { + remove(name) + forceUpdate() + }} /> diff --git a/@app/components/src/EventForm/QuotasTab.tsx b/@app/components/src/EventForm/QuotasTab.tsx index ffe3398ef..f433493b5 100644 --- a/@app/components/src/EventForm/QuotasTab.tsx +++ b/@app/components/src/EventForm/QuotasTab.tsx @@ -15,12 +15,16 @@ import { Draggable } from "../Draggable" interface QuotasTabProps { initialValues?: any selectedLanguages: string[] + // Only compared by memo: without it a language switch doesn't re-render + // the tab, which leaves its texts and field messages in the old language + lang: string } export const QuotasTab: React.FC = memo( ({ initialValues, selectedLanguages }) => { const [hasOpenQuota, setHasOpenQuota] = useState(false) const { t } = useTranslation("events") + const form = Form.useFormInstance() useEffect(() => { if (initialValues?.openQuotaSize > 0) setHasOpenQuota(true) @@ -32,11 +36,13 @@ export const QuotasTab: React.FC = memo( name="quotas" rules={[ { + // An event always needs a quota; an open quota alone isn't enough. + // The message is set on the rule, not in the rejection, so it's + // in the current language like the other fields' messages + message: t("errors.mustProvideEventQuota"), validator: async (_, quotas) => { - if ((!quotas || quotas?.length < 1) && !hasOpenQuota) { - return Promise.reject( - new Error(t("errors.mustProvideEventQuota")) - ) + if (!quotas || quotas?.length < 1) { + return Promise.reject() } }, }, @@ -141,13 +147,24 @@ export const QuotasTab: React.FC = memo( setHasOpenQuota(val)} + onChange={(val) => { + setHasOpenQuota(val) + // A switched off open quota shouldn't keep its size, or the + // event would still get one when saved. A switched on one + // starts empty, so it has to be given a size before saving + if (!val) form.setFieldValue("openQuotaSize", 0) + else if (!form.getFieldValue("openQuotaSize")) { + form.setFieldValue("openQuotaSize", null) + } + }} /> = (props) => { const { formRedirect, data, initialValues, type, eventId } = props const { languages, slug, isDraft: initialIsDraft } = initialValues || {} @@ -94,7 +97,7 @@ export const EventForm: React.FC = (props) => { ) // Translations, router, urql - const { t } = useTranslation("events") + const { t, lang } = useTranslation("events") const router = useRouter() // Handling form values, errors and submission @@ -104,11 +107,61 @@ export const EventForm: React.FC = (props) => { const [activeTab, setActiveTab] = useState(TAB.General) const [formSubmitting, setFormSubmitting] = useState(false) const [formError, setFormError] = useState(null) - const [tabErrors, setTabErrors] = useState(null) const [isDraft, setIsDraft] = useState(type === "create" || initialIsDraft) const [selectedLanguages, setSelectedLanguages] = useState( initialSelectedLanguages || [] ) + // Errors that keep the form from being saved, null until first checked + const [missingFields, setMissingFields] = useState(null) + // Field errors found when saving, shown in the footer since the fields + // they belong to can be on another tab + const [submitErrors, setSubmitErrors] = useState(null) + const tabsRef = useRef(null) + + // Saving stays disabled until every field passes validation. useWatch also + // fires on setFieldsValue, which onValuesChange doesn't. The check also + // runs again on a language switch, which keeps the form's values, so the + // reasons are given in the new language + const watchedValues = Form.useWatch([], form) + const [recheck, setRecheck] = useState(0) + useEffect(() => { + let cancelled = false + form + .validateFields({ validateOnly: true }) + .then(() => !cancelled && setMissingFields([])) + .catch(({ errorFields, outOfDate }) => { + if (cancelled) return + // Another validation (e.g. a field validating itself on change) + // started after this one, which rejects this one without errors + // whatever the fields hold. Check again once it has started + if (outOfDate) { + setTimeout(() => !cancelled && setRecheck((n) => n + 1)) + return + } + setMissingFields( + uniq(errorFields.flatMap(({ errors }) => errors as string[])) + ) + }) + return () => { + cancelled = true + } + }, [form, watchedValues, recheck, lang]) + + // The save errors were given in the previous language + useEffect(() => { + setSubmitErrors(null) + setFormError(null) + }, [lang]) + + const changeTab = useCallback((tab: string) => { + setActiveTab(tab as TAB) + // Bring the top of the new tab into view when the footer was used + // further down the page + const top = tabsRef.current?.getBoundingClientRect().top + if (top !== undefined && top < 0) { + tabsRef.current?.scrollIntoView({ behavior: "smooth" }) + } + }, []) // Mutations const eventMutation = @@ -130,7 +183,6 @@ export const EventForm: React.FC = (props) => { async (values) => { setFormSubmitting(true) setFormError(null) - setTabErrors(null) try { const { name, @@ -142,7 +194,7 @@ export const EventForm: React.FC = (props) => { headerImageFile: headerFile, } = values - if (!formQuotas && (openQuotaSize < 1 || !openQuotaSize)) { + if (!formQuotas?.length) { throw new Error(t("errors.mustProvideEventQuota")) } @@ -222,41 +274,16 @@ export const EventForm: React.FC = (props) => { [mutation, formRedirect, router, t, type, eventId] ) - const debounceTabErrors = useMemo( - () => - debounce(() => { - let tabErrors = form - .getFieldsError() - .filter( - ({ name, errors }) => - ["quotas", "questions"].includes(name[0] as string) && - errors.length > 0 - ) - .map(({ errors }) => errors[0]) - .filter((e) => !!e) - - if (tabErrors.length > 0) { - setTabErrors(uniq(tabErrors)) - } - }, 500), - [form] - ) - - const handleFieldsChange = useCallback(async () => { - // Filters form errors that relate to quotas or questions - // in order to display them on the general tab - debounceTabErrors() - }, [debounceTabErrors]) + const tabLabels: Record = { + [TAB.General]: t("admin:events.tabs.generalInfo"), + [TAB.Quotas]: t("admin:events.tabs.quotas"), + [TAB.Questions]: t("admin:events.tabs.questions"), + } const mainTabProps = { type, data, - isDraft, formValues, - setIsDraft, - formError, - tabErrors, - formSubmitting, selectedLanguages, setSelectedLanguages, supportedLanguages: languagesLower, @@ -273,36 +300,47 @@ export const EventForm: React.FC = (props) => { openQuotaSize: 0, ...initialValues, }} - onFieldsChange={handleFieldsChange} onFinish={handleSubmit} - onValuesChange={(_, values) => setFormValues(values)} + onFinishFailed={({ errorFields }) => + setSubmitErrors(uniq(errorFields.flatMap(({ errors }) => errors))) + } + onValuesChange={(_, values) => { + setFormValues(values) + setSubmitErrors(null) + }} > +
, }, { key: TAB.Quotas, - label: t("admin:events.tabs.quotas"), + label: tabLabels[TAB.Quotas], forceRender: true, children: ( ), }, { key: TAB.Questions, - label: t("admin:events.tabs.questions"), + label: tabLabels[TAB.Questions], forceRender: true, children: ( - + ), }, ...(type === "update" @@ -325,16 +363,21 @@ export const EventForm: React.FC = (props) => { }, ] : []), - { - key: TAB.Email, - label: t("admin:events.tabs.email"), - // Only render the email tab body when it is the active tab to - // avoid spamming renderEmailTemplate queries on every form change. - children: - activeTab === TAB.Email ? ( - - ) : null, - }, + // The email preview tab is only available in development + ...(process.env.NODE_ENV !== "production" + ? [ + { + key: TAB.Email, + label: t("admin:events.tabs.email"), + // Only render the email tab body when it is the active tab to + // avoid spamming renderEmailTemplate queries on every form change. + children: + activeTab === TAB.Email ? ( + + ) : null, + }, + ] + : []), ]} tabBarExtraContent={{ right: ( @@ -364,6 +407,20 @@ export const EventForm: React.FC = (props) => { }} onChange={(tab) => setActiveTab(tab as TAB)} /> + 0} + formError={formError} + formSubmitting={formSubmitting} + hidden={!FORM_TABS.includes(activeTab)} + isDraft={isDraft} + missingFields={missingFields} + setActiveTab={changeTab} + setIsDraft={setIsDraft} + submitErrors={submitErrors} + tabs={FORM_TABS.map((key) => ({ key, label: tabLabels[key] }))} + type={type} + /> ) } diff --git a/@app/components/src/SharedLayout.tsx b/@app/components/src/SharedLayout.tsx index da145e6e2..6b3bb3623 100644 --- a/@app/components/src/SharedLayout.tsx +++ b/@app/components/src/SharedLayout.tsx @@ -324,7 +324,13 @@ export function SharedLayout({ {sider ? sider : null} - + {/* Without the footer the content fills the rest of the window, so + the light body background doesn't show below short pages */} + {renderChildren({ error, stale,