From 818849caaefc351fa4173b061f7e5fd32065af4f Mon Sep 17 00:00:00 2001 From: Aino Kotiranta Date: Sat, 17 Oct 2026 11:50:10 +0300 Subject: [PATCH 1/6] fix: keep question options with their question when reordering or removing The questions tab renders each row's type and options from a snapshot of the form values taken when the tab renders. Form.List's move and remove only re-render the list, so rows kept the type and options of the question previously at that index. Force a re-render after both, as the other structural edits in the tab already do. Co-Authored-By: Claude Opus 5.5 --- @app/components/src/EventForm/QuestionsTab.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/@app/components/src/EventForm/QuestionsTab.tsx b/@app/components/src/EventForm/QuestionsTab.tsx index 44e33658f..d4e2dff99 100644 --- a/@app/components/src/EventForm/QuestionsTab.tsx +++ b/@app/components/src/EventForm/QuestionsTab.tsx @@ -303,7 +303,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 +374,10 @@ export const QuestionsTab: React.FC = memo( remove(name)} + onClick={() => { + remove(name) + forceUpdate() + }} /> From 33cfc82763d0b8ad224b819c1e8b8d009a765ba4 Mon Sep 17 00:00:00 2001 From: Aino Kotiranta Date: Sat, 17 Oct 2026 12:21:46 +0300 Subject: [PATCH 2/6] fix: reset editor state when switching description language The description editor reuses one Slate editor for every language and only swaps editor.children on switch. The cursor, pending marks and undo history still pointed into the previous language's document, so a cursor past the end of the new document crashed the editor and lost the text, and undo replayed the other language's edits. Clear them on switch. Co-Authored-By: Claude Opus 5.5 --- @app/components/src/Editor/index.tsx | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/@app/components/src/Editor/index.tsx b/@app/components/src/Editor/index.tsx index 226b89c0a..ad65832b9 100644 --- a/@app/components/src/Editor/index.tsx +++ b/@app/components/src/Editor/index.tsx @@ -80,6 +80,18 @@ export const Editor: React.FC = ({ const renderElement = useCallback((props) => , []) const renderLeaf = useCallback((props) => , []) + const changeEditorLanguage = useCallback( + (language: string) => { + // Each language is its own document; drop the cursor, pending marks + // and undo history that point into the previous one + editor.selection = null + editor.marks = null + editor.history = { undos: [], redos: [] } + setEditorLanguage(language) + }, + [editor] + ) + const isReadOnly = selectedLanguages?.length === 0 const includedLocales = [ ...selectedLanguages.filter((lang) => lang !== editorLanguage), @@ -220,7 +232,7 @@ export const Editor: React.FC = ({ Date: Sat, 17 Oct 2026 12:38:43 +0300 Subject: [PATCH 3/6] fix: keep unsaved event edits on locale switch and guard editor document swaps The update event page built initialValues as a new object on every render, and EventForm resets its fields whenever initialValues changes. Any re-render, such as switching the site locale, discarded unsaved edits and replaced the description while the editor's cursor still pointed into the old document, crashing Slate. Memoize initialValues on the event. Move the editor's cursor, marks and history reset from the language menu to wherever the document is swapped, so any outside replacement is safe. Co-Authored-By: Claude Opus 5.5 --- .../pages/admin/event/update/[id]/index.tsx | 6 ++++- @app/components/src/Editor/index.tsx | 25 ++++++++----------- 2 files changed, 16 insertions(+), 15 deletions(-) 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/components/src/Editor/index.tsx b/@app/components/src/Editor/index.tsx index ad65832b9..d1a4e20fd 100644 --- a/@app/components/src/Editor/index.tsx +++ b/@app/components/src/Editor/index.tsx @@ -80,25 +80,22 @@ export const Editor: React.FC = ({ const renderElement = useCallback((props) => , []) const renderLeaf = useCallback((props) => , []) - const changeEditorLanguage = useCallback( - (language: string) => { - // Each language is its own document; drop the cursor, pending marks - // and undo history that point into the previous one - editor.selection = null - editor.marks = null - editor.history = { undos: [], redos: [] } - setEditorLanguage(language) - }, - [editor] - ) - const isReadOnly = selectedLanguages?.length === 0 const includedLocales = [ ...selectedLanguages.filter((lang) => lang !== editorLanguage), ] // 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("") @@ -232,7 +229,7 @@ export const Editor: React.FC = ({ Date: Sat, 17 Oct 2026 14:21:02 +0300 Subject: [PATCH 4/6] feat: type event and registration times into boxes instead of scrolling Replace the time scroll columns in the event time and registration period pickers with HH : mm : ss boxes next to the OK button. Picking a date selects the hours box, two digits advance to the next box and the arrow keys move between boxes. The registration period defaults to 12:00:00 - 23:59:59, and moving a start past its end clears the end instead of swapping them. Both ends are required, since typing a time can store a half-filled range. Co-Authored-By: Claude Opus 5.5 --- @app/components/src/EventForm/MainTab.tsx | 154 +++++++++++++++++++++- 1 file changed, 147 insertions(+), 7 deletions(-) diff --git a/@app/components/src/EventForm/MainTab.tsx b/@app/components/src/EventForm/MainTab.tsx index dc3fd23ad..0bea6b5c2 100644 --- a/@app/components/src/EventForm/MainTab.tsx +++ b/@app/components/src/EventForm/MainTab.tsx @@ -1,19 +1,155 @@ -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 { css } from "@emotion/css" +import { + Button, + DatePicker, + Form, + Input, + InputRef, + Row, + Select, + Space, + Switch, +} from "antd" +import dayjs, { Dayjs } from "dayjs" import { Editor, ErrorAlert, 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 @@ -227,13 +363,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, }, ]} > - From 6b87b58f949e0b0c0cb3459c9116e15ef7e22959 Mon Sep 17 00:00:00 2001 From: Aino Kotiranta Date: Sat, 17 Oct 2026 14:49:10 +0300 Subject: [PATCH 5/6] feat: hide email preview tab in event form outside development Co-Authored-By: Claude Opus 5.5 --- @app/components/src/EventForm/index.tsx | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/@app/components/src/EventForm/index.tsx b/@app/components/src/EventForm/index.tsx index 5cb3f92ad..7666ddc22 100644 --- a/@app/components/src/EventForm/index.tsx +++ b/@app/components/src/EventForm/index.tsx @@ -325,16 +325,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: ( From 71525ae07050f76273bfc098d43fbcb2c2b4de30 Mon Sep 17 00:00:00 2001 From: Aino Kotiranta Date: Sat, 17 Oct 2026 17:17:18 +0300 Subject: [PATCH 6/6] feat: sticky event form footer with tab navigation and save controls Move the save as draft switch and the create/update button into a bar fixed to the bottom of the window on the general, quotas and questions tabs, with arrows for moving between the tabs. Saving stays disabled until the form is valid; hovering the hint lists what is missing. - Require at least one quota row; an open quota alone is not enough - Reset the open quota size when it is switched off - Re-render the quotas and questions tabs on a language switch so their texts and validation messages follow it - Fill the window below the header on pages without the site footer Co-Authored-By: Claude Opus 5.5 --- @app/client/src/translations/en/events.json | 2 +- @app/client/src/translations/fi/events.json | 2 +- @app/client/src/translations/se/events.json | 2 +- .../src/EventForm/EventFormFooter.tsx | 227 ++++++++++++++++++ @app/components/src/EventForm/MainTab.tsx | 68 +----- .../components/src/EventForm/QuestionsTab.tsx | 3 + @app/components/src/EventForm/QuotasTab.tsx | 27 ++- @app/components/src/EventForm/index.tsx | 138 +++++++---- @app/components/src/SharedLayout.tsx | 8 +- 9 files changed, 360 insertions(+), 117 deletions(-) create mode 100644 @app/components/src/EventForm/EventFormFooter.tsx 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/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 0bea6b5c2..fa3de887f 100644 --- a/@app/components/src/EventForm/MainTab.tsx +++ b/@app/components/src/EventForm/MainTab.tsx @@ -1,21 +1,11 @@ import { Dispatch, SetStateAction, useRef, useState } from "react" import { CreateEventPageQuery, UpdateEventPageQuery } from "@app/graphql" -import { range, tailFormItemLayout } from "@app/lib" +import { range } from "@app/lib" import { css } from "@emotion/css" -import { - Button, - DatePicker, - Form, - Input, - InputRef, - Row, - Select, - Space, - Switch, -} from "antd" +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 "." @@ -154,13 +144,8 @@ 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 } @@ -171,11 +156,6 @@ export const MainTab: React.FC = (props) => { formValues, selectedLanguages, setSelectedLanguages, - isDraft, - setIsDraft, - formError, - tabErrors, - formSubmitting, supportedLanguages, } = props const { t, lang } = useTranslation("events") @@ -419,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 d4e2dff99..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 } } 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" @@ -369,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,