Merge branch 'main' into feat/dtf-web
Prettier Format Check / format-check (pull_request) Canceled after 0s

This commit is contained in:
2026-10-29 16:18:30 +01:00
9 changed files with 152 additions and 89 deletions
+77 -41
View File
@@ -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<Record<keyof typeof form, z.core.$ZodIssue[]>> = $state({});
let isValid = $derived(Object.values(validation).every((issues) => !issues?.length));
let isSubmitting = $state(false);
let submitState = $state<ActionableState>("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 @@
</script>
<section class="wrapper md:flex md:flex-row">
<form class="mb-20 flex max-w-167 flex-col gap-10" onsubmit={handleSubmit}>
<form class="mb-20 flex max-w-167 flex-col gap-10" onsubmit={(event) => event.preventDefault()}>
<div class="flex flex-col gap-4">
<Title level={1} variant="section">
{$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")}
</Title>
<CategorySelect max={2} options={categories} onChange={handleCategories} />
<Title level={2} variant="subsection">
{$t("pages.project.create.categories.title")}
</Title>
<p
class={twJoin(
"transition-all duration-300 ease-in-out",
@@ -219,7 +241,16 @@
{$t("pages.project.create.categories.subtitle")}
{/if}
</p>
<CategorySelect max={2} options={themes} onChange={handleThemes} />
<CategorySelect max={2} options={categories} onChange={handleCategories} />
</div>
<div class="flex flex-col gap-4">
<Title level={2} variant="subsection">
{$t("pages.project.create.themes.title")}
</Title>
<p class="text-black transition-all duration-300 ease-in-out">
{$t("pages.project.create.themes.subtitle")}
</p>
<CategorySelect max={1} options={themes} onChange={handleThemes} />
</div>
<div class="flex flex-col gap-4">
<Title level={2} variant="subsection">
@@ -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"
@@ -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);
}
}
@@ -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}
+7 -1
View File
@@ -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": {
+7 -1
View File
@@ -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": {
+7 -1
View File
@@ -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": {
+5 -10
View File
@@ -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);
---
+1 -1
View File
@@ -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 {
+20 -15
View File
@@ -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"],
});
}
}
});