diff --git a/src/components/create/CreateProjectForm.svelte b/src/components/create/CreateProjectForm.svelte index 0d332d2f..2f1a0413 100644 --- a/src/components/create/CreateProjectForm.svelte +++ b/src/components/create/CreateProjectForm.svelte @@ -6,9 +6,9 @@ type Category, type ApiProjectsPostData, type Territory, + type Theme, apiCategoriesIdOrSlugGetUrl, apiProjectsPost, - type Theme, apiThemesIdOrSlugGetUrl, } from "../../openapi/client"; import { client } from "../../openapi/client/client.gen"; @@ -18,9 +18,11 @@ zCreateProjectForm, zProjectCampaignRelease, } from "../../validation/projectValidation"; - import Spinner from "../icons/status/Spinner.svelte"; - import Button from "../library/buttons/Button.svelte"; + import ActionableButton, { + type ActionableState, + } from "../library/buttons/ActionableButton.svelte"; import BaseCard from "../library/cards/BaseCard.svelte"; + import Toast from "../library/feedback/Toast.svelte"; import CategorySelect from "../library/inputs/CategorySelect.svelte"; import DateInput from "../library/inputs/DateInput.svelte"; import TerritoryInput from "../library/inputs/TerritoryInput.svelte"; @@ -44,7 +46,8 @@ let validation: Partial> = $state({}); let isValid = $derived(Object.values(validation).every((issues) => !issues?.length)); - let isSubmitting = $state(false); + let submitState = $state("actionable"); + let showError = $state(false); function validate(field: keyof typeof form) { const result = zCreateProjectForm.shape[field].safeParse(form[field]); @@ -71,6 +74,10 @@ return $t("pages.project.create.validation.titleBadFormat"); } + if (issue.code === "too_small" && field === "subtitle") { + return $t("pages.project.create.validation.subtitleMissing"); + } + if (issue.code === "too_small" && field === "categories") { return $t("pages.project.create.validation.categoriesNotEnough", { min: String(issue.minimum), @@ -91,27 +98,18 @@ }); } + function toIris(items: { id?: string }[], url: string) { + return items.map(({ id }) => client.buildUrl({ url, path: { idOrSlug: String(id) } })); + } + function handleCategories(categories: Category[]) { - const category = categories[0]; - - form.categories = [ - client.buildUrl({ - url: apiCategoriesIdOrSlugGetUrl, - path: { idOrSlug: String(category.id) }, - }), - ]; - + // @ts-expect-error toIris may have fewer, but it gets validated + form.categories = toIris(categories, apiCategoriesIdOrSlugGetUrl); validate("categories"); } function handleThemes(themes: Theme[]) { - form.themes = themes.map((t) => { - return client.buildUrl({ - url: apiThemesIdOrSlugGetUrl, - path: { idOrSlug: String(t.id) }, - }); - }); - + form.themes = toIris(themes, apiThemesIdOrSlugGetUrl); validate("themes"); } @@ -129,10 +127,33 @@ validation["calendar"] = result.error?.issues ?? []; } - async function handleSubmit(e: SubmitEvent) { - e.preventDefault(); + /** + * Places API constraint violations under their fields, anything unrecognized goes to a toast. + */ + function handleViolations(violations: { propertyPath?: string; message?: string }[]) { + let unhandled = violations.length === 0; + for (const { propertyPath, message = "" } of violations) { + if (propertyPath === "title" && /already in use/i.test(message)) { + validation.title = [ + { + code: "custom", + path: ["title"], + message: "pages.project.create.validation.titleInUse", + input: form.title, + }, + ]; + } else { + unhandled = true; + } + } + + showError = unhandled; + } + + async function submit() { validation = {}; + showError = false; const result = zCreateProjectForm.safeParse(form); @@ -143,11 +164,9 @@ validation[field] = [...(validation[field] ?? []), issue]; } - return; + throw new Error("Invalid project form"); } - isSubmitting = true; - const { data: project, error } = await apiProjectsPost({ baseUrl: "/api/relay", headers: { "Content-Language": $locale }, @@ -156,9 +175,14 @@ }); if (error) { - console.error(error); - isSubmitting = false; - return; + if ("violations" in error) { + handleViolations(error.violations ?? []); + } else { + showError = true; + } + + // Lets the button go back to actionable so the user can retry + throw new Error("Project creation failed", { cause: error }); } window.location.href = `/project/${project.id}/edit`; @@ -166,7 +190,7 @@
-
+ event.preventDefault()}>
{$t("pages.project.create.title")} @@ -194,6 +218,8 @@ <div class="relative"> <TextArea bind:value={form.subtitle} + onInput={() => validate("subtitle")} + error={getValidationMessage("subtitle")} helperText={$t("pages.project.create.description.subtitlePrompt")} placeholder={$t("pages.project.create.description.subtitlePlaceholder")} /> @@ -203,10 +229,6 @@ <Title level={2} variant="subsection"> {$t("Choose a shelf")} - - - {$t("pages.project.create.categories.title")} -

- + +

+
+ + {$t("pages.project.create.themes.title")} + +

+ {$t("pages.project.create.themes.subtitle")} +

+
@@ -251,14 +282,19 @@ error={getValidationMessage("calendar")} /> </div> - <Button type="submit" disabled={!isValid || isSubmitting}> - {#if isSubmitting} - <Spinner /> - {:else} - {$t("pages.project.create.submit")} - {/if} - </Button> + <ActionableButton + type="submit" + action={submit} + bind:state={submitState} + disabled={!isValid || submitState !== "actionable"} + class="w-fit" + > + {$t("pages.project.create.submit")} + </ActionableButton> </form> + <Toast floating variant="error" bind:showToast={showError}> + {$t("system.error.unknown")} + </Toast> <div class="ml-auto"> <BaseCard class="border-grey flex h-full max-h-126.5 w-full max-w-109.25 flex-col bg-white" diff --git a/src/components/library/buttons/ActionableButton.svelte b/src/components/library/buttons/ActionableButton.svelte index 7a6c4af3..28a6671e 100644 --- a/src/components/library/buttons/ActionableButton.svelte +++ b/src/components/library/buttons/ActionableButton.svelte @@ -40,11 +40,15 @@ state = "loading"; try { await action(); - } finally { - state = "actioned"; - if (autoreset !== undefined) { - setTimeout(() => (state = "actionable"), autoreset); - } + } catch (err) { + // A failed action can be retried, so it never reaches the actioned state + state = "actionable"; + console.error(err); + return; + } + state = "actioned"; + if (autoreset !== undefined) { + setTimeout(() => (state = "actionable"), autoreset); } } diff --git a/src/components/library/inputs/CategorySelect.svelte b/src/components/library/inputs/CategorySelect.svelte index 7b3ca49f..d5b161c5 100644 --- a/src/components/library/inputs/CategorySelect.svelte +++ b/src/components/library/inputs/CategorySelect.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import { t } from "../../../i18n/store"; import CategoryOption from "../tags/Category.svelte"; import type { Category, Theme } from "../../../openapi/client"; @@ -53,20 +54,24 @@ </script> <div> - <fieldset - class="m-0 flex flex-wrap gap-4 border-0 p-0" - aria-describedby={error ? "category-error" : undefined} - > - {#each options as option} - <CategoryOption - type={calcTagType(option)} - disabled={calcTagDisabled(option)} - onclick={() => handleClick(option)} - > - {option.name} - </CategoryOption> - {/each} - </fieldset> + {#if options.length === 0} + <p class="text-content">{$t("common.noOptions")}</p> + {:else} + <fieldset + class="m-0 flex flex-wrap gap-4 border-0 p-0" + aria-describedby={error ? "category-error" : undefined} + > + {#each options as option} + <CategoryOption + type={calcTagType(option)} + disabled={calcTagDisabled(option)} + onclick={() => handleClick(option)} + > + {option.name} + </CategoryOption> + {/each} + </fieldset> + {/if} {#if error} <p id="category-error" class="mt-2 ml-4 text-xs text-red-600" role="alert"> {error} diff --git a/src/i18n/locales/ca.json b/src/i18n/locales/ca.json index b3d38a65..d2236c2b 100644 --- a/src/i18n/locales/ca.json +++ b/src/i18n/locales/ca.json @@ -1114,6 +1114,10 @@ "title": "Quina categoria s'ajusta al teu projecte?", "subtitle": "(Pots triar un màxim de 2)" }, + "themes": { + "title": "Quin tema s'ajusta al teu projecte?", + "subtitle": "(Opcional, en pots triar un)" + }, "address": { "title": "Quina és l'adreça del projecte?", "subtitle": "Cerca i selecciona l'adreça completa del projecte. Això ens ajuda a ubicar la teva iniciativa.", @@ -1134,7 +1138,9 @@ "titleBadFormat": "El títol ha de contenir almenys una lletra.", "categoriesNotEnough": "Has de seleccionar almenys {{ min }} categoria/es.", "territoryMissing": "Has d'especificar un lloc.", - "releaseMissing": "Has d'especificar una data de llançament aproximada" + "releaseMissing": "Has d'especificar una data de llançament aproximada", + "titleInUse": "Ja existeix un projecte amb aquest títol.", + "subtitleMissing": "Has d'afegir una breu descripció del projecte." } }, "view": { diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 57bebf2c..c1e8ac55 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -1115,6 +1115,10 @@ "title": "Which category fits your project?", "subtitle": "(You can choose a maximum of 2)" }, + "themes": { + "title": "Which theme fits your project?", + "subtitle": "(Optional, you can choose one)" + }, "address": { "title": "What is the project address?", "subtitle": "Search for and select the project's full address. This helps us locate your initiative.", @@ -1135,7 +1139,9 @@ "titleBadFormat": "The title must contain at least one letter.", "categoriesNotEnough": "You must select at least {{ min }} category(ies).", "territoryMissing": "You must specify a location.", - "releaseMissing": "You must specify an approximate launch date" + "releaseMissing": "You must specify an approximate launch date", + "titleInUse": "A project with this title already exists.", + "subtitleMissing": "You must add a brief project description." } }, "view": { diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 3139c611..bb8d6a69 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -1116,6 +1116,10 @@ "title": "¿Qué categoría se ajusta a tu proyecto?", "subtitle": "(Puedes elegir un máximo de 2)" }, + "themes": { + "title": "¿Qué tema se ajusta a tu proyecto?", + "subtitle": "(Opcional, puedes elegir uno)" + }, "address": { "title": "¿Cuál es la dirección del proyecto?", "subtitle": "Busca y selecciona la dirección completa del proyecto. Esto nos ayuda a ubicar tu iniciativa.", @@ -1136,7 +1140,9 @@ "titleBadFormat": "El título debe contener al menos una letra.", "categoriesNotEnough": "Debes seleccionar al menos {{ min }} categoría(s).", "territoryMissing": "Debes especificar un lugar.", - "releaseMissing": "Debes especificar una fecha de salida aproximada" + "releaseMissing": "Debes especificar una fecha de salida aproximada", + "titleInUse": "Ya existe un proyecto con este título.", + "subtitleMissing": "Debes añadir una breve descripción del proyecto." } }, "view": { diff --git a/src/pages/[...locale]/create/project.astro b/src/pages/[...locale]/create/project.astro index 2e62e4f1..ba709e73 100644 --- a/src/pages/[...locale]/create/project.astro +++ b/src/pages/[...locale]/create/project.astro @@ -14,18 +14,13 @@ if (!session) { return goto("/register", { query: { callback: "/create/project" } }); } -const { data: categoriesRaw } = await withoutCache(() => - apiCategoriesGetCollection({ - headers: { "Accept-Language": langs }, - }), +const [{ data: categoriesRaw }, { data: themesRaw }] = await withoutCache(() => + Promise.all([ + apiCategoriesGetCollection({ headers: { "Accept-Language": langs } }), + apiThemesGetCollection({ headers: { "Accept-Language": langs } }), + ]), ); const categories = toCollectionItems<Category>(categoriesRaw); - -const { data: themesRaw } = await withoutCache(() => - apiThemesGetCollection({ - headers: { "Accept-Language": langs }, - }), -); const themes = toCollectionItems<Theme>(themesRaw); --- diff --git a/src/utils/extractId.ts b/src/utils/extractId.ts index c1a5b258..c973bfde 100644 --- a/src/utils/extractId.ts +++ b/src/utils/extractId.ts @@ -1,7 +1,7 @@ /** * Extracts the last numeric ID from an IRI by walking its path segments backwards. * - * @param iri - A string representing an IRI (Internationalized Resource Identifier) + * @param iri - A string representing an IRI * @returns The last numeric segment as a string, or null if not found */ export function extractId(iri?: string): string | null { diff --git a/src/validation/projectValidation.ts b/src/validation/projectValidation.ts index f448e251..95ad3947 100644 --- a/src/validation/projectValidation.ts +++ b/src/validation/projectValidation.ts @@ -14,19 +14,24 @@ export const zProjectCampaignRelease = z params: { max: CAMPAIGN_MAX_END_DATE }, }); -export const zCreateProjectForm = zProjectProjectCreationDto.superRefine((form, ctx) => { - if (!form.calendar?.release) { - return; - } - - const release = zProjectCampaignRelease.safeParse(new Date(form.calendar.release)); - - if (!release.success) { - for (const issue of release.error.issues) { - ctx.addIssue({ - ...issue, - path: ["calendar"], - }); +// The API rejects a blank subtitle, the generated schema accepts it +export const zCreateProjectForm = zProjectProjectCreationDto + .extend({ + subtitle: z.string().trim().min(1), + }) + .superRefine((form, ctx) => { + if (!form.calendar?.release) { + return; } - } -}); + + const release = zProjectCampaignRelease.safeParse(new Date(form.calendar.release)); + + if (!release.success) { + for (const issue of release.error.issues) { + ctx.addIssue({ + ...issue, + path: ["calendar"], + }); + } + } + });