Merge branch 'main' into feat/dtf-web
This commit is contained in:
+4
-1
@@ -27,13 +27,16 @@ openapi-ts*.log
|
||||
# vscode setting folder
|
||||
.vscode/
|
||||
|
||||
# Claude Code
|
||||
# AI skills files
|
||||
CLAUDE.md
|
||||
AGENTS.md
|
||||
|
||||
#Other
|
||||
yarn.lock
|
||||
.wrangler/
|
||||
|
||||
./graphify-out
|
||||
|
||||
.pnpm-store
|
||||
*storybook.log
|
||||
storybook-static
|
||||
|
||||
@@ -99,6 +99,13 @@ export default defineConfig({
|
||||
|
||||
routeRules,
|
||||
|
||||
/**
|
||||
* Shiki colours code blocks with inline `style` attributes, which the CSP below is not
|
||||
* meant to rely on. No Markdown here has code blocks, so highlighting is off. If that
|
||||
* changes, use `"prism"` (class-based) plus a Prism theme stylesheet.
|
||||
*/
|
||||
markdown: { syntaxHighlight: false },
|
||||
|
||||
security: {
|
||||
/**
|
||||
* On a server-rendered page Astro sends this as a `content-security-policy` response
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS proposed_campaigns (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
date_created INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
|
||||
date_updated INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS proposed_campaign_slots (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
proposal_id INTEGER NOT NULL REFERENCES proposed_campaigns(id) ON DELETE CASCADE,
|
||||
tab TEXT NOT NULL CHECK (tab IN ('ending-soon', 'most-successful')),
|
||||
position INTEGER NOT NULL,
|
||||
project_id TEXT NOT NULL,
|
||||
UNIQUE(proposal_id, tab, position)
|
||||
);
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Site-wide settings edited from /admin/customize, one JSON document per key
|
||||
-- (e.g. 'footer'). A missing key means the built-in defaults in code apply.
|
||||
-- Timestamps are milliseconds (Date.getTime()), matching the repository layer.
|
||||
CREATE TABLE
|
||||
IF NOT EXISTS site_settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
date_updated INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE IF NOT EXISTS theme_colors (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
light_colors TEXT NOT NULL DEFAULT '{}',
|
||||
dark_colors TEXT NOT NULL DEFAULT '{}',
|
||||
date_updated INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Header logo managed from /admin/customize/logo
|
||||
-- Timestamps are milliseconds (Date.getTime()), matching the repository layer.
|
||||
-- The header shows the most recently uploaded logo; when the table is empty it
|
||||
-- falls back to the built-in logo.
|
||||
CREATE TABLE
|
||||
IF NOT EXISTS header_logo (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
media_url TEXT NOT NULL,
|
||||
media_type TEXT NOT NULL,
|
||||
alt_text TEXT NOT NULL DEFAULT 'Goteo',
|
||||
date_created INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
||||
);
|
||||
@@ -48,6 +48,7 @@
|
||||
"bits-ui": "^2.18.1",
|
||||
"chart.js": "^4.5.1",
|
||||
"csrf": "^3.1.0",
|
||||
"dequal": "^2.0.3",
|
||||
"dexie": "^4.4.2",
|
||||
"dinero.js": "^2.0.2",
|
||||
"dotenv": "^17.4.2",
|
||||
@@ -57,6 +58,8 @@
|
||||
"marked": "^18.0.6",
|
||||
"media-icons": "^1.1.5",
|
||||
"murmurhash-js": "^1.0.0",
|
||||
"observable-slim": "^0.2.2",
|
||||
"polished": "^4.3.1",
|
||||
"stdnum": "^1.12.6",
|
||||
"svelte": "^5.56.6",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
|
||||
Generated
+157
-223
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,93 @@
|
||||
import { ActionError, defineAction } from "astro:actions";
|
||||
import { z } from "zod";
|
||||
|
||||
import { labels } from "../i18n/locales";
|
||||
import { footerRepository } from "../repositories/footer";
|
||||
import { FOOTER_SECTIONS, FOOTER_SOCIAL_NETWORKS } from "../types/footer";
|
||||
|
||||
import type { ActionAPIContext } from "astro:actions";
|
||||
|
||||
const defaultLocale = import.meta.env.PUBLIC_DEFAULT_LANGUAGE as keyof typeof labels;
|
||||
|
||||
// Site paths, anchors and http(s)/mailto URLs only: anything else (javascript:, data:)
|
||||
// would end up as a clickable link on every page.
|
||||
const href = z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((value) => {
|
||||
if (value.startsWith("/") || value.startsWith("#")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
return ["http:", "https:", "mailto:"].includes(new URL(value).protocol);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, "pages.admin.customize.footer.errors.invalidUrl");
|
||||
|
||||
// The default locale is required, so every visitor gets a text through the fallback.
|
||||
const localizedText = z
|
||||
.object(
|
||||
Object.fromEntries(
|
||||
Object.keys(labels).map((locale) => [locale, z.string().trim().optional()]),
|
||||
),
|
||||
)
|
||||
.refine((text) => !!text[defaultLocale], "pages.admin.customize.footer.errors.missingText");
|
||||
|
||||
const link = z.object({ label: localizedText, href });
|
||||
|
||||
const partner = z.object({
|
||||
src: z.string().trim().min(1, "pages.admin.customize.footer.errors.missingImage"),
|
||||
alt: z.string().trim().min(1, "system.constraint.text.notEmpty"),
|
||||
href: z.union([z.literal(""), href]).optional(),
|
||||
});
|
||||
|
||||
const footerSchema = z.object({
|
||||
hidden: z.record(z.enum(FOOTER_SECTIONS), z.boolean()),
|
||||
partnerGroups: z.array(z.object({ title: localizedText, partners: z.array(partner) })),
|
||||
navColumns: z.array(z.object({ title: localizedText, links: z.array(link) })),
|
||||
legalLinks: z.array(link),
|
||||
social: z.array(z.object({ network: z.enum(FOOTER_SOCIAL_NETWORKS), href })),
|
||||
});
|
||||
|
||||
/**
|
||||
* Actions are posted to /_actions/*, which the /admin firewall rule does not
|
||||
* match, so the role has to be checked here.
|
||||
* @param context The action context
|
||||
*/
|
||||
function assertAdmin({ locals: { session, t } }: ActionAPIContext) {
|
||||
if (!session?.user.roles?.includes("ROLE_ADMIN")) {
|
||||
throw new ActionError({
|
||||
code: "FORBIDDEN",
|
||||
message: t("pages.admin.customize.footer.errors.forbidden"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const saveFooter = defineAction({
|
||||
input: z.object({ config: z.string() }),
|
||||
handler: async ({ config }, context) => {
|
||||
assertAdmin(context);
|
||||
|
||||
const { t } = context.locals;
|
||||
|
||||
let parsed: unknown;
|
||||
|
||||
try {
|
||||
parsed = JSON.parse(config);
|
||||
} catch {
|
||||
parsed = undefined;
|
||||
}
|
||||
|
||||
const result = footerSchema.safeParse(parsed);
|
||||
|
||||
if (!result.success) {
|
||||
const [issue] = result.error.issues;
|
||||
|
||||
throw new ActionError({ code: "BAD_REQUEST", message: t(issue.message) });
|
||||
}
|
||||
|
||||
await footerRepository.save(result.data);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { ActionError, defineAction } from "astro:actions";
|
||||
import { z } from "zod";
|
||||
|
||||
import { headerLogoRepository } from "../repositories/headerLogo";
|
||||
|
||||
const LOGO_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp"] as const;
|
||||
|
||||
const mediaUrl = z.string().refine((value) => {
|
||||
if (value.startsWith("/")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(value);
|
||||
|
||||
return url.protocol === "http:" || url.protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, "system.constraint.text.expectedUrl");
|
||||
|
||||
const logoInputSchema = z.object({
|
||||
mediaUrl,
|
||||
mediaType: z.enum(LOGO_MEDIA_TYPES),
|
||||
altText: z.string().trim().min(1, "system.constraint.text.notEmpty"),
|
||||
});
|
||||
|
||||
/**
|
||||
* The header is public, but its management lives under /admin/customize. Actions
|
||||
* are posted to /_actions/*, which the /admin firewall rule does not match, so
|
||||
* the role has to be checked here.
|
||||
*/
|
||||
function assertAdmin(session: App.Locals["session"], t: App.Locals["t"]): void {
|
||||
if (!session?.user.roles?.includes("ROLE_ADMIN")) {
|
||||
throw new ActionError({
|
||||
code: "FORBIDDEN",
|
||||
message: t("pages.admin.customize.logo.errors.forbidden"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const createHeaderLogo = defineAction({
|
||||
accept: "form",
|
||||
input: logoInputSchema,
|
||||
handler: async (input, context) => {
|
||||
const { session, t } = context.locals;
|
||||
|
||||
assertAdmin(session, t);
|
||||
|
||||
await headerLogoRepository.create({
|
||||
mediaUrl: input.mediaUrl,
|
||||
mediaType: input.mediaType,
|
||||
altText: input.altText,
|
||||
dateCreated: new Date(),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const getHeaderLogoData = defineAction({
|
||||
handler: async (_input, context) => {
|
||||
const { session, t } = context.locals;
|
||||
|
||||
assertAdmin(session, t);
|
||||
|
||||
return {
|
||||
logos: await headerLogoRepository.getAll(),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const deleteHeaderLogo = defineAction({
|
||||
accept: "form",
|
||||
input: z.object({
|
||||
id: z.coerce.number().int().positive(),
|
||||
}),
|
||||
handler: async (input, context) => {
|
||||
const { session, t } = context.locals;
|
||||
|
||||
assertAdmin(session, t);
|
||||
|
||||
await headerLogoRepository.delete(input.id);
|
||||
},
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import { deleteBanner, saveBanner } from "./banners";
|
||||
import { saveBlogPost, setBlogPostPublished } from "./blog";
|
||||
import { saveFeaturedUsers } from "./featuredUsers";
|
||||
import { saveFooter } from "./footer";
|
||||
import { createHeaderLogo, deleteHeaderLogo, getHeaderLogoData } from "./headerLogo";
|
||||
import { createHomeHero, deleteHomeHero, getHomeHeroData, updateHomeHero } from "./hero";
|
||||
import { deleteHighlights, saveHighlights } from "./highlights";
|
||||
import { payment } from "./payment";
|
||||
@@ -10,8 +12,10 @@ import {
|
||||
updateReviewAreaRisk,
|
||||
updateReviewProjectStatus,
|
||||
} from "./projectReview";
|
||||
import { saveProposedCampaigns } from "./proposedCampaigns";
|
||||
import { updatePublicProfile } from "./publicProfile";
|
||||
import { register } from "./register";
|
||||
import { resetThemeColors, saveThemeColors } from "./themeColors";
|
||||
|
||||
export const server = {
|
||||
register,
|
||||
@@ -21,15 +25,22 @@ export const server = {
|
||||
saveBlogPost,
|
||||
setBlogPostPublished,
|
||||
createHomeHero,
|
||||
createHeaderLogo,
|
||||
deleteHeaderLogo,
|
||||
deleteHomeHero,
|
||||
getHeaderLogoData,
|
||||
getHomeHeroData,
|
||||
updateHomeHero,
|
||||
saveHighlights,
|
||||
deleteHighlights,
|
||||
saveFeaturedUsers,
|
||||
saveFooter,
|
||||
updatePublicProfile,
|
||||
updatePersonalProfile,
|
||||
updateReviewAreaRisk,
|
||||
updateReviewProjectStatus,
|
||||
sendReviewAreaComment,
|
||||
saveProposedCampaigns,
|
||||
saveThemeColors,
|
||||
resetThemeColors,
|
||||
};
|
||||
|
||||
@@ -1,25 +1,35 @@
|
||||
import { ActionError, defineAction } from "astro:actions";
|
||||
import { z } from "zod";
|
||||
|
||||
import { setSession } from "../auth/session.ts";
|
||||
import {
|
||||
apiUsersIdOrHandleGet,
|
||||
apiUsersIdorganizationPatch,
|
||||
apiUsersIdPatch,
|
||||
apiUsersIdpersonGet,
|
||||
apiUsersIdpersonPatch,
|
||||
type UserUserUpdationDto,
|
||||
type OrganizationJsonMergePatch,
|
||||
type PersonJsonMergePatch,
|
||||
type UserUserUpdationDtoJsonMergePatch,
|
||||
} from "../openapi/client/index.ts";
|
||||
import { zPersonalProfileForm } from "../validation/personalProfileValidation.ts";
|
||||
|
||||
const TERRITORY_FIELDS = ["country", "subLvl1", "subLvl2"];
|
||||
|
||||
/**
|
||||
* Saves the private part of the profile: the `Person` record, the `Territory` on the `User` and
|
||||
* the identity row (avatar, bio, social networks) that this section shares with the public one.
|
||||
* Saves the private part of the profile: the `Person` and `Organization` records, the `Territory`
|
||||
* and the private flags on the `User`, and the identity row (avatar, bio, social networks) that this section shares with the public one.
|
||||
* The email is deliberately left out: changing it needs a confirmation flow the API does not
|
||||
* expose here.
|
||||
*/
|
||||
export const updatePersonalProfile = defineAction({
|
||||
accept: "json",
|
||||
input: zPersonalProfileForm,
|
||||
handler: async (input, context) => {
|
||||
input: z.object({
|
||||
form: zPersonalProfileForm,
|
||||
// Fields the user edited since the last save, tracked by the form
|
||||
changed: z.array(zPersonalProfileForm.keyof()),
|
||||
}),
|
||||
handler: async ({ form: input, changed: changedFields }, context) => {
|
||||
const { t, session } = context.locals;
|
||||
|
||||
if (!session) {
|
||||
@@ -33,77 +43,96 @@ export const updatePersonalProfile = defineAction({
|
||||
const headers = session.token.asHttpHeaders;
|
||||
const isOrganization = input.type === "organization";
|
||||
|
||||
try {
|
||||
const userPatch: Partial<UserUserUpdationDto> = input;
|
||||
// Only send what the user edited: the API re-validates every field it gets, and rejects
|
||||
// an unchanged handle as already in use
|
||||
const changed = new Set<string>(changedFields);
|
||||
// Switching type moves the tax id to the other record, send all of its fields
|
||||
const typeChanged = changed.has("type");
|
||||
const pick = <T extends object>(values: T, all = false) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(values).filter(([key]) => all || changed.has(key)),
|
||||
) as Partial<T>;
|
||||
const hasFields = (values: object) => Object.keys(values).length > 0;
|
||||
|
||||
if (input.country) {
|
||||
const currentTerritory = session.user.territory;
|
||||
const newTerritory = {
|
||||
try {
|
||||
const userPatch: UserUserUpdationDtoJsonMergePatch = pick({
|
||||
handle: input.handle,
|
||||
type: input.type,
|
||||
shareLocation: input.shareLocation,
|
||||
referralSource: input.referralSource || null,
|
||||
});
|
||||
|
||||
if (input.country && TERRITORY_FIELDS.some((field) => changed.has(field))) {
|
||||
userPatch.territory = {
|
||||
country: input.country,
|
||||
subLvl1: input.subLvl1 || null,
|
||||
subLvl2: input.subLvl2 || null,
|
||||
address: input.address.trim() || null,
|
||||
// The API replaces the whole Territory, keep the address this form does not edit
|
||||
address: session.user.territory?.address ?? null,
|
||||
};
|
||||
if (
|
||||
!currentTerritory ||
|
||||
currentTerritory.country !== newTerritory.country ||
|
||||
(currentTerritory.subLvl1 ?? null) !== newTerritory.subLvl1 ||
|
||||
(currentTerritory.subLvl2 ?? null) !== newTerritory.subLvl2 ||
|
||||
(currentTerritory.address ?? null) !== newTerritory.address
|
||||
) {
|
||||
userPatch.territory = newTerritory;
|
||||
}
|
||||
} else if (session.user.territory?.country) {
|
||||
// Country cleared in the form: do not send territory at all
|
||||
userPatch.territory = undefined;
|
||||
}
|
||||
|
||||
let userError: unknown;
|
||||
if (Object.keys(userPatch).length > 0) {
|
||||
if (hasFields(userPatch)) {
|
||||
const { error } = await apiUsersIdPatch({
|
||||
path: { id },
|
||||
headers,
|
||||
body: userPatch as UserUserUpdationDto,
|
||||
body: userPatch,
|
||||
});
|
||||
userError = error;
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (userError) {
|
||||
throw userError;
|
||||
const organizationPatch: OrganizationJsonMergePatch = pick(
|
||||
{
|
||||
legalName: input.legalName.trim(),
|
||||
businessName: input.businessName.trim(),
|
||||
taxId: input.taxId.trim(),
|
||||
taxIdType: input.taxIdType || null,
|
||||
legalForm: input.legalForm || null,
|
||||
publicEntity: input.publicEntity,
|
||||
},
|
||||
typeChanged,
|
||||
);
|
||||
|
||||
if (isOrganization && hasFields(organizationPatch)) {
|
||||
const { error } = await apiUsersIdorganizationPatch({
|
||||
path: { id },
|
||||
headers,
|
||||
body: organizationPatch,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
let personError: unknown;
|
||||
if (!isOrganization) {
|
||||
const currentPerson = await apiUsersIdpersonGet({ path: { id }, headers }).then(
|
||||
(r) => r.data,
|
||||
);
|
||||
const personPatch: Record<string, unknown> = {};
|
||||
const firstNameTrim = input.firstName.trim();
|
||||
if ((currentPerson?.firstName ?? "") !== firstNameTrim) {
|
||||
personPatch.firstName = firstNameTrim;
|
||||
}
|
||||
const lastNameTrim = input.lastName.trim();
|
||||
if ((currentPerson?.lastName ?? "") !== lastNameTrim) {
|
||||
personPatch.lastName = lastNameTrim;
|
||||
}
|
||||
const taxIdTrim = input.taxId.trim();
|
||||
if ((currentPerson?.taxId ?? "") !== taxIdTrim) {
|
||||
personPatch.taxId = taxIdTrim;
|
||||
}
|
||||
if (Object.keys(personPatch).length > 0) {
|
||||
const { error } = await apiUsersIdpersonPatch({
|
||||
path: { id },
|
||||
headers,
|
||||
body: personPatch as any,
|
||||
});
|
||||
personError = error;
|
||||
}
|
||||
} else {
|
||||
personError = null;
|
||||
}
|
||||
const personPatch: PersonJsonMergePatch = {
|
||||
...pick({ firstName: input.firstName.trim(), lastName: input.lastName.trim() }),
|
||||
// On organizations the tax id belongs to the Organization record
|
||||
...(!isOrganization &&
|
||||
pick(
|
||||
{
|
||||
taxId: input.taxId.trim(),
|
||||
taxIdType: input.taxIdType || null,
|
||||
birthYear: input.birthYear ? Number(input.birthYear) : null,
|
||||
gender: input.gender || null,
|
||||
},
|
||||
typeChanged,
|
||||
)),
|
||||
};
|
||||
|
||||
if (personError) {
|
||||
throw personError;
|
||||
if (hasFields(personPatch)) {
|
||||
const { error } = await apiUsersIdpersonPatch({
|
||||
path: { id },
|
||||
headers,
|
||||
body: personPatch,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// The names feed the display name, refresh the cookie so the header stays in sync
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { ActionError, defineAction } from "astro:actions";
|
||||
import { z } from "zod";
|
||||
|
||||
import { proposedCampaignsRepository } from "../repositories/proposedCampaigns";
|
||||
|
||||
export const saveProposedCampaigns = defineAction({
|
||||
accept: "json",
|
||||
input: z.object({
|
||||
"ending-soon": z.array(z.number().int().positive()),
|
||||
"most-successful": z.array(z.number().int().positive()),
|
||||
}),
|
||||
handler: async (input, context) => {
|
||||
const { session, t } = context.locals;
|
||||
|
||||
if (!session?.user.roles?.includes("ROLE_ADMIN")) {
|
||||
throw new ActionError({
|
||||
code: "FORBIDDEN",
|
||||
message: t("pages.admin.comm.banners.errors.forbidden"),
|
||||
});
|
||||
}
|
||||
|
||||
await proposedCampaignsRepository.save({
|
||||
"ending-soon": input["ending-soon"],
|
||||
"most-successful": input["most-successful"],
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ActionError, defineAction } from "astro:actions";
|
||||
import { z } from "zod";
|
||||
|
||||
import { setSession } from "../auth/session.ts";
|
||||
import { apiUsersIdOrHandleGet, apiUsersIdPatch } from "../openapi/client/index.ts";
|
||||
@@ -7,8 +8,12 @@ import { zProfileForm } from "../validation/publicProfileValidation.ts";
|
||||
|
||||
export const updatePublicProfile = defineAction({
|
||||
accept: "json",
|
||||
input: zProfileForm,
|
||||
handler: async (input, context) => {
|
||||
input: z.object({
|
||||
form: zProfileForm,
|
||||
// Fields the user edited since the last save, tracked by the form
|
||||
changed: z.array(zProfileForm.keyof()),
|
||||
}),
|
||||
handler: async ({ form: input, changed: changedFields }, context) => {
|
||||
const { t, session } = context.locals;
|
||||
|
||||
if (!session) {
|
||||
@@ -32,20 +37,23 @@ export const updatePublicProfile = defineAction({
|
||||
}),
|
||||
];
|
||||
|
||||
try {
|
||||
// User first: switching to `organization` makes the API create the Organization record
|
||||
const { error: userError } = await apiUsersIdPatch({
|
||||
path: { id },
|
||||
headers,
|
||||
body: {
|
||||
avatar: input.avatar,
|
||||
description: input.description.trim(),
|
||||
links,
|
||||
},
|
||||
});
|
||||
// Only send what the user edited: the API re-validates every field it gets
|
||||
const changed = new Set<string>(changedFields);
|
||||
const userPatch = Object.fromEntries(
|
||||
Object.entries({
|
||||
avatar: input.avatar,
|
||||
description: input.description.trim(),
|
||||
links,
|
||||
}).filter(([key]) => changed.has(key)),
|
||||
);
|
||||
|
||||
if (userError) {
|
||||
throw userError;
|
||||
try {
|
||||
if (Object.keys(userPatch).length > 0) {
|
||||
const { error } = await apiUsersIdPatch({ path: { id }, headers, body: userPatch });
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the session cookie in sync so header and profile pages show fresh data
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { ActionError, defineAction } from "astro:actions";
|
||||
import { z } from "zod";
|
||||
|
||||
import { themeColorsRepository } from "../repositories/themeColors";
|
||||
import { DARK_THEME_COLOR_TOKENS, THEME_COLOR_TOKENS, isHexColor } from "../utils/themeColors";
|
||||
|
||||
const hexColorSchema = z
|
||||
.string()
|
||||
.refine(isHexColor, "Colors must use #RRGGBB or #RRGGBBAA notation");
|
||||
|
||||
function assertAdmin(
|
||||
session: { user: { roles?: string[] } } | undefined,
|
||||
t: (key: string) => string,
|
||||
) {
|
||||
if (!session?.user.roles?.includes("ROLE_ADMIN")) {
|
||||
throw new ActionError({
|
||||
code: "FORBIDDEN",
|
||||
message: t("pages.admin.customize.colors.errors.forbidden"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const saveThemeColors = defineAction({
|
||||
accept: "json",
|
||||
input: z.object({
|
||||
lightColors: z.record(z.enum(THEME_COLOR_TOKENS), hexColorSchema),
|
||||
darkColors: z.record(z.enum(DARK_THEME_COLOR_TOKENS), hexColorSchema),
|
||||
}),
|
||||
handler: async (input, context) => {
|
||||
assertAdmin(context.locals.session, context.locals.t);
|
||||
|
||||
await themeColorsRepository.save(input.lightColors, input.darkColors);
|
||||
},
|
||||
});
|
||||
|
||||
export const resetThemeColors = defineAction({
|
||||
accept: "json",
|
||||
input: z.object({}),
|
||||
handler: async (_input, context) => {
|
||||
assertAdmin(context.locals.session, context.locals.t);
|
||||
|
||||
await themeColorsRepository.reset();
|
||||
},
|
||||
});
|
||||
+41
-1
@@ -1,5 +1,45 @@
|
||||
import { writable, type Writable } from "svelte/store";
|
||||
import { get, writable, type Writable } from "svelte/store";
|
||||
|
||||
import type { Session } from "./types";
|
||||
|
||||
export const session: Writable<Session | undefined> = writable();
|
||||
|
||||
let pendingRefresh: Promise<Session | undefined> | undefined;
|
||||
|
||||
/**
|
||||
* Re-reads the session from the server. `/api/session` refreshes an expired access
|
||||
* token before returning it, which keeps long-lived tabs signed in instead of
|
||||
* sending a token the API will reject.
|
||||
*
|
||||
* Concurrent callers share the same request: several API calls can notice the stale
|
||||
* token at once (the project preview fetches the owner and the accounting in parallel).
|
||||
*/
|
||||
export function refreshSession(): Promise<Session | undefined> {
|
||||
pendingRefresh ??= (async () => {
|
||||
try {
|
||||
const response = await fetch("/api/session", {
|
||||
headers: { Accept: "application/json" },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return get(session);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as Session | null;
|
||||
const current = data ? { ...data, expires_at: new Date(data.expires_at) } : undefined;
|
||||
|
||||
session.set(current);
|
||||
|
||||
return current;
|
||||
} catch (error) {
|
||||
console.error("Session refresh failed:", error);
|
||||
|
||||
return get(session);
|
||||
}
|
||||
})().finally(() => {
|
||||
pendingRefresh = undefined;
|
||||
});
|
||||
|
||||
return pendingRefresh;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import { locale, t } from "../../i18n/store";
|
||||
import { apiAddressesIdPatch, apiAddressesPost } from "../../openapi/client";
|
||||
import { getCountries } from "../../utils/countries";
|
||||
import { useFormDraft, restoreFields } from "../../utils/forms/useFormDraft.svelte";
|
||||
import Select from "../library/inputs/Select.svelte";
|
||||
import TextInput from "../library/inputs/TextInput.svelte";
|
||||
|
||||
@@ -18,10 +19,13 @@
|
||||
let {
|
||||
address,
|
||||
userIri,
|
||||
draftId = "address",
|
||||
}: {
|
||||
/** Address to edit. Absent, a new one is created. */
|
||||
address?: Address;
|
||||
userIri: string;
|
||||
/** Identifies the draft of this form, so two of them do not write over each other. */
|
||||
draftId?: string;
|
||||
} = $props();
|
||||
|
||||
// Seeded once: parents mount a fresh form for every address they edit.
|
||||
@@ -42,6 +46,26 @@
|
||||
|
||||
let countries = $derived(getCountries($locale));
|
||||
|
||||
/**
|
||||
* Addresses hold nothing sensitive, so all of it can be kept.
|
||||
*/
|
||||
const { restored } = useFormDraft(
|
||||
untrack(() => draftId),
|
||||
() => ({
|
||||
firstName: form.firstName,
|
||||
lastName: form.lastName,
|
||||
line1: form.line1,
|
||||
line2: form.line2,
|
||||
city: form.city,
|
||||
postCode: form.postCode,
|
||||
country: form.country,
|
||||
}),
|
||||
);
|
||||
|
||||
if (restored) {
|
||||
restoreFields(form, restored);
|
||||
}
|
||||
|
||||
/** Saves the Address. Resolves to it, or to `undefined` with the errors shown. */
|
||||
export async function save(): Promise<Address | undefined> {
|
||||
error = undefined;
|
||||
|
||||
@@ -38,34 +38,48 @@
|
||||
|
||||
function navItemClass(item: AdminSidebarItem): string {
|
||||
return twMerge(
|
||||
"hover:bg-variant1 flex content-center items-center w-fit gap-2 rounded-lg px-4 py-2 text-base font-bold whitespace-nowrap transition-colors duration-300 text-secondary",
|
||||
"hover:bg-variant1 flex h-10 items-center gap-3 rounded-lg px-3 text-base font-bold whitespace-nowrap transition-colors duration-300 text-secondary",
|
||||
isActive(item) && "bg-variant2 hover:bg-variant3",
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Desktop sidebar -->
|
||||
<aside
|
||||
class={twMerge(
|
||||
"bg-purple-soft z-30 hidden min-w-58 shrink-0 flex-col rounded-2xl py-10 pr-10 pl-5 shadow-sm lg:sticky lg:top-(--sticky-top) lg:flex lg:max-h-[calc(100vh-var(--sticky-top)-1rem)]",
|
||||
classes,
|
||||
)}
|
||||
>
|
||||
<nav class="flex min-h-0 w-full flex-1 flex-col gap-2 overflow-x-hidden overflow-y-auto">
|
||||
{#each navItems as item (item.href)}
|
||||
<a
|
||||
href={`/${$locale}${item.href}`}
|
||||
class={navItemClass(item)}
|
||||
aria-current={isActive(item) ? "page" : undefined}
|
||||
>
|
||||
{#if item.icon}
|
||||
<item.icon class="size-5 shrink-0" />
|
||||
{/if}
|
||||
<span>{$t(item.label)}</span>
|
||||
</a>
|
||||
{/each}
|
||||
</nav>
|
||||
</aside>
|
||||
<!--
|
||||
Desktop sidebar: collapsed to one letter (or icon) per item, it opens over the content
|
||||
on hover or keyboard focus. The outer box keeps the collapsed width in the layout so
|
||||
opening it never moves the page.
|
||||
-->
|
||||
<div class="relative z-30 hidden w-18 shrink-0 self-start lg:sticky lg:top-(--sticky-top) lg:block">
|
||||
<aside
|
||||
class={twMerge(
|
||||
"group bg-purple-soft absolute top-0 left-0 flex max-h-[calc(100vh-var(--sticky-top)-1rem)] w-18 flex-col overflow-hidden rounded-2xl p-3 py-6 shadow-sm transition-[width] duration-200 focus-within:w-58 hover:w-58 hover:shadow-lg",
|
||||
classes,
|
||||
)}
|
||||
>
|
||||
<nav class="flex min-h-0 w-full flex-1 flex-col gap-2 overflow-x-hidden overflow-y-auto">
|
||||
{#each navItems as item (item.href)}
|
||||
<a
|
||||
href={`/${$locale}${item.href}`}
|
||||
class={navItemClass(item)}
|
||||
aria-current={isActive(item) ? "page" : undefined}
|
||||
>
|
||||
{#if item.icon}
|
||||
<item.icon class="size-6 shrink-0" />
|
||||
{:else}
|
||||
<span aria-hidden="true" class="w-6 shrink-0 text-center">
|
||||
{$t(item.label).charAt(0)}
|
||||
</span>
|
||||
{/if}
|
||||
<span
|
||||
class="opacity-0 transition-opacity duration-200 group-focus-within:opacity-100 group-hover:opacity-100"
|
||||
>
|
||||
{$t(item.label)}
|
||||
</span>
|
||||
</a>
|
||||
{/each}
|
||||
</nav>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<svelte:window onkeydown={(event) => event.key === "Escape" && closeMobile()} />
|
||||
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
import { t } from "../../i18n/store";
|
||||
import AnnotationIcon from "../icons/Comments.svelte";
|
||||
|
||||
const { id } = $props<{ id: string }>();
|
||||
interface Props {
|
||||
id: string;
|
||||
}
|
||||
|
||||
const { id }: Props = $props();
|
||||
|
||||
let date = $state<string | null>(null);
|
||||
let time = $state<string | null>(null);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
export interface DetailsField {
|
||||
label: string;
|
||||
value: string | number | undefined;
|
||||
value?: string | number;
|
||||
/** Custom content painted instead of `value`, for fields that are not plain text. */
|
||||
snippet?: Snippet;
|
||||
/** Hover text; defaults to the value. */
|
||||
|
||||
@@ -8,6 +8,15 @@
|
||||
import Spinner from "../icons/status/Spinner.svelte";
|
||||
import Button from "../library/buttons/Button.svelte";
|
||||
|
||||
interface Props {
|
||||
endpoint?: string;
|
||||
queryParams?: Record<string, unknown>;
|
||||
filenamePrefix?: string;
|
||||
totalItems?: number;
|
||||
size?: "sm" | "md";
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
let {
|
||||
endpoint = "/v4/gateway_charges",
|
||||
queryParams = {},
|
||||
@@ -15,14 +24,7 @@
|
||||
totalItems = undefined,
|
||||
size = "sm",
|
||||
disabled = false,
|
||||
} = $props<{
|
||||
endpoint?: string;
|
||||
queryParams?: Record<string, unknown>;
|
||||
filenamePrefix?: string;
|
||||
totalItems?: number;
|
||||
size?: "sm" | "md";
|
||||
disabled?: boolean;
|
||||
}>();
|
||||
}: Props = $props();
|
||||
|
||||
const iconSize = $derived(size === "md" ? "24" : "16");
|
||||
|
||||
|
||||
@@ -15,17 +15,14 @@
|
||||
const dateRegex =
|
||||
/^(dateCreated|dateUpdated)\[(after|before|strictly_after|strictly_before)\]$/;
|
||||
|
||||
let {
|
||||
title,
|
||||
filters,
|
||||
onCloseFilter,
|
||||
resource = undefined,
|
||||
} = $props<{
|
||||
interface Props {
|
||||
title: string;
|
||||
filters?: Record<string, any>;
|
||||
onCloseFilter: (filters: Record<string, any>) => void;
|
||||
resource?: FilterResource;
|
||||
}>();
|
||||
}
|
||||
|
||||
let { title, filters, onCloseFilter, resource = undefined }: Props = $props();
|
||||
|
||||
let tags: FilterTag[] = $state([]);
|
||||
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
|
||||
import type { Gateway } from "../../openapi/client";
|
||||
|
||||
const { gateways } = $props<{
|
||||
interface Props {
|
||||
gateways: Gateway[];
|
||||
}>();
|
||||
}
|
||||
|
||||
const { gateways }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
interface Props {
|
||||
children: Snippet;
|
||||
text?: string;
|
||||
duration?: number;
|
||||
tooltipClass?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const {
|
||||
children,
|
||||
text = "¡Tooltip!",
|
||||
duration = 1000,
|
||||
tooltipClass,
|
||||
className = "",
|
||||
} = $props<{
|
||||
children: Snippet;
|
||||
text?: string;
|
||||
duration?: number;
|
||||
tooltipClass?: string;
|
||||
className?: string;
|
||||
}>();
|
||||
}: Props = $props();
|
||||
|
||||
const baseClasses =
|
||||
"text-white text-sm px-2 rounded z-[9999] backdrop-blur-sm whitespace-nowrap";
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import LanguagesDropdown from "../header/LanguagesDropdown.svelte";
|
||||
import Trash from "../icons/actions/Trash.svelte";
|
||||
import Button from "../library/buttons/Button.svelte";
|
||||
import DropdownMenu from "../library/dropdown/DropdownMenu.svelte";
|
||||
import DropdownSearch from "../library/dropdown/DropdownSearch.svelte";
|
||||
import DeleteModal from "../library/feedback/DeleteModal.svelte";
|
||||
import Title from "../library/typography/Title.svelte";
|
||||
|
||||
@@ -45,7 +45,6 @@
|
||||
|
||||
let isAddModalOpen = $state(false);
|
||||
let languageSearch = $state("");
|
||||
let candidateOptions = $state<DropdownOption[]>([]);
|
||||
let selectedLanguageOption = $state<DropdownOption[]>([]);
|
||||
let isRemoveModalOpen = $state(false);
|
||||
let isRemoveAllModalOpen = $state(false);
|
||||
@@ -61,31 +60,24 @@
|
||||
function openAddModal() {
|
||||
languageSearch = "";
|
||||
selectedLanguageOption = [];
|
||||
refreshLanguageOptions();
|
||||
isAddModalOpen = true;
|
||||
}
|
||||
|
||||
function refreshLanguageOptions(query = "") {
|
||||
function searchLanguages(query: string): DropdownOption[] {
|
||||
// Once an option is picked its label fills the search; it must not filter the list.
|
||||
const search = query.trim().toLowerCase();
|
||||
const search = query.toLowerCase();
|
||||
const selectedLabel = ALL_LANGUAGE_OPTIONS.find(
|
||||
(option) => option.id === selectedLanguageOption[0]?.id,
|
||||
)?.label.toLowerCase();
|
||||
const needle = search && search !== selectedLabel ? search : "";
|
||||
|
||||
candidateOptions = ALL_LANGUAGE_OPTIONS.filter(
|
||||
return ALL_LANGUAGE_OPTIONS.filter(
|
||||
(option) =>
|
||||
!languages.includes(option.id) &&
|
||||
(!needle ||
|
||||
option.label.toLowerCase().includes(needle) ||
|
||||
option.id.includes(needle)),
|
||||
).map((option) => ({ ...option, selected: selectedLanguageOption[0]?.id === option.id }));
|
||||
}
|
||||
|
||||
function handleAddLanguageChange(option: DropdownOption) {
|
||||
selectedLanguageOption = [option];
|
||||
languageSearch = option.label;
|
||||
refreshLanguageOptions(option.label);
|
||||
);
|
||||
}
|
||||
|
||||
function confirmAddLanguage() {
|
||||
@@ -165,16 +157,14 @@
|
||||
{$t("domain.translationLanguages.addModal.description")}
|
||||
</p>
|
||||
|
||||
<DropdownMenu
|
||||
<DropdownSearch
|
||||
variant="basic"
|
||||
singleSelect
|
||||
hasSearch
|
||||
bind:searchValue={languageSearch}
|
||||
bind:options={candidateOptions}
|
||||
search={searchLanguages}
|
||||
debounceMs={0}
|
||||
bind:value={languageSearch}
|
||||
bind:selected={selectedLanguageOption}
|
||||
onSearch={(query) => refreshLanguageOptions(query)}
|
||||
onChange={handleAddLanguageChange}
|
||||
searchPlaceholder={$t("domain.translationLanguages.addModal.searchPlaceholder")}
|
||||
placeholder={$t("domain.translationLanguages.addModal.searchPlaceholder")}
|
||||
itemClass="text-start"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { AdminSidebarItem } from "./AdminSidebar.svelte";
|
||||
|
||||
export interface AdminLink {
|
||||
/** i18n key, resolved via t() at render time */
|
||||
labelKey: string;
|
||||
@@ -33,6 +35,11 @@ export const ADMIN_SECTIONS: AdminSection[] = [
|
||||
labelKey: "pages.admin.nav.users",
|
||||
descriptionKey: "pages.admin.users.description",
|
||||
},
|
||||
{
|
||||
href: "/admin/categorization",
|
||||
labelKey: "pages.admin.nav.categorization",
|
||||
descriptionKey: "pages.admin.categorization.description",
|
||||
},
|
||||
{
|
||||
href: "/admin/comm",
|
||||
labelKey: "pages.admin.nav.comm",
|
||||
@@ -49,8 +56,37 @@ export const ADMIN_SECTIONS: AdminSection[] = [
|
||||
subSections: [
|
||||
{ href: "/admin/home/hero", labelKey: "pages.admin.home.tabs.hero" },
|
||||
{ href: "/admin/home/highlights", labelKey: "pages.admin.home.tabs.highlights" },
|
||||
{ href: "/admin/home/proposed", labelKey: "pages.admin.home.tabs.proposed" },
|
||||
{ href: "/admin/home/featured-users", labelKey: "pages.admin.home.tabs.featuredUsers" },
|
||||
{ href: "/admin/home/banners", labelKey: "pages.admin.home.tabs.banners" },
|
||||
],
|
||||
},
|
||||
{
|
||||
href: "/admin/customize",
|
||||
labelKey: "pages.admin.nav.customize",
|
||||
descriptionKey: "pages.admin.customize.description",
|
||||
subSections: [
|
||||
{ href: "/admin/customize/logo", labelKey: "pages.admin.customize.tabs.logo" },
|
||||
{ href: "/admin/customize/colors", labelKey: "pages.admin.customize.tabs.colors" },
|
||||
{ href: "/admin/customize/footer", labelKey: "pages.admin.customize.tabs.footer" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Sidebar entries for the sub-sections of a section, in the shape `WithSidebar` expects.
|
||||
*
|
||||
* Read out of the registry so that a sub-section is declared once: every page of a section
|
||||
* shares the very same sidebar, instead of each page folder carrying a copy of the list that
|
||||
* has to be kept in sync by hand.
|
||||
*
|
||||
* @param sectionHref the `href` of the section, e.g. "/admin/home"
|
||||
*/
|
||||
export function getSubSections(sectionHref: string): AdminSidebarItem[] {
|
||||
const section = ADMIN_SECTIONS.find((section) => section.href === sectionHref);
|
||||
|
||||
return (section?.subSections ?? []).map(({ labelKey, href }) => ({
|
||||
label: labelKey,
|
||||
href,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
<script lang="ts">
|
||||
import CategorizationTable, {
|
||||
type CategorizationRow,
|
||||
type CategorizationType,
|
||||
} from "./CategorizationTable.svelte";
|
||||
import CreateEditCategorizationModal from "./CreateEditCategorizationModal.svelte";
|
||||
import { session } from "../../../auth/store";
|
||||
import { locale, t } from "../../../i18n/store";
|
||||
import {
|
||||
apiCategoriesGetCollection,
|
||||
apiCategoriesIdDelete,
|
||||
apiThemesGetCollection,
|
||||
apiThemesIdDelete,
|
||||
type Category,
|
||||
type Theme,
|
||||
} from "../../../openapi/client/index.ts";
|
||||
import { toCollectionItems } from "../../../utils/hydra";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import DeleteModal from "../../library/feedback/DeleteModal.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
function authHeaders(): Record<string, string> {
|
||||
return Object.assign(
|
||||
{ Accept: "application/ld+json" },
|
||||
($session?.token.asHttpHeaders as Record<string, string>) ?? {},
|
||||
);
|
||||
}
|
||||
|
||||
let categories = $state<Category[]>([]);
|
||||
let themes = $state<Theme[]>([]);
|
||||
let isLoading = $state(true);
|
||||
|
||||
let modalOpen = $state(false);
|
||||
let modalMode = $state<"create" | "edit">("create");
|
||||
let modalType = $state<CategorizationType>("category");
|
||||
let editingItem = $state<Category | Theme | null>(null);
|
||||
|
||||
let deleteOpen = $state(false);
|
||||
let deleteRow = $state<CategorizationRow | null>(null);
|
||||
|
||||
const rows = $derived<CategorizationRow[]>([
|
||||
...categories.map((item) => ({ type: "category" as const, item })),
|
||||
...themes.map((item) => ({ type: "theme" as const, item })),
|
||||
]);
|
||||
|
||||
async function loadAll() {
|
||||
isLoading = true;
|
||||
try {
|
||||
const headers = { ...authHeaders(), "Accept-Language": $locale };
|
||||
|
||||
const [categoriesResponse, themesResponse] = await Promise.all([
|
||||
apiCategoriesGetCollection({ baseUrl: "/api/relay", headers }),
|
||||
apiThemesGetCollection({ baseUrl: "/api/relay", headers }),
|
||||
]);
|
||||
|
||||
if (categoriesResponse.error || themesResponse.error) {
|
||||
console.error(
|
||||
"Failed to load categories/themes:",
|
||||
categoriesResponse.error ?? themesResponse.error,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
categories = toCollectionItems<Category>(categoriesResponse.data);
|
||||
themes = toCollectionItems<Theme>(themesResponse.data);
|
||||
} catch (error) {
|
||||
console.error("Failed to load categories/themes:", error);
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
$locale;
|
||||
void loadAll();
|
||||
});
|
||||
|
||||
function openCreate(type: CategorizationType) {
|
||||
modalType = type;
|
||||
modalMode = "create";
|
||||
editingItem = null;
|
||||
modalOpen = true;
|
||||
}
|
||||
|
||||
function openEdit(row: CategorizationRow) {
|
||||
modalType = row.type;
|
||||
modalMode = "edit";
|
||||
editingItem = row.item;
|
||||
modalOpen = true;
|
||||
}
|
||||
|
||||
function openDelete(row: CategorizationRow) {
|
||||
deleteRow = row;
|
||||
deleteOpen = true;
|
||||
}
|
||||
|
||||
function typeKey(type: CategorizationType): string {
|
||||
return type === "category"
|
||||
? "pages.admin.categorization.table.types.category"
|
||||
: "pages.admin.categorization.table.types.theme";
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
if (!deleteRow) return;
|
||||
|
||||
const { type, item } = deleteRow;
|
||||
const id = item.id;
|
||||
|
||||
if (!id) return;
|
||||
|
||||
try {
|
||||
const headers = authHeaders();
|
||||
|
||||
if (type === "category") {
|
||||
await apiCategoriesIdDelete({ baseUrl: "/api/relay", path: { id }, headers });
|
||||
} else {
|
||||
await apiThemesIdDelete({ baseUrl: "/api/relay", path: { id }, headers });
|
||||
}
|
||||
|
||||
deleteOpen = false;
|
||||
deleteRow = null;
|
||||
await loadAll();
|
||||
} catch (error) {
|
||||
console.error("Failed to delete categorization item:", error);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="wrapper">
|
||||
<div class="flex w-full flex-col gap-8 py-10">
|
||||
<header class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between sm:gap-6">
|
||||
<div class="flex flex-col gap-4">
|
||||
<Title level={2} variant="headline" weight="bold" color="default">
|
||||
{$t("pages.admin.categorization.title")}
|
||||
</Title>
|
||||
<p class="text-content">
|
||||
{$t("pages.admin.categorization.description")}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 flex-wrap items-center gap-2">
|
||||
<Button kind="secondary" onclick={() => openCreate("category")}>
|
||||
{$t("pages.admin.categorization.actions.createCategory")}
|
||||
</Button>
|
||||
<Button onclick={() => openCreate("theme")}>
|
||||
{$t("pages.admin.categorization.actions.createTheme")}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<CategorizationTable {rows} {isLoading} onEdit={openEdit} onDelete={openDelete} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CreateEditCategorizationModal
|
||||
bind:open={modalOpen}
|
||||
mode={modalMode}
|
||||
type={modalType}
|
||||
item={editingItem}
|
||||
onSaved={loadAll}
|
||||
/>
|
||||
|
||||
<DeleteModal
|
||||
bind:open={deleteOpen}
|
||||
title={$t("pages.admin.categorization.delete.title", {
|
||||
type: deleteRow ? $t(typeKey(deleteRow.type)) : "",
|
||||
})}
|
||||
description={$t("pages.admin.categorization.delete.description", {
|
||||
name: deleteRow?.item.name ?? "",
|
||||
})}
|
||||
onclick={confirmDelete}
|
||||
/>
|
||||
@@ -0,0 +1,102 @@
|
||||
<script lang="ts" module>
|
||||
import type { Category, Theme } from "../../../openapi/client/index.ts";
|
||||
|
||||
export type CategorizationType = "category" | "theme";
|
||||
|
||||
export interface CategorizationRow {
|
||||
type: CategorizationType;
|
||||
item: Category | Theme;
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { TableBodyCell } from "flowbite-svelte";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import { t } from "../../../i18n/store";
|
||||
import { getLanguageDisplayName } from "../../../utils/lang";
|
||||
import Edit from "../../icons/actions/Edit.svelte";
|
||||
import Trash from "../../icons/actions/Trash.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import DataTable from "../../library/tables/DataTable.svelte";
|
||||
import Tag from "../../library/tags/Tag.svelte";
|
||||
|
||||
import type { DataTableHeader } from "../../library/tables/DataTable.svelte";
|
||||
|
||||
let {
|
||||
rows = [],
|
||||
isLoading = false,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: {
|
||||
rows: CategorizationRow[];
|
||||
isLoading: boolean;
|
||||
onEdit: (row: CategorizationRow) => void;
|
||||
onDelete: (row: CategorizationRow) => void;
|
||||
} = $props();
|
||||
|
||||
const headers: DataTableHeader[] = [
|
||||
{ key: "pages.admin.categorization.table.headers.name" },
|
||||
{ key: "pages.admin.categorization.table.headers.slug" },
|
||||
{ key: "pages.admin.categorization.table.headers.locales" },
|
||||
{ key: "pages.admin.categorization.table.headers.type" },
|
||||
{ key: "", class: "w-24" },
|
||||
];
|
||||
</script>
|
||||
|
||||
<DataTable
|
||||
{headers}
|
||||
{rows}
|
||||
{isLoading}
|
||||
emptyMessage="pages.admin.categorization.empty"
|
||||
currentPage={1}
|
||||
totalItems={rows.length}
|
||||
itemsPerPage={rows.length || 10}
|
||||
>
|
||||
{#snippet children(row: CategorizationRow)}
|
||||
<TableBodyCell class="border-variant1 rounded-l-md border-t border-b border-l p-4">
|
||||
<span class="text-content font-medium">{row.item.name}</span>
|
||||
</TableBodyCell>
|
||||
<TableBodyCell class="border-variant1 border-t border-b p-4">
|
||||
<span class="text-secondary text-sm">{row.item.slug ?? "—"}</span>
|
||||
</TableBodyCell>
|
||||
<TableBodyCell class="border-variant1 border-t border-b p-4">
|
||||
{(row.item.locales ?? [])
|
||||
.map((code: string) => getLanguageDisplayName(code) ?? code)
|
||||
.join(", ") || "—"}
|
||||
</TableBodyCell>
|
||||
<TableBodyCell class="border-variant1 border-t border-b p-4">
|
||||
<Tag
|
||||
variant="bold"
|
||||
class={twMerge(
|
||||
"text-secondary w-fit",
|
||||
row.type === "category" ? "bg-variant1" : "bg-variant2",
|
||||
)}
|
||||
>
|
||||
{row.type === "category"
|
||||
? $t("pages.admin.categorization.table.types.category")
|
||||
: $t("pages.admin.categorization.table.types.theme")}
|
||||
</Tag>
|
||||
</TableBodyCell>
|
||||
<TableBodyCell class="border-variant1 rounded-r-md border-t border-r border-b p-2">
|
||||
<div class="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="sm"
|
||||
class="rounded-full p-2.5"
|
||||
onclick={() => onEdit(row)}
|
||||
>
|
||||
<Edit class="size-5" />
|
||||
</Button>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="sm"
|
||||
class="text-tertiary inset-ring-tertiary rounded-full p-3"
|
||||
onclick={() => onDelete(row)}
|
||||
>
|
||||
<Trash class="size-4 text-current" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableBodyCell>
|
||||
{/snippet}
|
||||
</DataTable>
|
||||
@@ -0,0 +1,323 @@
|
||||
<script lang="ts">
|
||||
import { Modal } from "flowbite-svelte";
|
||||
|
||||
import { session } from "../../../auth/store";
|
||||
import { t } from "../../../i18n/store";
|
||||
import {
|
||||
apiCategoriesIdDelete,
|
||||
apiCategoriesIdOrSlugGet,
|
||||
apiCategoriesIdPatch,
|
||||
apiCategoriesPost,
|
||||
apiThemesIdDelete,
|
||||
apiThemesIdOrSlugGet,
|
||||
apiThemesIdPatch,
|
||||
apiThemesPost,
|
||||
type Category,
|
||||
type Theme,
|
||||
} from "../../../openapi/client/index.ts";
|
||||
import { getDefaultLanguage } from "../../../utils/consts";
|
||||
import {
|
||||
getLanguageDisplayName,
|
||||
primaryLanguage as pickPrimaryLanguage,
|
||||
} from "../../../utils/lang";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import TextInput from "../../library/inputs/TextInput.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
import TranslationLanguages from "../TranslationLanguages.svelte";
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
mode = "create",
|
||||
type = "category",
|
||||
item = null,
|
||||
onSaved,
|
||||
}: {
|
||||
open: boolean;
|
||||
mode: "create" | "edit";
|
||||
type: "category" | "theme";
|
||||
item?: Category | Theme | null;
|
||||
onSaved?: () => Promise<void> | void;
|
||||
} = $props();
|
||||
|
||||
const defaultLanguage = getDefaultLanguage();
|
||||
|
||||
interface Texts {
|
||||
name: string;
|
||||
}
|
||||
|
||||
const emptyTexts = (): Texts => ({ name: "" });
|
||||
|
||||
let languages = $state<string[]>([defaultLanguage]);
|
||||
let selectedLanguage = $state(defaultLanguage);
|
||||
let texts = $state<Record<string, Texts>>({ [defaultLanguage]: emptyTexts() });
|
||||
|
||||
let originalLocales = $state<string[]>([]);
|
||||
let originalId = $state<string | null>(null);
|
||||
let originalSlug = $state<string | null>(null);
|
||||
|
||||
let isLoading = $state(false);
|
||||
let isSubmitting = $state(false);
|
||||
let errorMessage = $state("");
|
||||
|
||||
const active = $derived(texts[selectedLanguage] ?? emptyTexts());
|
||||
|
||||
let requestId = 0;
|
||||
|
||||
function authHeaders(): Record<string, string> {
|
||||
return Object.assign(
|
||||
{ Accept: "application/ld+json" },
|
||||
($session?.token.asHttpHeaders as Record<string, string>) ?? {},
|
||||
);
|
||||
}
|
||||
|
||||
function initCreate() {
|
||||
requestId++;
|
||||
languages = [defaultLanguage];
|
||||
selectedLanguage = defaultLanguage;
|
||||
texts = { [defaultLanguage]: emptyTexts() };
|
||||
originalLocales = [];
|
||||
originalId = null;
|
||||
originalSlug = null;
|
||||
isLoading = false;
|
||||
isSubmitting = false;
|
||||
errorMessage = "";
|
||||
}
|
||||
|
||||
async function initEdit(target: Category | Theme) {
|
||||
const locales = target.locales?.length ? [...target.locales] : [defaultLanguage];
|
||||
const token = ++requestId;
|
||||
|
||||
originalLocales = locales;
|
||||
originalId = target.id ?? null;
|
||||
originalSlug = target.slug ?? null;
|
||||
languages = locales;
|
||||
selectedLanguage = locales[0];
|
||||
texts = Object.fromEntries(
|
||||
locales.map((code) => [code, { name: code === locales[0] ? (target.name ?? "") : "" }]),
|
||||
);
|
||||
isSubmitting = false;
|
||||
errorMessage = "";
|
||||
isLoading = Boolean(target.id);
|
||||
|
||||
if (!target.id) return;
|
||||
|
||||
try {
|
||||
let failed = false;
|
||||
|
||||
const names = await Promise.all(
|
||||
locales.map(async (code): Promise<[string, string]> => {
|
||||
const options = {
|
||||
baseUrl: "/api/relay",
|
||||
path: { idOrSlug: target.id! },
|
||||
headers: { ...authHeaders(), "Accept-Language": code },
|
||||
};
|
||||
const { data, error } =
|
||||
type === "category"
|
||||
? await apiCategoriesIdOrSlugGet(options)
|
||||
: await apiThemesIdOrSlugGet(options);
|
||||
|
||||
if (error) {
|
||||
failed = true;
|
||||
console.error(`Failed to load ${type} translation "${code}":`, error);
|
||||
return [code, ""];
|
||||
}
|
||||
|
||||
return [code, data?.name ?? ""];
|
||||
}),
|
||||
);
|
||||
|
||||
if (token !== requestId) return;
|
||||
|
||||
texts = Object.fromEntries(names.map(([code, name]) => [code, { name }]));
|
||||
|
||||
if (failed) {
|
||||
errorMessage = $t("pages.admin.categorization.errors.loadFailed");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to load ${type} translations:`, error);
|
||||
|
||||
if (token === requestId) {
|
||||
errorMessage = $t("pages.admin.categorization.errors.loadFailed");
|
||||
}
|
||||
} finally {
|
||||
if (token === requestId) isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
|
||||
if (mode === "create") {
|
||||
initCreate();
|
||||
} else if (item) {
|
||||
void initEdit(item);
|
||||
}
|
||||
});
|
||||
|
||||
function textFor(code: string): string {
|
||||
return texts[code]?.name.trim() ?? "";
|
||||
}
|
||||
|
||||
async function saveTranslation(id: string, code: string, name: string): Promise<void> {
|
||||
const options = {
|
||||
baseUrl: "/api/relay",
|
||||
path: { id },
|
||||
body: { name },
|
||||
headers: { ...authHeaders(), "Content-Language": code },
|
||||
};
|
||||
|
||||
if (type === "category") {
|
||||
await apiCategoriesIdPatch(options);
|
||||
} else {
|
||||
await apiThemesIdPatch(options);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteTranslation(id: string, code: string): Promise<void> {
|
||||
const options = {
|
||||
baseUrl: "/api/relay",
|
||||
path: { id },
|
||||
headers: { ...authHeaders(), "Content-Language": code },
|
||||
};
|
||||
|
||||
if (type === "category") {
|
||||
await apiCategoriesIdDelete(options);
|
||||
} else {
|
||||
await apiThemesIdDelete(options);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
errorMessage = "";
|
||||
|
||||
const missing = languages.filter((code) => !textFor(code));
|
||||
|
||||
if (missing.length > 0) {
|
||||
selectedLanguage = missing[0];
|
||||
errorMessage = $t("pages.admin.categorization.errors.incompleteLanguages", {
|
||||
languages: missing.map((code) => getLanguageDisplayName(code) ?? code).join(", "),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
isSubmitting = true;
|
||||
|
||||
try {
|
||||
const primary = pickPrimaryLanguage(languages, defaultLanguage);
|
||||
const translations = languages.filter((code) => code !== primary);
|
||||
|
||||
if (mode === "create") {
|
||||
const { data, error } =
|
||||
type === "category"
|
||||
? await apiCategoriesPost({
|
||||
baseUrl: "/api/relay",
|
||||
body: { name: textFor(primary) },
|
||||
headers: { ...authHeaders(), "Content-Language": primary },
|
||||
})
|
||||
: await apiThemesPost({
|
||||
baseUrl: "/api/relay",
|
||||
body: { name: textFor(primary) },
|
||||
headers: { ...authHeaders(), "Content-Language": primary },
|
||||
});
|
||||
|
||||
if (error || !data?.id) {
|
||||
throw error ?? new Error("The resource was created without an identifier");
|
||||
}
|
||||
|
||||
for (const code of translations) {
|
||||
await saveTranslation(data.id, code, textFor(code));
|
||||
}
|
||||
} else if (originalId) {
|
||||
for (const code of languages) {
|
||||
await saveTranslation(originalId, code, textFor(code));
|
||||
}
|
||||
|
||||
for (const code of originalLocales.filter((code) => !languages.includes(code))) {
|
||||
await deleteTranslation(originalId, code);
|
||||
}
|
||||
}
|
||||
|
||||
await onSaved?.();
|
||||
open = false;
|
||||
} catch (error) {
|
||||
console.error("Failed to save categorization item:", error);
|
||||
errorMessage = $t("pages.admin.categorization.errors.saveFailed");
|
||||
} finally {
|
||||
isSubmitting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal
|
||||
bind:open
|
||||
closeBtnClass="top-3 end-3 cursor-pointer bg-transparent text-secondary hover:bg-transparent hover:text-secondary hover:scale-110 transition-transform duration-200 transform focus:ring-0 shadow-none dark:text-secondary dark:hover:text-secondary dark:hover:bg-transparent"
|
||||
class="backdrop:bg-overlay fixed top-1/2 left-1/2 mx-2 flex w-full max-w-2xl -translate-x-1/2 -translate-y-1/2 flex-col gap-4 overflow-visible rounded-3xl border-b-0 bg-white p-6 shadow-lg backdrop:backdrop-blur-[5px] sm:mx-4 lg:mx-0"
|
||||
headerClass="border-b-0 md:p-0 p-0"
|
||||
bodyClass="md:p-0 p-0 overflow-y-visible border-b-0"
|
||||
footerClass="md:p-0 p-0 flex items-center justify-end gap-4 border-b-0"
|
||||
>
|
||||
{#snippet header()}
|
||||
<Title level={2} variant="subsection">
|
||||
{mode === "create"
|
||||
? type === "category"
|
||||
? $t("pages.admin.categorization.modal.createCategory")
|
||||
: $t("pages.admin.categorization.modal.createTheme")
|
||||
: type === "category"
|
||||
? $t("pages.admin.categorization.modal.editCategory")
|
||||
: $t("pages.admin.categorization.modal.editTheme")}
|
||||
</Title>
|
||||
{/snippet}
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<TranslationLanguages
|
||||
bind:languages
|
||||
bind:selected={selectedLanguage}
|
||||
onAdd={(code) => (texts[code] = emptyTexts())}
|
||||
onRemove={(code) => delete texts[code]}
|
||||
onSelect={() => (errorMessage = "")}
|
||||
/>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<span class="text-content text-sm font-medium">
|
||||
{$t("pages.admin.categorization.modal.name")}
|
||||
</span>
|
||||
<TextInput
|
||||
bind:value={() => active.name, (value) => (active.name = String(value))}
|
||||
placeholder={$t("pages.admin.categorization.modal.name")}
|
||||
disabled={isLoading || isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if mode === "edit" && (originalSlug || originalId)}
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-content text-sm font-medium">
|
||||
{$t("pages.admin.categorization.modal.slug")}
|
||||
</span>
|
||||
<span class="text-secondary text-sm">{originalSlug ?? "—"}</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-content text-sm font-medium">
|
||||
{$t("pages.admin.categorization.modal.locales")}
|
||||
</span>
|
||||
<span class="text-secondary text-sm">
|
||||
{originalLocales.join(", ") || "—"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if errorMessage}
|
||||
<p class="text-tertiary text-sm">{errorMessage}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#snippet footer()}
|
||||
<Button kind="ghost" onclick={() => (open = false)} class="w-fit" disabled={isSubmitting}>
|
||||
{$t("pages.admin.categorization.modal.cancel")}
|
||||
</Button>
|
||||
<Button onclick={handleSubmit} class="w-fit" disabled={isLoading || isSubmitting}>
|
||||
{$t("pages.admin.categorization.modal.save")}
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
@@ -16,8 +16,10 @@
|
||||
initialFormState,
|
||||
initialFiscal,
|
||||
type CreateChargeForm,
|
||||
type CreateChargeFormFiscal,
|
||||
type DonorType,
|
||||
} from "../../../types/admin-charge";
|
||||
import { useFormDraft, restoreFields } from "../../../utils/forms/useFormDraft.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
@@ -50,6 +52,98 @@
|
||||
let submitState = $state<"idle" | "submitting" | "error">("idle");
|
||||
let submitError = $state<string | null>(null);
|
||||
|
||||
/**
|
||||
* The fiscal data of the donor, without the tax ids.
|
||||
*
|
||||
* They are fiscal data and are left out on purpose: whoever fills the form in types them
|
||||
* again.
|
||||
*/
|
||||
type FiscalDraft =
|
||||
| { kind: "organization"; legalName: string; repFirstName: string; repLastName: string }
|
||||
| { kind: "individual"; firstName: string; lastName: string };
|
||||
|
||||
function fiscalDraft(fiscal: CreateChargeFormFiscal): FiscalDraft {
|
||||
if (fiscal.kind === "organization") {
|
||||
return {
|
||||
kind: "organization",
|
||||
legalName: fiscal.legalName,
|
||||
repFirstName: fiscal.repFirstName,
|
||||
repLastName: fiscal.repLastName,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "individual",
|
||||
firstName: fiscal.firstName,
|
||||
lastName: fiscal.lastName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds the fiscal data of the donor, with the tax ids empty because they are not
|
||||
* kept. The kind comes with it, so the effect that keeps both in step leaves it alone.
|
||||
*/
|
||||
function fiscalFromDraft(draft: FiscalDraft): CreateChargeFormFiscal {
|
||||
if (draft.kind === "organization") {
|
||||
return {
|
||||
kind: "organization",
|
||||
legalName: draft.legalName,
|
||||
taxId: "",
|
||||
repFirstName: draft.repFirstName,
|
||||
repLastName: draft.repLastName,
|
||||
repTaxId: "",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "individual",
|
||||
firstName: draft.firstName,
|
||||
lastName: draft.lastName,
|
||||
taxId: "",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The password of the donor is left out on purpose, it is a credential.
|
||||
*/
|
||||
type ChargeDraft = {
|
||||
currentStep: StepKey;
|
||||
existingUser: CreateChargeForm["existingUser"];
|
||||
user: Pick<CreateChargeForm["user"], "type" | "email">;
|
||||
fiscal: FiscalDraft;
|
||||
charge: CreateChargeForm["charge"];
|
||||
};
|
||||
|
||||
const { restored } = useFormDraft<ChargeDraft>("admin-create-charge", () => ({
|
||||
currentStep,
|
||||
existingUser: form.existingUser,
|
||||
user: { type: form.user.type, email: form.user.email },
|
||||
fiscal: fiscalDraft(form.fiscal),
|
||||
charge: form.charge,
|
||||
}));
|
||||
|
||||
/**
|
||||
* Puts back what was kept before the language switch.
|
||||
*/
|
||||
function restoreCharge(draft: Partial<ChargeDraft>) {
|
||||
currentStep = draft.currentStep ?? "user";
|
||||
form.existingUser = draft.existingUser ?? null;
|
||||
|
||||
restoreFields(form.user, draft.user, ["type", "email"]);
|
||||
|
||||
if (draft.charge) {
|
||||
form.charge = draft.charge;
|
||||
}
|
||||
|
||||
if (draft.fiscal) {
|
||||
form.fiscal = fiscalFromDraft(draft.fiscal);
|
||||
}
|
||||
}
|
||||
|
||||
if (restored) {
|
||||
restoreCharge(restored);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
submitting = submitState === "submitting";
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
} from "flowbite-svelte";
|
||||
|
||||
import { t } from "../../../i18n/store";
|
||||
import { useFormDraft } from "../../../utils/forms/useFormDraft.svelte";
|
||||
import PlusIcon from "../../icons/actions/PlusIcon.svelte";
|
||||
import FiltersIcon from "../../icons/filters/Filters.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
@@ -88,6 +89,38 @@
|
||||
|
||||
let isSubmitting = $state(false);
|
||||
|
||||
/**
|
||||
* The newsletter holds no sensitive data, so the whole form can be kept.
|
||||
*/
|
||||
const { restored } = useFormDraft("admin-newsletter", () => ({
|
||||
selectedTemplate,
|
||||
recipientBlocks,
|
||||
selectedRecipients,
|
||||
isTest,
|
||||
onlySpanish,
|
||||
}));
|
||||
if (restored) {
|
||||
if (restored.selectedTemplate !== undefined) {
|
||||
selectedTemplate = restored.selectedTemplate;
|
||||
}
|
||||
|
||||
if (restored.recipientBlocks) {
|
||||
recipientBlocks = restored.recipientBlocks;
|
||||
}
|
||||
|
||||
if (restored.selectedRecipients) {
|
||||
selectedRecipients = restored.selectedRecipients;
|
||||
}
|
||||
|
||||
if (restored.isTest !== undefined) {
|
||||
isTest = restored.isTest;
|
||||
}
|
||||
|
||||
if (restored.onlySpanish !== undefined) {
|
||||
onlySpanish = restored.onlySpanish;
|
||||
}
|
||||
}
|
||||
|
||||
const recipientOptions = $derived([
|
||||
{ value: "all", label: $t("pages.admin.newsletter.send.recipients.all") },
|
||||
{ value: "promoters", label: $t("pages.admin.newsletter.send.recipients.promoters") },
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { locale, t } from "../../../../i18n/store";
|
||||
import { BLOG_SECTIONS } from "../../../../utils/blog";
|
||||
import { getDefaultLanguage } from "../../../../utils/consts";
|
||||
import { useFormDraft, restoreFields } from "../../../../utils/forms/useFormDraft.svelte";
|
||||
import {
|
||||
getLanguageDisplayName,
|
||||
primaryLanguage as pickPrimaryLanguage,
|
||||
@@ -50,6 +51,8 @@
|
||||
const contentId = $props.id();
|
||||
let publishedAt = $state(initial?.publishedAt ?? new Date());
|
||||
let section = $state<BlogSection>(initial?.section ?? "news");
|
||||
let author = $state(initial?.author ?? "");
|
||||
let videoUrl = $state(initial?.videoUrl ?? "");
|
||||
|
||||
// Only URL and type are stored, so rebuild what FileUpload needs to list the current header.
|
||||
let header = $state<UploadedObject[]>(
|
||||
@@ -71,25 +74,24 @@
|
||||
const defaultLanguage = getDefaultLanguage();
|
||||
|
||||
// Every language's texts live here, the base one included, and are saved together.
|
||||
let texts = $state<Record<string, Texts>>(
|
||||
initial
|
||||
? Object.fromEntries(
|
||||
initial.languages.map((code) => {
|
||||
const stored =
|
||||
code === initial.language ? initial : initial.translations[code];
|
||||
const initialTexts: Record<string, Texts> = initial
|
||||
? Object.fromEntries(
|
||||
initial.languages.map((code) => {
|
||||
const stored = code === initial.language ? initial : initial.translations[code];
|
||||
|
||||
return [
|
||||
code,
|
||||
{
|
||||
title: stored?.title ?? "",
|
||||
subtitle: stored?.subtitle ?? "",
|
||||
content: stored?.content ?? "",
|
||||
},
|
||||
];
|
||||
}),
|
||||
)
|
||||
: { [defaultLanguage]: emptyTexts() },
|
||||
);
|
||||
return [
|
||||
code,
|
||||
{
|
||||
title: stored?.title ?? "",
|
||||
subtitle: stored?.subtitle ?? "",
|
||||
content: stored?.content ?? "",
|
||||
},
|
||||
];
|
||||
}),
|
||||
)
|
||||
: { [defaultLanguage]: emptyTexts() };
|
||||
|
||||
let texts = $state<Record<string, Texts>>(initialTexts);
|
||||
let languages = $state<string[]>(initial?.languages ?? [defaultLanguage]);
|
||||
let selectedLanguage = $state(untrack(() => languages[0]));
|
||||
const active = $derived(texts[selectedLanguage]);
|
||||
@@ -103,6 +105,59 @@
|
||||
fieldErrors = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Nothing in this form is sensitive, so all of it can be kept. The header is kept by URL
|
||||
* and type, the way it is sent to the API.
|
||||
*/
|
||||
const { restored } = useFormDraft("admin-comm-blog", () => ({
|
||||
texts,
|
||||
languages,
|
||||
selectedLanguage,
|
||||
publishedAt: publishedAt.toISOString(),
|
||||
section,
|
||||
author,
|
||||
videoUrl,
|
||||
header: header.map(({ url, type }) => ({ url, type })),
|
||||
}));
|
||||
|
||||
if (restored) {
|
||||
restoreFields(texts, restored.texts);
|
||||
|
||||
if (restored.languages) {
|
||||
languages = restored.languages;
|
||||
}
|
||||
|
||||
if (restored.selectedLanguage) {
|
||||
selectedLanguage = restored.selectedLanguage;
|
||||
}
|
||||
|
||||
if (restored.publishedAt) {
|
||||
publishedAt = new Date(restored.publishedAt);
|
||||
}
|
||||
|
||||
if (restored.section) {
|
||||
section = restored.section;
|
||||
}
|
||||
|
||||
if (restored.author !== undefined) {
|
||||
author = restored.author;
|
||||
}
|
||||
|
||||
if (restored.videoUrl !== undefined) {
|
||||
videoUrl = restored.videoUrl;
|
||||
}
|
||||
|
||||
if (restored.header) {
|
||||
header = restored.header.map(({ url, type }) => ({
|
||||
id: url,
|
||||
url,
|
||||
type,
|
||||
size: 0,
|
||||
name: url.split("/").pop() ?? "",
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
async function submit(publish: boolean) {
|
||||
fieldErrors = {};
|
||||
|
||||
@@ -242,7 +297,7 @@
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<TextInput
|
||||
name="author"
|
||||
value={post?.author ?? ""}
|
||||
bind:value={author}
|
||||
placeholder={$t("pages.admin.comm.blog.form.authorPlaceholder")}
|
||||
/>
|
||||
<DateInput
|
||||
@@ -294,7 +349,7 @@
|
||||
</Title>
|
||||
<TextInput
|
||||
name="videoUrl"
|
||||
value={post?.videoUrl ?? ""}
|
||||
bind:value={videoUrl}
|
||||
placeholder={$t("pages.admin.comm.blog.form.videoPlaceholder")}
|
||||
error={fieldErrors.videoUrl && $t(fieldErrors.videoUrl)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import { t } from "../../../i18n/store";
|
||||
import {
|
||||
MINIMUM_CONTRAST_RATIO,
|
||||
validateThemeColorContrast,
|
||||
} from "../../../utils/colorContrast";
|
||||
import {
|
||||
DARK_THEME_COLOR_DEFAULTS,
|
||||
DARK_THEME_COLOR_TOKENS,
|
||||
GENERIC_THEME_COLOR_TOKENS,
|
||||
LIGHT_THEME_COLOR_TOKENS,
|
||||
THEME_COLOR_DEFAULTS,
|
||||
THEME_COLOR_TOKENS,
|
||||
isHexColor,
|
||||
} from "../../../utils/themeColors";
|
||||
import ActionableButton from "../../library/buttons/ActionableButton.svelte";
|
||||
import Toast from "../../library/feedback/Toast.svelte";
|
||||
import ColorInput from "../../library/inputs/ColorInput.svelte";
|
||||
import Tabs from "../../library/layout/Tabs.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
import type { ContrastWarning } from "../../../utils/colorContrast";
|
||||
import type {
|
||||
DarkThemeColors,
|
||||
DarkThemeColorToken,
|
||||
GenericThemeColorToken,
|
||||
ThemeColors,
|
||||
ThemeColorToken,
|
||||
} from "../../../utils/themeColors";
|
||||
|
||||
interface Props {
|
||||
config: {
|
||||
lightColors: ThemeColors;
|
||||
darkColors: DarkThemeColors;
|
||||
};
|
||||
}
|
||||
|
||||
let { config }: Props = $props();
|
||||
|
||||
const initialConfig = untrack(() => config);
|
||||
let lightColors = $state<ThemeColors>({ ...initialConfig.lightColors });
|
||||
let darkColors = $state<DarkThemeColors>({ ...initialConfig.darkColors });
|
||||
let activeTheme = $state<"generic" | "light" | "dark">("generic");
|
||||
let showError = $state(false);
|
||||
let errorMessage = $state("");
|
||||
let showSuccess = $state(false);
|
||||
let successMessage = $state("");
|
||||
|
||||
const tabs = $derived([
|
||||
{ id: "generic", label: $t("pages.admin.customize.colors.themes.generic") },
|
||||
{ id: "light", label: $t("pages.admin.customize.colors.themes.light") },
|
||||
{ id: "dark", label: $t("pages.admin.customize.colors.themes.dark") },
|
||||
]);
|
||||
const contrastWarnings = $derived(validateThemeColorContrast(lightColors, darkColors));
|
||||
const hasInvalidColors = $derived(
|
||||
!THEME_COLOR_TOKENS.every((token) => isHexColor(lightColors[token])) ||
|
||||
!DARK_THEME_COLOR_TOKENS.every((token) => isHexColor(darkColors[token])),
|
||||
);
|
||||
|
||||
function tokenLabel(token: ThemeColorToken): string {
|
||||
return $t(`pages.admin.customize.colors.tokens.${token}`);
|
||||
}
|
||||
|
||||
function warningMessage(warning: ContrastWarning, includeTheme = false): string {
|
||||
return $t(
|
||||
includeTheme
|
||||
? "pages.admin.customize.colors.contrast.warningWithTheme"
|
||||
: "pages.admin.customize.colors.contrast.warning",
|
||||
{
|
||||
theme: $t(`pages.admin.customize.colors.themes.${warning.theme}`),
|
||||
text: tokenLabel(warning.textToken),
|
||||
background: tokenLabel(warning.backgroundToken),
|
||||
ratio: warning.ratio,
|
||||
minimum: MINIMUM_CONTRAST_RATIO,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function warningsFor(
|
||||
theme: "light" | "dark",
|
||||
token: ThemeColorToken | DarkThemeColorToken,
|
||||
): string[] {
|
||||
return contrastWarnings
|
||||
.filter((warning) => warning.theme === theme && warning.textToken === token)
|
||||
.map((warning) => warningMessage(warning));
|
||||
}
|
||||
|
||||
function genericWarningsFor(token: GenericThemeColorToken): string[] {
|
||||
return contrastWarnings
|
||||
.filter((warning) => warning.textToken === token)
|
||||
.map((warning) => warningMessage(warning, true));
|
||||
}
|
||||
|
||||
function showFailure(message: string): never {
|
||||
errorMessage = message;
|
||||
showError = true;
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (hasInvalidColors) {
|
||||
showFailure($t("pages.admin.customize.colors.errors.invalid"));
|
||||
}
|
||||
|
||||
const { error } = await actions.saveThemeColors({ lightColors, darkColors });
|
||||
|
||||
if (error) showFailure(error.message);
|
||||
|
||||
successMessage = $t("pages.admin.customize.colors.feedback.saved");
|
||||
showSuccess = true;
|
||||
}
|
||||
|
||||
async function handleReset() {
|
||||
if (!window.confirm($t("pages.admin.customize.colors.reset.confirm"))) return;
|
||||
|
||||
const { error } = await actions.resetThemeColors({});
|
||||
|
||||
if (error) showFailure(error.message);
|
||||
|
||||
lightColors = { ...THEME_COLOR_DEFAULTS };
|
||||
darkColors = { ...DARK_THEME_COLOR_DEFAULTS };
|
||||
successMessage = $t("pages.admin.customize.colors.feedback.reset");
|
||||
showSuccess = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-10">
|
||||
<header class="flex flex-col justify-between gap-6 lg:flex-row lg:items-start">
|
||||
<div class="flex max-w-2xl flex-col gap-2">
|
||||
<Title level={2} variant="headline">
|
||||
{$t("pages.admin.customize.colors.title")}
|
||||
</Title>
|
||||
<p class="text-content text-base">
|
||||
{$t("pages.admin.customize.colors.description")}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 flex-col gap-3 sm:flex-row">
|
||||
<ActionableButton action={handleReset} autoreset={2000} kind="ghost" class="w-fit px-6">
|
||||
{$t("pages.admin.customize.colors.reset.button")}
|
||||
</ActionableButton>
|
||||
<ActionableButton
|
||||
action={handleSave}
|
||||
autoreset={2000}
|
||||
class="w-fit px-6"
|
||||
disabled={hasInvalidColors}
|
||||
>
|
||||
{$t("pages.admin.customize.colors.save")}
|
||||
</ActionableButton>
|
||||
</div>
|
||||
</header>
|
||||
<section
|
||||
class="bg-purple-soft border-grey flex flex-col gap-3 rounded-xl border p-4 shadow-sm"
|
||||
aria-label={$t("pages.admin.customize.colors.contrast.title")}
|
||||
>
|
||||
<Title level={3} variant="subsection">
|
||||
{$t("pages.admin.customize.colors.contrast.title")}
|
||||
</Title>
|
||||
<p class="text-content text-sm">
|
||||
{$t("pages.admin.customize.colors.contrast.description", {
|
||||
minimum: MINIMUM_CONTRAST_RATIO,
|
||||
})}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<Tabs
|
||||
{tabs}
|
||||
activeTab={activeTheme}
|
||||
alignment="left"
|
||||
useDataAttributes={false}
|
||||
onTabChange={(tab) => (activeTheme = tab as "generic" | "light" | "dark")}
|
||||
/>
|
||||
|
||||
{#if activeTheme === "generic"}
|
||||
<section class="flex flex-col gap-6">
|
||||
<div>
|
||||
<Title level={3} variant="subsection">
|
||||
{$t("pages.admin.customize.colors.themes.generic")}
|
||||
</Title>
|
||||
<p class="text-content text-sm">
|
||||
{$t("pages.admin.customize.colors.themes.genericDescription")}
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 items-start gap-6 md:grid-cols-2 xl:grid-cols-3">
|
||||
{#each GENERIC_THEME_COLOR_TOKENS as token}
|
||||
<ColorInput
|
||||
bind:value={lightColors[token]}
|
||||
labelText={tokenLabel(token)}
|
||||
helperText={`--color-${token}`}
|
||||
pickerLabel={$t("pages.admin.customize.colors.picker", {
|
||||
color: tokenLabel(token),
|
||||
})}
|
||||
error={!isHexColor(lightColors[token])
|
||||
? $t("pages.admin.customize.colors.errors.hex")
|
||||
: undefined}
|
||||
contrastWarnings={genericWarningsFor(token)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{:else if activeTheme === "light"}
|
||||
<section class="flex flex-col gap-6">
|
||||
<div>
|
||||
<Title level={3} variant="subsection">
|
||||
{$t("pages.admin.customize.colors.themes.light")}
|
||||
</Title>
|
||||
<p class="text-content text-sm">
|
||||
{$t("pages.admin.customize.colors.themes.lightDescription")}
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 items-start gap-6 md:grid-cols-2 xl:grid-cols-3">
|
||||
{#each LIGHT_THEME_COLOR_TOKENS as token}
|
||||
<ColorInput
|
||||
bind:value={lightColors[token]}
|
||||
labelText={tokenLabel(token)}
|
||||
helperText={`--color-${token}`}
|
||||
pickerLabel={$t("pages.admin.customize.colors.picker", {
|
||||
color: tokenLabel(token),
|
||||
})}
|
||||
error={!isHexColor(lightColors[token])
|
||||
? $t("pages.admin.customize.colors.errors.hex")
|
||||
: undefined}
|
||||
contrastWarnings={warningsFor("light", token)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{:else}
|
||||
<section class="flex flex-col gap-6">
|
||||
<div>
|
||||
<Title level={3} variant="subsection">
|
||||
{$t("pages.admin.customize.colors.themes.dark")}
|
||||
</Title>
|
||||
<p class="text-content text-sm">
|
||||
{$t("pages.admin.customize.colors.themes.darkDescription")}
|
||||
</p>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 items-start gap-6 md:grid-cols-2 xl:grid-cols-3">
|
||||
{#each DARK_THEME_COLOR_TOKENS as token}
|
||||
<ColorInput
|
||||
bind:value={darkColors[token]}
|
||||
labelText={tokenLabel(token)}
|
||||
helperText={`--color-${token}`}
|
||||
pickerLabel={$t("pages.admin.customize.colors.picker", {
|
||||
color: tokenLabel(token),
|
||||
})}
|
||||
error={!isHexColor(darkColors[token])
|
||||
? $t("pages.admin.customize.colors.errors.hex")
|
||||
: undefined}
|
||||
contrastWarnings={warningsFor("dark", token)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Toast floating variant="error" bind:showToast={showError}>{errorMessage}</Toast>
|
||||
<Toast floating variant="success" bind:showToast={showSuccess}>{successMessage}</Toast>
|
||||
@@ -0,0 +1,486 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { Modal } from "flowbite-svelte";
|
||||
import { tick, untrack } from "svelte";
|
||||
|
||||
import { languagesList, type Locale } from "../../../../i18n/locales";
|
||||
import { t } from "../../../../i18n/store";
|
||||
import { localized } from "../../../../layouts/footer-data";
|
||||
import { FOOTER_SOCIAL_NETWORKS } from "../../../../types/footer";
|
||||
import { getDefaultLanguage } from "../../../../utils/consts";
|
||||
import FooterView from "../../../footer/FooterView.svelte";
|
||||
import Trash from "../../../icons/actions/Trash.svelte";
|
||||
import Chevron from "../../../icons/navigation/Chevron.svelte";
|
||||
import ActionableButton from "../../../library/buttons/ActionableButton.svelte";
|
||||
import Button from "../../../library/buttons/Button.svelte";
|
||||
import Toast from "../../../library/feedback/Toast.svelte";
|
||||
import Checkbox from "../../../library/inputs/Checkbox.svelte";
|
||||
import ImageUploadModal from "../../../library/inputs/ImageUploadModal.svelte";
|
||||
import Select from "../../../library/inputs/Select.svelte";
|
||||
import TextInput from "../../../library/inputs/TextInput.svelte";
|
||||
import TabNavigation from "../../../library/layout/TabNavigation.svelte";
|
||||
import Title from "../../../library/typography/Title.svelte";
|
||||
|
||||
import type {
|
||||
FooterConfig,
|
||||
FooterSection,
|
||||
FooterLinkItem,
|
||||
FooterPartner,
|
||||
LocalizedText,
|
||||
} from "../../../../types/footer";
|
||||
import type { UploadedObject } from "../../../../utils/media/objectStorage.types";
|
||||
|
||||
interface Props {
|
||||
config: FooterConfig;
|
||||
}
|
||||
|
||||
let { config: initial }: Props = $props();
|
||||
|
||||
const defaultLanguage = getDefaultLanguage() as Locale;
|
||||
|
||||
// Own copy, sent whole on save. `$state.snapshot` because Astro hydrates props as a
|
||||
// `$state` proxy, which `structuredClone` cannot copy.
|
||||
let config = $state<FooterConfig>($state.snapshot(untrack(() => initial)));
|
||||
const languageTabs = Object.entries(languagesList).map(([id, label]) => ({ id, label }));
|
||||
let language = $state<Locale>(defaultLanguage);
|
||||
|
||||
let errorMessage = $state("");
|
||||
let showError = $state(false);
|
||||
let showSaved = $state(false);
|
||||
|
||||
// The partner list and position the upload modal fills; `index` past the end adds one.
|
||||
let uploadTarget = $state<{ list: FooterPartner[]; index: number } | null>(null);
|
||||
let isUploadOpen = $state(false);
|
||||
|
||||
function move<T>(list: T[], index: number, delta: number) {
|
||||
const target = index + delta;
|
||||
|
||||
if (target < 0 || target >= list.length) return;
|
||||
|
||||
[list[index], list[target]] = [list[target], list[index]];
|
||||
}
|
||||
|
||||
function openUpload(list: FooterPartner[], index: number) {
|
||||
uploadTarget = { list, index };
|
||||
isUploadOpen = true;
|
||||
}
|
||||
|
||||
function handleUpload([file]: UploadedObject[]) {
|
||||
if (!file || !uploadTarget) return;
|
||||
|
||||
const { list, index } = uploadTarget;
|
||||
|
||||
if (index < list.length) {
|
||||
list[index].src = file.url;
|
||||
} else {
|
||||
list.push({ src: file.url, alt: "", href: "" });
|
||||
}
|
||||
|
||||
uploadTarget = null;
|
||||
}
|
||||
|
||||
let form: HTMLFormElement;
|
||||
|
||||
// The `.wrapper` max width: the preview is drawn at that size and zoomed into its box.
|
||||
const PREVIEW_WIDTH = 1440;
|
||||
let previewWidth = $state(0);
|
||||
|
||||
// The navigation column or logo group being edited in the modal.
|
||||
type EditableList = "navColumns" | "partnerGroups";
|
||||
|
||||
let editing = $state<{ list: EditableList; index: number } | null>(null);
|
||||
let isEditOpen = $state(false);
|
||||
|
||||
function edit(list: EditableList, index: number) {
|
||||
editing = { list, index };
|
||||
isEditOpen = true;
|
||||
}
|
||||
|
||||
function addColumn() {
|
||||
config.navColumns.push({ title: {}, links: [{ label: {}, href: "" }] });
|
||||
edit("navColumns", config.navColumns.length - 1);
|
||||
}
|
||||
|
||||
function addGroup() {
|
||||
config.partnerGroups.push({ title: {}, partners: [] });
|
||||
edit("partnerGroups", config.partnerGroups.length - 1);
|
||||
}
|
||||
|
||||
// A row is highlighted while any of its fields has focus (`focus-within`).
|
||||
const rowClass =
|
||||
"focus-within:ring-primary flex items-center gap-3 rounded-lg focus-within:ring-2";
|
||||
|
||||
/**
|
||||
* Clicking an element of the preview focuses its row in the form, matched through the
|
||||
* `data-edit` path the preview puts on it. The preview's own links never navigate.
|
||||
*/
|
||||
async function focusField(event: MouseEvent) {
|
||||
event.preventDefault();
|
||||
|
||||
const path = (event.target as Element).closest<HTMLElement>("[data-edit]")?.dataset.edit;
|
||||
|
||||
if (!path) return;
|
||||
|
||||
// Columns and logo groups are edited in a modal: open it and wait until it has rendered.
|
||||
// ponytail: two frames, because the dialog grabs focus itself when its intro starts.
|
||||
const [list, index] = path.split(".");
|
||||
|
||||
if (list === "navColumns" || list === "partnerGroups") {
|
||||
edit(list, Number(index));
|
||||
await tick();
|
||||
await new Promise((resolve) =>
|
||||
requestAnimationFrame(() => requestAnimationFrame(resolve)),
|
||||
);
|
||||
}
|
||||
|
||||
const row = form.querySelector(`[data-field="${path}"]`);
|
||||
|
||||
row?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
row?.querySelector<HTMLElement>("input, select, button")?.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const { error } = await actions.saveFooter({ config: JSON.stringify(config) });
|
||||
|
||||
if (error) {
|
||||
errorMessage =
|
||||
error.code === "INTERNAL_SERVER_ERROR" ? $t("system.error.unknown") : error.message;
|
||||
showError = true;
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
showSaved = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet rowControls(list: unknown[], index: number)}
|
||||
<div class="flex shrink-0 items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="text-secondary cursor-pointer p-1 disabled:opacity-30"
|
||||
aria-label={$t("pages.admin.customize.footer.actions.moveUp")}
|
||||
disabled={index === 0}
|
||||
onclick={() => move(list, index, -1)}
|
||||
>
|
||||
<Chevron direction="up" width="20" height="20" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="text-secondary cursor-pointer p-1 disabled:opacity-30"
|
||||
aria-label={$t("pages.admin.customize.footer.actions.moveDown")}
|
||||
disabled={index === list.length - 1}
|
||||
onclick={() => move(list, index, 1)}
|
||||
>
|
||||
<Chevron direction="down" width="20" height="20" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="text-tertiary cursor-pointer p-1"
|
||||
aria-label={$t("common.remove")}
|
||||
onclick={() => list.splice(index, 1)}
|
||||
>
|
||||
<Trash width="18" height="20" />
|
||||
</button>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet localizedInput(text: LocalizedText, placeholder: string)}
|
||||
<div class="flex-1">
|
||||
<TextInput
|
||||
bind:value={() => text[language] ?? "", (value) => (text[language] = String(value))}
|
||||
placeholder={language === defaultLanguage
|
||||
? placeholder
|
||||
: text[defaultLanguage] || placeholder}
|
||||
/>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet linkList(links: FooterLinkItem[], path: string)}
|
||||
<ul class="space-y-3">
|
||||
{#each links as link, index (link)}
|
||||
<li class={rowClass} data-field="{path}.{index}">
|
||||
{@render localizedInput(
|
||||
link.label,
|
||||
$t("pages.admin.customize.footer.fields.labelPlaceholder"),
|
||||
)}
|
||||
<div class="flex-1">
|
||||
<TextInput
|
||||
bind:value={link.href}
|
||||
placeholder={$t("pages.admin.customize.footer.fields.hrefPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
{@render rowControls(links, index)}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="sm"
|
||||
class="w-fit"
|
||||
onclick={() => links.push({ label: {}, href: "" })}
|
||||
>
|
||||
{$t("pages.admin.customize.footer.actions.addLink")}
|
||||
</Button>
|
||||
{/snippet}
|
||||
|
||||
{#snippet partnerList(partners: FooterPartner[], path: string)}
|
||||
<ul class="space-y-3">
|
||||
{#each partners as partner, index (partner)}
|
||||
<li class={rowClass} data-field="{path}.{index}">
|
||||
<button
|
||||
type="button"
|
||||
class="bg-grey flex h-14 w-24 shrink-0 cursor-pointer items-center justify-center rounded-lg p-1"
|
||||
aria-label={$t("pages.admin.customize.footer.actions.changeImage")}
|
||||
onclick={() => openUpload(partners, index)}
|
||||
>
|
||||
<img src={partner.src} alt="" class="max-h-full max-w-full object-contain" />
|
||||
</button>
|
||||
<div class="flex-1">
|
||||
<TextInput
|
||||
bind:value={partner.alt}
|
||||
placeholder={$t("pages.admin.customize.footer.fields.altPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<TextInput
|
||||
bind:value={
|
||||
() => partner.href ?? "", (value) => (partner.href = String(value))
|
||||
}
|
||||
placeholder={$t(
|
||||
"pages.admin.customize.footer.fields.partnerHrefPlaceholder",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{@render rowControls(partners, index)}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="sm"
|
||||
class="w-fit"
|
||||
onclick={() => openUpload(partners, partners.length)}
|
||||
>
|
||||
{$t("pages.admin.customize.footer.actions.addPartner")}
|
||||
</Button>
|
||||
{/snippet}
|
||||
|
||||
<!-- One language for the whole editor: the form and the modal switch it together. -->
|
||||
{#snippet languageTabsNav()}
|
||||
<TabNavigation
|
||||
tabs={languageTabs}
|
||||
currentTab={language}
|
||||
onTabClick={(id) => (language = id as Locale)}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
{#snippet sectionHeader(section: FooterSection, titleKey: string)}
|
||||
<div class="flex flex-wrap items-center justify-between gap-4">
|
||||
<Title level={3} variant="subsection">{$t(titleKey)}</Title>
|
||||
<Checkbox
|
||||
bind:checked={config.hidden[section]}
|
||||
label={$t("pages.admin.customize.footer.hideSection")}
|
||||
/>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet summaryCard(list: EditableList, title: LocalizedText, count: string, index: number)}
|
||||
<li class="border-grey flex items-center gap-3 rounded-2xl border p-4">
|
||||
<div class="flex-1">
|
||||
<p class="text-secondary font-bold">
|
||||
{localized(title, language) ||
|
||||
$t("pages.admin.customize.footer.fields.titlePlaceholder")}
|
||||
</p>
|
||||
<p class="text-content text-sm">{count}</p>
|
||||
</div>
|
||||
<Button kind="ghost" size="sm" onclick={() => edit(list, index)}>
|
||||
{$t("common.edit")}
|
||||
</Button>
|
||||
{@render rowControls(config[list], index)}
|
||||
</li>
|
||||
{/snippet}
|
||||
|
||||
<section class="mb-10 space-y-3">
|
||||
<Title level={3} variant="subsection">
|
||||
{$t("pages.admin.customize.footer.sections.preview")}
|
||||
</Title>
|
||||
<p class="text-content text-sm">{$t("pages.admin.customize.footer.previewHelp")}</p>
|
||||
<!-- Mouse shortcut only: every field is reachable from the form below. -->
|
||||
<div
|
||||
role="presentation"
|
||||
class="[&_[data-edit]:hover]:outline-primary overflow-hidden rounded-b-3xl **:data-edit:cursor-pointer **:data-edit:rounded-sm [&_[data-edit]:hover]:outline-2 [&_[data-edit]:hover]:outline-offset-2"
|
||||
onclick={focusField}
|
||||
bind:clientWidth={previewWidth}
|
||||
>
|
||||
<!-- Laid out as on a 1440px window (1360px of content), then zoomed to fit. -->
|
||||
<div
|
||||
class="w-360"
|
||||
style:zoom={previewWidth ? Math.min(1, previewWidth / PREVIEW_WIDTH) : undefined}
|
||||
>
|
||||
<FooterView {config} lang={language} t={$t} idPrefix="footer-preview" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<form
|
||||
bind:this={form}
|
||||
class="space-y-10"
|
||||
onsubmit={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<div class="space-y-2">
|
||||
{@render languageTabsNav()}
|
||||
<p class="text-content text-sm">
|
||||
{$t("pages.admin.customize.footer.languageHelp", {
|
||||
language: languagesList[defaultLanguage],
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-10 xl:grid-cols-2">
|
||||
<section class="space-y-6">
|
||||
{@render sectionHeader("partners", "pages.admin.customize.footer.sections.partners")}
|
||||
|
||||
<ul class="space-y-3">
|
||||
{#each config.partnerGroups as group, index (group)}
|
||||
{@render summaryCard(
|
||||
"partnerGroups",
|
||||
group.title,
|
||||
$t("pages.admin.customize.footer.logoCount", {
|
||||
count: group.partners.length,
|
||||
}),
|
||||
index,
|
||||
)}
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<Button kind="secondary" size="sm" class="w-fit" onclick={addGroup}>
|
||||
{$t("pages.admin.customize.footer.actions.addGroup")}
|
||||
</Button>
|
||||
</section>
|
||||
|
||||
<section class="space-y-6">
|
||||
{@render sectionHeader(
|
||||
"navigation",
|
||||
"pages.admin.customize.footer.sections.navigation",
|
||||
)}
|
||||
|
||||
<ul class="space-y-3">
|
||||
{#each config.navColumns as column, index (column)}
|
||||
{@render summaryCard(
|
||||
"navColumns",
|
||||
column.title,
|
||||
$t("pages.admin.customize.footer.linkCount", {
|
||||
count: column.links.length,
|
||||
}),
|
||||
index,
|
||||
)}
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<Button kind="secondary" size="sm" class="w-fit" onclick={addColumn}>
|
||||
{$t("pages.admin.customize.footer.actions.addColumn")}
|
||||
</Button>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- Inside the form so `focusField` finds its rows; Enter is already prevented. -->
|
||||
<Modal
|
||||
bind:open={isEditOpen}
|
||||
closeBtnClass="top-7 end-7 cursor-pointer bg-transparent text-secondary hover:bg-transparent hover:text-secondary hover:scale-110 transition-transform duration-200 transform focus:ring-0 shadow-none dark:text-secondary dark:hover:text-secondary dark:hover:bg-transparent"
|
||||
class="backdrop:bg-overlay fixed top-1/2 left-1/2 mx-2 flex max-h-[90vh] w-full max-w-200 -translate-x-1/2 -translate-y-1/2 divide-y-0 overflow-y-auto rounded-3xl bg-white shadow-lg backdrop:backdrop-blur-[5px] sm:mx-4 lg:mx-0"
|
||||
bodyClass="p-8"
|
||||
>
|
||||
{#if editing && config[editing.list][editing.index]}
|
||||
{@const { list, index } = editing}
|
||||
<div class="space-y-6">
|
||||
<Title level={2} variant="subsection">
|
||||
{$t(
|
||||
list === "navColumns"
|
||||
? "pages.admin.customize.footer.editColumn"
|
||||
: "pages.admin.customize.footer.editGroup",
|
||||
)}
|
||||
</Title>
|
||||
{@render languageTabsNav()}
|
||||
<div class={rowClass} data-field="{list}.{index}">
|
||||
{@render localizedInput(
|
||||
config[list][index].title,
|
||||
$t("pages.admin.customize.footer.fields.titlePlaceholder"),
|
||||
)}
|
||||
</div>
|
||||
{#if list === "navColumns"}
|
||||
{@render linkList(config.navColumns[index].links, `navColumns.${index}.links`)}
|
||||
{:else}
|
||||
{@render partnerList(
|
||||
config.partnerGroups[index].partners,
|
||||
`partnerGroups.${index}.partners`,
|
||||
)}
|
||||
{/if}
|
||||
<div class="flex justify-end">
|
||||
<Button class="w-fit" onclick={() => (isEditOpen = false)}>
|
||||
{$t("common.close")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<div class="grid gap-10 xl:grid-cols-2">
|
||||
<section class="space-y-4">
|
||||
{@render sectionHeader("legal", "pages.admin.customize.footer.sections.legal")}
|
||||
{@render linkList(config.legalLinks, "legalLinks")}
|
||||
</section>
|
||||
|
||||
<section class="space-y-4">
|
||||
{@render sectionHeader("social", "pages.admin.customize.footer.sections.social")}
|
||||
<ul class="space-y-3">
|
||||
{#each config.social as link, index (link)}
|
||||
<li class={rowClass} data-field="social.{index}">
|
||||
<Select bind:value={link.network} class="w-48">
|
||||
{#each FOOTER_SOCIAL_NETWORKS as network (network)}
|
||||
<option value={network}>
|
||||
{$t(`common.footer.a11y.social.${network}`)}
|
||||
</option>
|
||||
{/each}
|
||||
</Select>
|
||||
<div class="flex-1">
|
||||
<TextInput
|
||||
bind:value={link.href}
|
||||
placeholder={$t(
|
||||
"pages.admin.customize.footer.fields.socialPlaceholder",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{@render rowControls(config.social, index)}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="sm"
|
||||
class="w-fit"
|
||||
onclick={() => config.social.push({ network: "instagram", href: "" })}
|
||||
>
|
||||
{$t("pages.admin.customize.footer.actions.addSocial")}
|
||||
</Button>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<ActionableButton action={save} autoreset={2000} class="w-fit">
|
||||
{$t("common.save")}
|
||||
</ActionableButton>
|
||||
</form>
|
||||
|
||||
<ImageUploadModal
|
||||
bind:open={isUploadOpen}
|
||||
accept={["image/png", "image/jpeg", "image/webp"]}
|
||||
recommendedSize="300x120px"
|
||||
onConfirm={handleUpload}
|
||||
/>
|
||||
|
||||
<Toast floating variant="error" bind:showToast={showError}>{errorMessage}</Toast>
|
||||
<Toast floating variant="success" bind:showToast={showSaved}>
|
||||
{$t("pages.admin.customize.footer.saved")}
|
||||
</Toast>
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import LogoForm from "./LogoForm.svelte";
|
||||
import LogoHistory from "./LogoHistory.svelte";
|
||||
import LogoTabs from "./LogoTabs.svelte";
|
||||
import { t } from "../../../../i18n/store";
|
||||
import Toast from "../../../library/feedback/Toast.svelte";
|
||||
import Title from "../../../library/typography/Title.svelte";
|
||||
|
||||
import type { HeaderLogoRecord } from "../../../../repositories/headerLogo";
|
||||
|
||||
interface Props {
|
||||
logos: HeaderLogoRecord[];
|
||||
}
|
||||
|
||||
let { logos }: Props = $props();
|
||||
|
||||
let currentSubtab = $state("new");
|
||||
let showError = $state(false);
|
||||
let errorMessage = $state("");
|
||||
let logosList = $state(untrack(() => logos));
|
||||
|
||||
function handleTabChange(tabId: string) {
|
||||
currentSubtab = tabId;
|
||||
|
||||
// Re-fetch every time the history is opened, so it always shows the
|
||||
// latest logos regardless of when they were saved.
|
||||
if (tabId === "history") {
|
||||
refreshLogos();
|
||||
}
|
||||
}
|
||||
|
||||
// The list is passed in once by the page; after a save it must be refreshed
|
||||
// so the history shows the new logo without a full page reload.
|
||||
async function refreshLogos() {
|
||||
try {
|
||||
const { data, error } = await actions.getHeaderLogoData();
|
||||
|
||||
if (error) {
|
||||
errorMessage = error.message;
|
||||
showError = true;
|
||||
return;
|
||||
}
|
||||
|
||||
logosList = data?.logos ?? logosList;
|
||||
} catch (e) {
|
||||
errorMessage = e instanceof Error ? e.message : String(e);
|
||||
showError = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaved() {
|
||||
await refreshLogos();
|
||||
currentSubtab = "history";
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<Title level={2} variant="headline">
|
||||
{$t("pages.admin.customize.logo.title")}
|
||||
</Title>
|
||||
<p class="text-content text-base font-normal">
|
||||
{$t("pages.admin.customize.logo.description")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Toast floating variant="error" bind:showToast={showError}>{errorMessage}</Toast>
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<LogoTabs currentTab={currentSubtab} onTabChange={handleTabChange} />
|
||||
{#if currentSubtab === "new"}
|
||||
<LogoForm onSaved={handleSaved} />
|
||||
{:else if currentSubtab === "history"}
|
||||
<LogoHistory
|
||||
rows={logosList}
|
||||
onError={(message: string) => {
|
||||
errorMessage = message;
|
||||
showError = true;
|
||||
}}
|
||||
onSaved={refreshLogos}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,175 @@
|
||||
<script lang="ts">
|
||||
import { actions, isInputError } from "astro:actions";
|
||||
|
||||
import { t } from "../../../../i18n/store";
|
||||
import ActionableButton from "../../../library/buttons/ActionableButton.svelte";
|
||||
import Button from "../../../library/buttons/Button.svelte";
|
||||
import Toast from "../../../library/feedback/Toast.svelte";
|
||||
import ImageUploadModal from "../../../library/inputs/ImageUploadModal.svelte";
|
||||
import TextInput from "../../../library/inputs/TextInput.svelte";
|
||||
import Title from "../../../library/typography/Title.svelte";
|
||||
|
||||
import type { UploadedObject } from "../../../../utils/media/objectStorage.types";
|
||||
|
||||
interface Props {
|
||||
onSaved?: () => void;
|
||||
}
|
||||
|
||||
let { onSaved }: Props = $props();
|
||||
|
||||
type FieldErrors = Partial<Record<"altText", string>>;
|
||||
|
||||
let formElement: HTMLFormElement;
|
||||
|
||||
let media = $state<UploadedObject>();
|
||||
let altText = $state("Goteo");
|
||||
let isUploadOpen = $state(false);
|
||||
|
||||
let fieldErrors: FieldErrors = $state({});
|
||||
let mediaError = $state("");
|
||||
let errorMessage = $state("");
|
||||
let showError = $state(false);
|
||||
|
||||
function handleUpload(files: UploadedObject[]) {
|
||||
media = files[0];
|
||||
mediaError = "";
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
fieldErrors = {};
|
||||
mediaError = "";
|
||||
|
||||
if (!media) {
|
||||
mediaError = $t("pages.admin.customize.logo.errors.mediaRequired");
|
||||
return;
|
||||
}
|
||||
|
||||
const data = new FormData(formElement);
|
||||
|
||||
// The uploaded object is not a form field: hand the asset over explicitly.
|
||||
data.set("mediaUrl", media.url);
|
||||
data.set("mediaType", media.type);
|
||||
data.set("altText", altText.trim());
|
||||
|
||||
try {
|
||||
const { error } = await actions.createHeaderLogo(data);
|
||||
|
||||
if (error) {
|
||||
if (!isInputError(error)) {
|
||||
errorMessage = error.message;
|
||||
showError = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
fieldErrors = Object.fromEntries(
|
||||
Object.entries(error.fields).map(([field, issues]) => [field, issues?.[0]]),
|
||||
) as FieldErrors;
|
||||
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
// The action call itself threw (e.g. a network failure); do not
|
||||
// let ActionableButton swallow it silently.
|
||||
errorMessage = e instanceof Error ? e.message : String(e);
|
||||
showError = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
media = undefined;
|
||||
altText = "Goteo";
|
||||
|
||||
onSaved?.();
|
||||
}
|
||||
|
||||
async function handleSubmit(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
await submit();
|
||||
}
|
||||
</script>
|
||||
|
||||
<form bind:this={formElement} onsubmit={handleSubmit} class="flex max-w-167 flex-col gap-10">
|
||||
<div class="flex flex-col gap-6">
|
||||
<Title level={3} variant="subsection">
|
||||
{$t("pages.admin.customize.logo.fields.mediaTitle")}
|
||||
</Title>
|
||||
|
||||
<div
|
||||
class="border-grey flex w-full flex-col gap-6 rounded-2xl border bg-white p-6 shadow-sm sm:max-w-138"
|
||||
>
|
||||
<div class="flex flex-col">
|
||||
<p class="text-secondary text-base font-bold">
|
||||
{$t("pages.admin.customize.logo.fields.mediaLabel")}
|
||||
</p>
|
||||
|
||||
{#if media}
|
||||
<p class="text-content truncate text-base font-normal">{media.name}</p>
|
||||
{:else}
|
||||
<p class="text-content text-base font-normal">
|
||||
{$t("pages.admin.customize.logo.fields.mediaHint")}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if media}
|
||||
<div class="flex items-center justify-center rounded-lg bg-gray-50 p-6">
|
||||
<img
|
||||
src={media.url}
|
||||
alt={altText || media.name}
|
||||
class="max-h-24 w-auto max-w-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if mediaError}
|
||||
<p class="text-tertiary text-sm">{mediaError}</p>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<Button
|
||||
kind="secondary"
|
||||
size="sm"
|
||||
class="w-fit"
|
||||
onclick={() => (isUploadOpen = true)}
|
||||
>
|
||||
{$t("pages.admin.customize.logo.fields.mediaAdd")}
|
||||
</Button>
|
||||
|
||||
{#if media}
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="sm"
|
||||
class="w-fit"
|
||||
onclick={() => (media = undefined)}
|
||||
>
|
||||
{$t("common.remove")}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TextInput
|
||||
bind:value={altText}
|
||||
required
|
||||
labelText={$t("pages.admin.customize.logo.fields.altTextLabel")}
|
||||
placeholder={$t("pages.admin.customize.logo.fields.altTextPlaceholder")}
|
||||
error={fieldErrors.altText && $t(fieldErrors.altText)}
|
||||
class="sm:max-w-138"
|
||||
/>
|
||||
|
||||
<ActionableButton action={submit} autoreset={2000} class="w-fit px-6">
|
||||
{$t("common.save")}
|
||||
</ActionableButton>
|
||||
</form>
|
||||
|
||||
<Toast floating variant="error" bind:showToast={showError}>{errorMessage}</Toast>
|
||||
|
||||
<ImageUploadModal
|
||||
bind:open={isUploadOpen}
|
||||
accept={["image/png", "image/jpeg", "image/webp"]}
|
||||
multiple={false}
|
||||
recommendedSize="480x120px"
|
||||
onConfirm={handleUpload}
|
||||
/>
|
||||
@@ -0,0 +1,197 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { Modal, TableBodyCell } from "flowbite-svelte";
|
||||
import { tick, untrack } from "svelte";
|
||||
|
||||
import { t } from "../../../../i18n/store";
|
||||
import Eye from "../../../icons/media/Eye.svelte";
|
||||
import Close from "../../../icons/navigation/Close.svelte";
|
||||
import DeleteModal from "../../../library/feedback/DeleteModal.svelte";
|
||||
import DataTable from "../../../library/tables/DataTable.svelte";
|
||||
import Title from "../../../library/typography/Title.svelte";
|
||||
|
||||
import type { HeaderLogoRecord } from "../../../../repositories/headerLogo";
|
||||
import type { DataTableHeader } from "../../../library/tables/DataTable.svelte";
|
||||
|
||||
interface Props {
|
||||
rows: HeaderLogoRecord[];
|
||||
onError?: (message: string) => void;
|
||||
onSaved?: () => void;
|
||||
}
|
||||
|
||||
let { rows, onError, onSaved }: Props = $props();
|
||||
|
||||
let list = $state(untrack(() => rows));
|
||||
|
||||
// rows is refreshed after a save; keep the local list in sync, while the
|
||||
// local deletions below continue to apply on top of the incoming list.
|
||||
$effect(() => {
|
||||
list = rows;
|
||||
});
|
||||
|
||||
// Same rule as the repository's getActive(): rows come newest first, so
|
||||
// the first one is the one the header shows.
|
||||
const activeId = $derived(list[0]?.id);
|
||||
|
||||
type Status = "active" | "past";
|
||||
|
||||
function statusOf(row: HeaderLogoRecord): Status {
|
||||
return row.id === activeId ? "active" : "past";
|
||||
}
|
||||
|
||||
const STATUS_BADGES: Record<Status, string> = {
|
||||
active: "bg-green-100 text-green-800",
|
||||
past: "bg-gray-100 text-gray-500",
|
||||
};
|
||||
|
||||
const headers: DataTableHeader[] = [
|
||||
{ key: "pages.admin.customize.logo.history.headers.id", sortable: false, class: "w-16" },
|
||||
{ key: "pages.admin.customize.logo.history.headers.image", sortable: false },
|
||||
{ key: "pages.admin.customize.logo.history.headers.altText", sortable: false },
|
||||
{ key: "pages.admin.customize.logo.history.headers.status", sortable: false },
|
||||
{ key: "", sortable: false, class: "w-24" },
|
||||
];
|
||||
|
||||
const itemsPerPage = 10;
|
||||
let currentPage = $state(1);
|
||||
|
||||
const paginatedRows = $derived(
|
||||
list.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage),
|
||||
);
|
||||
|
||||
let isDeleteModalOpen = $state(false);
|
||||
let rowToDelete = $state<HeaderLogoRecord | null>(null);
|
||||
|
||||
function openDeleteModal(row: HeaderLogoRecord) {
|
||||
rowToDelete = row;
|
||||
isDeleteModalOpen = true;
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
const logo = rowToDelete;
|
||||
|
||||
if (!logo) return;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("id", String(logo.id));
|
||||
|
||||
const { error } = await actions.deleteHeaderLogo(formData);
|
||||
|
||||
isDeleteModalOpen = false;
|
||||
rowToDelete = null;
|
||||
|
||||
if (error) {
|
||||
onError?.(error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
list = list.filter((item) => item.id !== logo.id);
|
||||
|
||||
// The parent list is also refreshed so the header statuses follow.
|
||||
onSaved?.();
|
||||
|
||||
// Let the updated rows reach the table before clamping.
|
||||
await tick();
|
||||
|
||||
// Deleting the last row of the last page would leave an empty table.
|
||||
if (currentPage > 1 && (currentPage - 1) * itemsPerPage >= list.length) {
|
||||
currentPage -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
let isPreviewOpen = $state(false);
|
||||
let previewRow = $state<HeaderLogoRecord | null>(null);
|
||||
|
||||
function openPreview(row: HeaderLogoRecord) {
|
||||
previewRow = row;
|
||||
isPreviewOpen = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<Title level={3} variant="subsection">
|
||||
{$t("pages.admin.customize.logo.history.title")}
|
||||
</Title>
|
||||
<p class="text-content">{$t("pages.admin.customize.logo.history.description")}</p>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
{headers}
|
||||
rows={paginatedRows}
|
||||
isLoading={false}
|
||||
emptyMessage="pages.admin.customize.logo.history.noData"
|
||||
{currentPage}
|
||||
totalItems={list.length}
|
||||
{itemsPerPage}
|
||||
onPageChange={(page) => (currentPage = page)}
|
||||
>
|
||||
{#snippet children(row)}
|
||||
<TableBodyCell class="border-variant1 w-16 rounded-l-md border-t border-b border-l p-4">
|
||||
{row.id}
|
||||
</TableBodyCell>
|
||||
<TableBodyCell class="border-variant1 border-t border-b p-4">
|
||||
<img
|
||||
src={row.mediaUrl}
|
||||
alt={row.altText}
|
||||
class="max-h-10 w-auto max-w-40 object-contain"
|
||||
/>
|
||||
</TableBodyCell>
|
||||
<TableBodyCell class="border-variant1 max-w-80 truncate border-t border-b p-4">
|
||||
{row.altText}
|
||||
</TableBodyCell>
|
||||
<TableBodyCell class="border-variant1 border-t border-b p-4">
|
||||
{@const status = statusOf(row)}
|
||||
<span
|
||||
class="flex w-fit items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold whitespace-nowrap {STATUS_BADGES[
|
||||
status
|
||||
]}"
|
||||
>
|
||||
<span class="size-1.5 rounded-full bg-current"></span>
|
||||
{$t(`pages.admin.customize.logo.history.status.${status}`)}
|
||||
</span>
|
||||
</TableBodyCell>
|
||||
<TableBodyCell class="border-variant1 w-24 rounded-r-md border-t border-r border-b p-4">
|
||||
<div class="flex items-center justify-end gap-3">
|
||||
<button
|
||||
class="text-secondary cursor-pointer transition-transform duration-200 hover:scale-110"
|
||||
aria-label={$t("common.preview")}
|
||||
onclick={() => openPreview(row)}
|
||||
>
|
||||
<Eye class="size-5" />
|
||||
</button>
|
||||
<button
|
||||
class="text-secondary cursor-pointer transition-transform duration-200 hover:scale-110"
|
||||
aria-label={$t("common.delete")}
|
||||
onclick={() => openDeleteModal(row)}
|
||||
>
|
||||
<Close class="size-5" />
|
||||
</button>
|
||||
</div>
|
||||
</TableBodyCell>
|
||||
{/snippet}
|
||||
</DataTable>
|
||||
|
||||
<Modal
|
||||
bind:open={isPreviewOpen}
|
||||
closeBtnClass="top-7 end-7 cursor-pointer bg-transparent text-secondary hover:bg-transparent hover:text-secondary hover:scale-110 transition-transform duration-200 transform focus:ring-0 shadow-none dark:text-secondary dark:hover:text-secondary dark:hover:bg-transparent"
|
||||
class="backdrop:bg-overlay fixed top-1/2 left-1/2 mx-2 flex w-fit max-w-[min(46rem,calc(100vw-1rem))] -translate-x-1/2 -translate-y-1/2 divide-y-0 rounded-3xl bg-white shadow-lg backdrop:backdrop-blur-[5px] sm:mx-4 lg:mx-0"
|
||||
bodyClass="border-grey max-h-[90vh] overflow-y-auto rounded-3xl bg-white p-6"
|
||||
>
|
||||
{#if previewRow}
|
||||
<div class="flex flex-col gap-4">
|
||||
<img
|
||||
src={previewRow.mediaUrl}
|
||||
alt={previewRow.altText}
|
||||
class="max-h-60 w-auto max-w-full object-contain"
|
||||
/>
|
||||
<p class="text-content text-base">{previewRow.altText}</p>
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<DeleteModal
|
||||
bind:open={isDeleteModalOpen}
|
||||
title={$t("pages.admin.customize.logo.history.deleteModal.title")}
|
||||
description={$t("pages.admin.customize.logo.history.deleteModal.description")}
|
||||
onclick={confirmDelete}
|
||||
/>
|
||||
@@ -0,0 +1,39 @@
|
||||
<script lang="ts">
|
||||
import { t } from "../../../../i18n/store";
|
||||
import PlusIcon from "../../../icons/actions/PlusIcon.svelte";
|
||||
import Clock from "../../../icons/Clock.svelte";
|
||||
|
||||
interface Props {
|
||||
currentTab: string;
|
||||
onTabChange: (tabId: string) => void;
|
||||
}
|
||||
|
||||
let { currentTab, onTabChange }: Props = $props();
|
||||
|
||||
function tabClass(tabId: string): string {
|
||||
return currentTab === tabId
|
||||
? "border-primary text-secondary"
|
||||
: "border-variant1 text-content";
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex gap-0">
|
||||
<button
|
||||
class="hover:bg-primary-dark flex w-fit cursor-pointer items-center gap-2 rounded-t-lg border-b-2 px-6 py-2 text-base font-bold {tabClass(
|
||||
'new',
|
||||
)}"
|
||||
onclick={() => onTabChange("new")}
|
||||
>
|
||||
<PlusIcon class="text-secondary size-4" />
|
||||
{$t("pages.admin.customize.logo.tabs.new")}
|
||||
</button>
|
||||
<button
|
||||
class="hover:bg-primary-dark flex w-fit cursor-pointer items-center gap-2 rounded-t-lg border-b-2 px-6 py-2 text-base font-bold {tabClass(
|
||||
'history',
|
||||
)}"
|
||||
onclick={() => onTabChange("history")}
|
||||
>
|
||||
<Clock class="text-secondary size-4" />
|
||||
{$t("pages.admin.customize.logo.tabs.history")}
|
||||
</button>
|
||||
</div>
|
||||
@@ -89,4 +89,5 @@
|
||||
{labels}
|
||||
search={searchUsers}
|
||||
onSave={saveUsers}
|
||||
draftId="admin-featured-users"
|
||||
/>
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { Modal } from "flowbite-svelte";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import ProjectPickerModal, { type PickedProject } from "./ProjectPickerModal.svelte";
|
||||
import ProjectSlotCard from "./ProjectSlotCard.svelte";
|
||||
import { t } from "../../../i18n/store";
|
||||
import { apiProjectsGetCollection } from "../../../openapi/client/sdk.gen";
|
||||
import { debounce } from "../../../utils/debounce";
|
||||
import { toCollectionItems } from "../../../utils/hydra";
|
||||
import ActionableButton from "../../library/buttons/ActionableButton.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import DropdownMenu from "../../library/dropdown/DropdownMenu.svelte";
|
||||
import Toast from "../../library/feedback/Toast.svelte";
|
||||
import RadioButton from "../../library/inputs/RadioButton.svelte";
|
||||
import Select from "../../library/inputs/Select.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
import type { Project } from "../../../openapi/client/types.gen";
|
||||
import type { DropdownOption } from "../../library/dropdown/dropdown.types";
|
||||
|
||||
interface SlotAssignment {
|
||||
position: number;
|
||||
projectId: number;
|
||||
@@ -67,18 +61,14 @@
|
||||
},
|
||||
];
|
||||
|
||||
let type = $state(config.highlight?.type ?? "recent");
|
||||
let layout = $state(config.highlight?.layout ?? "2x3");
|
||||
let type = $state(untrack(() => config.highlight?.type ?? "recent"));
|
||||
let layout = $state(untrack(() => config.highlight?.layout ?? "2x3"));
|
||||
let addOpen = $state(false);
|
||||
let projectQuery = $state("");
|
||||
let searchOptions = $state<DropdownOption[]>([]);
|
||||
let selectedOption = $state<DropdownOption[]>([]);
|
||||
let editingSlotIndex = $state<number | null>(null);
|
||||
let searchResults: Project[] = [];
|
||||
let showError = $state(false);
|
||||
let errorMessage = $state("");
|
||||
|
||||
let slotAssignments = $state<SlotAssignment[]>(config.slots);
|
||||
let slotAssignments = $state<SlotAssignment[]>(untrack(() => config.slots));
|
||||
|
||||
let slotCount = $derived(LAYOUTS.find((l) => l.id === layout)?.rows.flat().length ?? 0);
|
||||
|
||||
@@ -86,57 +76,22 @@
|
||||
Array.from({ length: slotCount }, (_, i) => slotAssignments.find((a) => a.position === i)),
|
||||
);
|
||||
|
||||
const searchProjects = debounce(async (title: string) => {
|
||||
const { data, error } = await apiProjectsGetCollection({
|
||||
baseUrl: "/api/relay",
|
||||
headers: { Accept: "application/ld+json" },
|
||||
query: { title, itemsPerPage: 10 },
|
||||
});
|
||||
|
||||
if (error) console.error("Project search failed:", error);
|
||||
|
||||
searchResults = toCollectionItems<Project>(data);
|
||||
searchOptions = searchResults.map((p) => ({
|
||||
id: String(p.id),
|
||||
label: p.title ?? p.slug ?? "",
|
||||
selected: false,
|
||||
}));
|
||||
});
|
||||
|
||||
function handleSearch(query: string) {
|
||||
const trimmed = query.trim();
|
||||
|
||||
if (trimmed.length < 2) {
|
||||
searchProjects.cancel();
|
||||
searchOptions = [];
|
||||
return;
|
||||
}
|
||||
|
||||
searchProjects(trimmed);
|
||||
}
|
||||
|
||||
function handleAddProject(slotIndex: number) {
|
||||
editingSlotIndex = slotIndex;
|
||||
projectQuery = "";
|
||||
searchOptions = [];
|
||||
selectedOption = [];
|
||||
addOpen = true;
|
||||
}
|
||||
|
||||
function handleConfirmAdd() {
|
||||
if (editingSlotIndex === null || selectedOption.length === 0) return;
|
||||
const chosen = selectedOption[0];
|
||||
const project = searchResults.find((p) => String(p.id) === chosen.id);
|
||||
function handleConfirmAdd(project: PickedProject) {
|
||||
if (editingSlotIndex === null) return;
|
||||
slotAssignments = [
|
||||
...slotAssignments.filter((a) => a.position !== editingSlotIndex),
|
||||
{
|
||||
position: editingSlotIndex,
|
||||
projectId: Number(chosen.id),
|
||||
projectTitle: chosen.label,
|
||||
projectImage: project?.video?.thumbnail ?? project?.cover ?? null,
|
||||
projectId: project.id,
|
||||
projectTitle: project.title,
|
||||
projectImage: project.image,
|
||||
},
|
||||
];
|
||||
addOpen = false;
|
||||
editingSlotIndex = null;
|
||||
}
|
||||
|
||||
@@ -232,48 +187,13 @@
|
||||
</div>
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
{#each slots as slot, index (index)}
|
||||
<div class="border-grey flex flex-col items-start gap-2 rounded-2xl border p-4">
|
||||
<p class="text-secondary font-bold">
|
||||
{$t("pages.admin.home.highlights.projects.slot", {
|
||||
number: String(index + 1).padStart(2, "0"),
|
||||
})}
|
||||
</p>
|
||||
{#if slot}
|
||||
{#if slot.projectImage}
|
||||
<img
|
||||
src={slot.projectImage}
|
||||
alt={slot.projectTitle}
|
||||
class="aspect-video w-full rounded-lg object-cover"
|
||||
/>
|
||||
{/if}
|
||||
<p class="text-content text-body-small font-medium">
|
||||
{slot.projectTitle}
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<Button
|
||||
kind="secondary"
|
||||
size="sm"
|
||||
onclick={() => handleAddProject(index)}
|
||||
>
|
||||
{$t("pages.admin.home.highlights.projects.replace")}
|
||||
</Button>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="sm"
|
||||
onclick={() => handleRemoveProject(index)}
|
||||
>
|
||||
{$t("pages.admin.home.highlights.projects.remove")}
|
||||
</Button>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-content text-body-small">
|
||||
{$t("pages.admin.home.highlights.projects.empty")}
|
||||
</p>
|
||||
<Button kind="secondary" size="sm" onclick={() => handleAddProject(index)}>
|
||||
{$t("pages.admin.home.highlights.projects.add")}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
<ProjectSlotCard
|
||||
slotNumber={index + 1}
|
||||
project={slot ? { title: slot.projectTitle, image: slot.projectImage } : null}
|
||||
onAdd={() => handleAddProject(index)}
|
||||
onReplace={() => handleAddProject(index)}
|
||||
onRemove={() => handleRemoveProject(index)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
@@ -281,51 +201,11 @@
|
||||
|
||||
<Toast floating variant="error" bind:showToast={showError}>{errorMessage}</Toast>
|
||||
|
||||
<Modal
|
||||
<ProjectPickerModal
|
||||
bind:open={addOpen}
|
||||
closeBtnClass="top-3 end-3 cursor-pointer bg-transparent text-secondary hover:bg-transparent hover:text-secondary hover:scale-110 transition-transform duration-200 transform focus:ring-0 shadow-none dark:text-secondary dark:hover:text-secondary dark:hover:bg-transparent"
|
||||
class="fixed top-1/2 left-1/2 mx-2 flex w-full max-w-172 -translate-x-1/2 -translate-y-1/2 flex-col gap-6 divide-y-0 overflow-visible rounded-3xl bg-white p-6 shadow-lg backdrop:bg-[#878282B2] backdrop:backdrop-blur-[5px] sm:mx-4 lg:mx-0"
|
||||
headerClass="md:p-0 p-0 border-none"
|
||||
bodyClass="md:p-0 p-0 border-none overflow-y-visible"
|
||||
footerClass="md:p-0 p-0 border-none flex items-center justify-end gap-4"
|
||||
>
|
||||
{#snippet header()}
|
||||
<Title level={2} variant="subsection">
|
||||
{$t("pages.admin.home.highlights.projects.modal.title")}
|
||||
</Title>
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-6">
|
||||
<p class="text-content text-base font-normal">
|
||||
{$t("pages.admin.home.highlights.projects.modal.description")}
|
||||
</p>
|
||||
<div class="relative">
|
||||
{#if projectQuery}
|
||||
<span
|
||||
class="text-secondary absolute top-0 left-4 z-10 -translate-y-1/2 transform bg-white px-1 text-sm font-medium"
|
||||
>
|
||||
{$t("pages.admin.home.highlights.projects.modal.search")}
|
||||
</span>
|
||||
{/if}
|
||||
<DropdownMenu
|
||||
variant="basic"
|
||||
hasSearch
|
||||
singleSelect
|
||||
clearable
|
||||
options={searchOptions}
|
||||
bind:selected={selectedOption}
|
||||
bind:searchValue={projectQuery}
|
||||
onSearch={handleSearch}
|
||||
searchClasses="rounded-3xl border-secondary shadow-none"
|
||||
searchPlaceholder={$t("pages.admin.home.highlights.projects.modal.search")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#snippet footer()}
|
||||
<Button kind="ghost" onclick={() => (addOpen = false)} class="w-fit">
|
||||
{$t("common.cancel")}
|
||||
</Button>
|
||||
<Button onclick={handleConfirmAdd} class="w-fit">
|
||||
{$t("pages.admin.home.highlights.projects.modal.submit")}
|
||||
</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
title={$t("pages.admin.home.highlights.projects.modal.title")}
|
||||
description={$t("pages.admin.home.highlights.projects.modal.description")}
|
||||
searchLabel={$t("pages.admin.home.highlights.projects.modal.search")}
|
||||
submitLabel={$t("pages.admin.home.highlights.projects.modal.submit")}
|
||||
onConfirm={handleConfirmAdd}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
<!--
|
||||
Project Picker Modal - reusable admin modal to search and pick a project.
|
||||
|
||||
Searches the platform projects (debounced, min 2 chars) via the API relay
|
||||
and reports the chosen project through `onConfirm`. Closing the modal (or
|
||||
confirming) resets the search state.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { Modal } from "flowbite-svelte";
|
||||
|
||||
import { t } from "../../../i18n/store";
|
||||
import { apiProjectsGetCollection } from "../../../openapi/client/sdk.gen";
|
||||
import { toCollectionItems } from "../../../utils/hydra";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import DropdownSearch from "../../library/dropdown/DropdownSearch.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
import type { Project } from "../../../openapi/client/types.gen";
|
||||
import type { DropdownOption } from "../../library/dropdown/dropdown.types";
|
||||
|
||||
export interface PickedProject {
|
||||
id: number;
|
||||
title: string;
|
||||
image: string | null;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
title: string;
|
||||
description?: string;
|
||||
searchLabel?: string;
|
||||
submitLabel?: string;
|
||||
onConfirm: (project: PickedProject) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
title,
|
||||
description,
|
||||
searchLabel,
|
||||
submitLabel,
|
||||
onConfirm,
|
||||
}: Props = $props();
|
||||
|
||||
let projectQuery = $state("");
|
||||
let selectedOption = $state<DropdownOption[]>([]);
|
||||
let searchResults: Project[] = [];
|
||||
|
||||
// Reset the search state every time the modal opens, so a previous pick
|
||||
// never lingers when it is reused for another slot.
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
projectQuery = "";
|
||||
selectedOption = [];
|
||||
searchResults = [];
|
||||
}
|
||||
});
|
||||
|
||||
async function searchProjects(title: string, signal: AbortSignal): Promise<DropdownOption[]> {
|
||||
const { data, error } = await apiProjectsGetCollection({
|
||||
baseUrl: "/api/relay",
|
||||
headers: { Accept: "application/ld+json" },
|
||||
query: { title, itemsPerPage: 10 },
|
||||
signal,
|
||||
});
|
||||
|
||||
if (error) console.error("Project search failed:", error);
|
||||
|
||||
const results = toCollectionItems<Project>(data);
|
||||
// A superseded search must not replace the results `handleConfirm` looks into.
|
||||
if (!signal.aborted) searchResults = results;
|
||||
|
||||
return results.map((p) => ({
|
||||
id: String(p.id),
|
||||
label: p.title ?? p.slug ?? "",
|
||||
selected: false,
|
||||
}));
|
||||
}
|
||||
|
||||
function handleConfirm() {
|
||||
if (selectedOption.length === 0) return;
|
||||
const chosen = selectedOption[0];
|
||||
const project = searchResults.find((p) => String(p.id) === chosen.id);
|
||||
onConfirm({
|
||||
id: Number(chosen.id),
|
||||
title: chosen.label,
|
||||
image: project?.video?.thumbnail ?? project?.cover ?? null,
|
||||
});
|
||||
open = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal
|
||||
bind:open
|
||||
closeBtnClass="top-3 end-3 cursor-pointer bg-transparent text-secondary hover:bg-transparent hover:text-secondary hover:scale-110 transition-transform duration-200 transform focus:ring-0 shadow-none dark:text-secondary dark:hover:text-secondary dark:hover:bg-transparent"
|
||||
class="fixed top-1/2 left-1/2 mx-2 flex w-full max-w-172 -translate-x-1/2 -translate-y-1/2 flex-col gap-6 divide-y-0 overflow-visible rounded-3xl bg-white p-6 shadow-lg backdrop:bg-[#878282B2] backdrop:backdrop-blur-[5px] sm:mx-4 lg:mx-0"
|
||||
headerClass="md:p-0 p-0 border-none"
|
||||
bodyClass="md:p-0 p-0 border-none overflow-y-visible"
|
||||
footerClass="md:p-0 p-0 border-none flex items-center justify-end gap-4"
|
||||
>
|
||||
{#snippet header()}
|
||||
<Title level={2} variant="subsection">{title}</Title>
|
||||
{/snippet}
|
||||
<div class="flex flex-col gap-6">
|
||||
{#if description}
|
||||
<p class="text-content text-base font-normal">{description}</p>
|
||||
{/if}
|
||||
<div class="relative">
|
||||
{#if projectQuery && searchLabel}
|
||||
<span
|
||||
class="text-secondary absolute top-0 left-4 z-10 -translate-y-1/2 transform bg-white px-1 text-sm font-medium"
|
||||
>
|
||||
{searchLabel}
|
||||
</span>
|
||||
{/if}
|
||||
<DropdownSearch
|
||||
variant="basic"
|
||||
singleSelect
|
||||
clearable
|
||||
search={searchProjects}
|
||||
minChars={2}
|
||||
bind:selected={selectedOption}
|
||||
bind:value={projectQuery}
|
||||
searchClasses="rounded-3xl border-secondary shadow-none"
|
||||
placeholder={searchLabel ?? $t("common.search")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#snippet footer()}
|
||||
<Button kind="ghost" onclick={() => (open = false)} class="w-fit">
|
||||
{$t("common.cancel")}
|
||||
</Button>
|
||||
<Button onclick={handleConfirm} class="w-fit">{submitLabel ?? $t("common.add")}</Button>
|
||||
{/snippet}
|
||||
</Modal>
|
||||
@@ -0,0 +1,137 @@
|
||||
<!--
|
||||
Project Slot Card - reusable admin card for a project slot in a grid.
|
||||
|
||||
Variants:
|
||||
- "fixed": image on the left + slot content on the right (24px gap). The
|
||||
content is a title/subtitle group at the top and the action buttons at
|
||||
the bottom, separated by auto space (justify-between). When a project is
|
||||
selected the title is the project title and the subtitle is its carousel
|
||||
position; the empty state shows the slot label ("Proyecto NN") plus the
|
||||
helper text instead.
|
||||
- onRemove: clears the project from the slot, rendered as an "X" icon
|
||||
button on filled cards (optional).
|
||||
- onRemoveSlot: deletes the whole slot card, rendered as a trash icon
|
||||
button on empty cards (opt-in; only used by proposed campaigns, other
|
||||
consumers keep non-deletable slots).
|
||||
- "add": standalone trailing card (title + subtitle + ghost button) used to
|
||||
append a new slot to the grid.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
import { t } from "../../../i18n/store";
|
||||
import PlusIcon from "../../icons/actions/PlusIcon.svelte";
|
||||
import Trash from "../../icons/actions/Trash.svelte";
|
||||
import Close from "../../icons/navigation/Close.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
interface Props {
|
||||
slotNumber?: number;
|
||||
project?: { title: string; image: string | null } | null;
|
||||
variant?: "fixed" | "add";
|
||||
onAdd?: () => void;
|
||||
onReplace?: () => void;
|
||||
onRemove?: () => void;
|
||||
onRemoveSlot?: () => void;
|
||||
class?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
slotNumber,
|
||||
project = null,
|
||||
variant = "fixed",
|
||||
onAdd,
|
||||
onReplace,
|
||||
onRemove,
|
||||
onRemoveSlot,
|
||||
class: className = "",
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
{#if variant === "add"}
|
||||
<div
|
||||
class={twMerge(
|
||||
"border-grey bg-grey flex flex-col gap-6 rounded-3xl border-1 p-6",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div class="flex flex-col gap-1">
|
||||
<Title level={2} variant="field" color="secondary" class="text-base">
|
||||
{$t("pages.admin.slotCard.addTitle")}
|
||||
</Title>
|
||||
<p class="text-content text-base font-normal">
|
||||
{$t("pages.admin.slotCard.addSubtitle")}
|
||||
</p>
|
||||
</div>
|
||||
<Button class="w-fit" kind="ghost" size="sm" onclick={() => onAdd?.()}>
|
||||
<PlusIcon class="size-4" />
|
||||
{$t("pages.admin.slotCard.addMore")}
|
||||
</Button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class={twMerge("border-grey flex gap-6 rounded-2xl border p-4", className)}>
|
||||
{#if project?.image}
|
||||
<img
|
||||
src={project.image}
|
||||
alt={project.title}
|
||||
class="aspect-square size-30 shrink-0 self-start rounded-2xl object-cover"
|
||||
/>
|
||||
{/if}
|
||||
<div class="flex min-w-0 flex-1 flex-col items-start justify-between gap-4">
|
||||
{#if project}
|
||||
<div class="flex flex-col gap-1">
|
||||
<p class="text-secondary font-bold">{project.title}</p>
|
||||
{#if slotNumber !== undefined}
|
||||
<p class="text-content text-body-small font-normal">
|
||||
{$t("pages.admin.slotCard.position", {
|
||||
number: String(slotNumber).padStart(2, "0"),
|
||||
})}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button kind="secondary" size="sm" onclick={() => onReplace?.()}>
|
||||
{$t("pages.admin.slotCard.replace")}
|
||||
</Button>
|
||||
{#if onRemove}
|
||||
<button
|
||||
type="button"
|
||||
class="text-secondary cursor-pointer transition-transform duration-200 hover:scale-110"
|
||||
aria-label={$t("pages.admin.slotCard.remove")}
|
||||
onclick={() => onRemove?.()}
|
||||
>
|
||||
<Close class="size-5" />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-1">
|
||||
{#if slotNumber !== undefined}
|
||||
<p class="text-secondary font-bold">
|
||||
{$t("pages.admin.slotCard.slot", {
|
||||
number: String(slotNumber).padStart(2, "0"),
|
||||
})}
|
||||
</p>
|
||||
{/if}
|
||||
<p class="text-content text-body-small">{$t("pages.admin.slotCard.empty")}</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button kind="secondary" size="sm" onclick={() => onAdd?.()}>
|
||||
{$t("pages.admin.slotCard.add")}
|
||||
</Button>
|
||||
{#if onRemoveSlot}
|
||||
<button
|
||||
type="button"
|
||||
class="text-secondary cursor-pointer transition-transform duration-200 hover:scale-110"
|
||||
aria-label={$t("common.delete")}
|
||||
onclick={() => onRemoveSlot?.()}
|
||||
>
|
||||
<Trash class="size-5" />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,179 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import ProjectPickerModal, { type PickedProject } from "./ProjectPickerModal.svelte";
|
||||
import ProjectSlotCard from "./ProjectSlotCard.svelte";
|
||||
import { t } from "../../../i18n/store";
|
||||
import CampaignsTabsNav from "../../home/CampaignsTabsNav.svelte";
|
||||
import ActionableButton from "../../library/buttons/ActionableButton.svelte";
|
||||
import Toast from "../../library/feedback/Toast.svelte";
|
||||
import Grid from "../../library/layout/Grid.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
import type { ProposedCampaignTab } from "../../../repositories/proposedCampaigns";
|
||||
|
||||
interface SlotAssignment {
|
||||
tab: ProposedCampaignTab;
|
||||
position: number;
|
||||
// null project = empty slot (added from the grid, not yet filled)
|
||||
projectId: number | null;
|
||||
projectTitle: string | null;
|
||||
projectImage: string | null;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
config: {
|
||||
slots: SlotAssignment[];
|
||||
};
|
||||
}
|
||||
|
||||
let { config }: Props = $props();
|
||||
|
||||
let activeTab = $state<ProposedCampaignTab>("ending-soon");
|
||||
let pickerOpen = $state(false);
|
||||
let editingIndex = $state<number | null>(null);
|
||||
let showError = $state(false);
|
||||
let errorMessage = $state("");
|
||||
|
||||
// Seeded once: later prop changes must not overwrite what the admin is editing
|
||||
const initialSlots = untrack(() => config.slots);
|
||||
|
||||
// Slots are grouped per tab; the array order within a tab is the display
|
||||
// order (top to bottom, left to right) and becomes the saved position.
|
||||
let slotsByTab = $state<Record<ProposedCampaignTab, SlotAssignment[]>>({
|
||||
"ending-soon": initialSlots
|
||||
.filter((s) => s.tab === "ending-soon")
|
||||
.sort((a, b) => a.position - b.position),
|
||||
"most-successful": initialSlots
|
||||
.filter((s) => s.tab === "most-successful")
|
||||
.sort((a, b) => a.position - b.position),
|
||||
});
|
||||
|
||||
let activeSlots = $derived(slotsByTab[activeTab]);
|
||||
|
||||
function handleTabChange(tabId: string) {
|
||||
activeTab = tabId as ProposedCampaignTab;
|
||||
}
|
||||
|
||||
function openPicker(index: number) {
|
||||
editingIndex = index;
|
||||
pickerOpen = true;
|
||||
}
|
||||
|
||||
function appendSlot() {
|
||||
const list = slotsByTab[activeTab];
|
||||
const empty: SlotAssignment = {
|
||||
tab: activeTab,
|
||||
position: list.length,
|
||||
projectId: null,
|
||||
projectTitle: null,
|
||||
projectImage: null,
|
||||
};
|
||||
slotsByTab = { ...slotsByTab, [activeTab]: [...list, empty] };
|
||||
}
|
||||
|
||||
function handleConfirmPick(project: PickedProject) {
|
||||
if (editingIndex === null) return;
|
||||
|
||||
const picked: SlotAssignment = {
|
||||
tab: activeTab,
|
||||
position: editingIndex,
|
||||
projectId: project.id,
|
||||
projectTitle: project.title,
|
||||
projectImage: project.image,
|
||||
};
|
||||
|
||||
slotsByTab = {
|
||||
...slotsByTab,
|
||||
[activeTab]: slotsByTab[activeTab].map((s, i) => (i === editingIndex ? picked : s)),
|
||||
};
|
||||
editingIndex = null;
|
||||
}
|
||||
|
||||
function handleClearProject(index: number) {
|
||||
slotsByTab = {
|
||||
...slotsByTab,
|
||||
[activeTab]: slotsByTab[activeTab].map((s, i) =>
|
||||
i === index ? { ...s, projectId: null, projectTitle: null, projectImage: null } : s,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function handleRemoveSlot(index: number) {
|
||||
slotsByTab = {
|
||||
...slotsByTab,
|
||||
[activeTab]: slotsByTab[activeTab].filter((_, i) => i !== index),
|
||||
};
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
const { error } = await actions.saveProposedCampaigns({
|
||||
"ending-soon": slotsByTab["ending-soon"]
|
||||
.map((s) => s.projectId)
|
||||
.filter((id): id is number => id !== null),
|
||||
"most-successful": slotsByTab["most-successful"]
|
||||
.map((s) => s.projectId)
|
||||
.filter((id): id is number => id !== null),
|
||||
});
|
||||
|
||||
if (error) {
|
||||
errorMessage = error.message;
|
||||
showError = true;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-10">
|
||||
<header class="flex flex-col justify-between gap-6 sm:flex-row sm:items-start">
|
||||
<div class="flex max-w-150 flex-col gap-2">
|
||||
<Title level={2} variant="headline">{$t("pages.admin.home.proposed.title")}</Title>
|
||||
<p class="text-content text-base font-normal">
|
||||
{$t("pages.admin.home.proposed.description")}
|
||||
</p>
|
||||
</div>
|
||||
<ActionableButton action={handleSave} autoreset={2000} class="w-fit shrink-0 px-6">
|
||||
{$t("pages.admin.home.proposed.save")}
|
||||
</ActionableButton>
|
||||
</header>
|
||||
|
||||
<section class="flex flex-col gap-6">
|
||||
<div class="flex flex-col gap-2">
|
||||
<Title level={3} variant="subsection">
|
||||
{$t("pages.admin.home.proposed.projects.title")}
|
||||
</Title>
|
||||
<p class="text-content text-body-small">
|
||||
{$t("pages.admin.home.proposed.projects.description")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<CampaignsTabsNav {activeTab} onTabChange={handleTabChange} alignment="left" />
|
||||
|
||||
<Grid class="grid-cols-1 md:grid-cols-2 lg:grid-cols-2">
|
||||
{#each activeSlots as slot, index (index)}
|
||||
<ProjectSlotCard
|
||||
slotNumber={index + 1}
|
||||
project={slot.projectId !== null && slot.projectTitle !== null
|
||||
? { title: slot.projectTitle, image: slot.projectImage }
|
||||
: null}
|
||||
onAdd={() => openPicker(index)}
|
||||
onReplace={() => openPicker(index)}
|
||||
onRemove={() => handleClearProject(index)}
|
||||
onRemoveSlot={() => handleRemoveSlot(index)}
|
||||
/>
|
||||
{/each}
|
||||
<ProjectSlotCard variant="add" onAdd={appendSlot} />
|
||||
</Grid>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<Toast floating variant="error" bind:showToast={showError}>{errorMessage}</Toast>
|
||||
|
||||
<ProjectPickerModal
|
||||
bind:open={pickerOpen}
|
||||
title={$t("pages.admin.home.proposed.modal.title")}
|
||||
description={$t("pages.admin.home.proposed.modal.description")}
|
||||
searchLabel={$t("pages.admin.home.proposed.modal.search")}
|
||||
submitLabel={$t("pages.admin.home.proposed.modal.submit")}
|
||||
onConfirm={handleConfirmPick}
|
||||
/>
|
||||
@@ -5,6 +5,7 @@
|
||||
import { locale, t } from "../../../../i18n/store";
|
||||
import { getDefaultLanguage } from "../../../../utils/consts";
|
||||
import { endOfDay, formatDate, startOfDay } from "../../../../utils/dates";
|
||||
import { useFormDraft, restoreFields } from "../../../../utils/forms/useFormDraft.svelte";
|
||||
import { getLanguageDisplayName, primaryLanguage } from "../../../../utils/lang";
|
||||
import ActionableButton from "../../../library/buttons/ActionableButton.svelte";
|
||||
import Toast from "../../../library/feedback/Toast.svelte";
|
||||
@@ -42,19 +43,19 @@
|
||||
const defaultLanguage = getDefaultLanguage();
|
||||
|
||||
// Every language's texts live here, the base one included, and are saved together.
|
||||
let texts = $state<Record<string, BannerTexts>>(
|
||||
initial
|
||||
? Object.fromEntries(
|
||||
initial.languages.map((code) => [
|
||||
code,
|
||||
{
|
||||
...emptyTexts(),
|
||||
...(code === initial.language ? initial : initial.translations[code]),
|
||||
},
|
||||
]),
|
||||
)
|
||||
: { [defaultLanguage]: emptyTexts() },
|
||||
);
|
||||
const initialTexts: Record<string, BannerTexts> = initial
|
||||
? Object.fromEntries(
|
||||
initial.languages.map((code) => [
|
||||
code,
|
||||
{
|
||||
...emptyTexts(),
|
||||
...(code === initial.language ? initial : initial.translations[code]),
|
||||
},
|
||||
]),
|
||||
)
|
||||
: { [defaultLanguage]: emptyTexts() };
|
||||
|
||||
let texts = $state<Record<string, BannerTexts>>(initialTexts);
|
||||
let languages = $state<string[]>(initial?.languages ?? [defaultLanguage]);
|
||||
let selectedLanguage = $state(untrack(() => languages[0]));
|
||||
const active = $derived(texts[selectedLanguage]);
|
||||
@@ -93,6 +94,37 @@
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Nothing in this form is sensitive, so all of it can be kept.
|
||||
*/
|
||||
const { restored } = useFormDraft("admin-home-banner", () => ({
|
||||
texts,
|
||||
languages,
|
||||
selectedLanguage,
|
||||
startsAt: startsAt.toISOString(),
|
||||
endsAt: endsAt.toISOString(),
|
||||
}));
|
||||
|
||||
if (restored) {
|
||||
restoreFields(texts, restored.texts);
|
||||
|
||||
if (restored.languages) {
|
||||
languages = restored.languages;
|
||||
}
|
||||
|
||||
if (restored.selectedLanguage) {
|
||||
selectedLanguage = restored.selectedLanguage;
|
||||
}
|
||||
|
||||
if (restored.startsAt) {
|
||||
startsAt = new Date(restored.startsAt);
|
||||
}
|
||||
|
||||
if (restored.endsAt) {
|
||||
endsAt = new Date(restored.endsAt);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
fieldErrors = {};
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { Modal, TableBodyCell } from "flowbite-svelte";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import BannersForm from "./BannersForm.svelte";
|
||||
import { locale, t } from "../../../../i18n/store";
|
||||
@@ -25,7 +26,7 @@
|
||||
|
||||
let { rows, onError, onSaved }: Props = $props();
|
||||
|
||||
let list = $state(rows);
|
||||
let list = $state(untrack(() => rows));
|
||||
|
||||
const headers: DataTableHeader[] = [
|
||||
{ key: "pages.admin.comm.banners.history.headers.title", sortable: false },
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import HeroForm from "./HeroForm.svelte";
|
||||
import HeroHistory from "./HeroHistory.svelte";
|
||||
@@ -19,7 +20,7 @@
|
||||
let currentSubtab = $state("fields");
|
||||
let showError = $state(false);
|
||||
let errorMessage = $state("");
|
||||
let heroesList = $state(heroes);
|
||||
let heroesList = $state(untrack(() => heroes));
|
||||
|
||||
function handleTabChange(tabId: string) {
|
||||
currentSubtab = tabId;
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { actions, isInputError } from "astro:actions";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import HeroPreviewModal from "./HeroPreviewModal.svelte";
|
||||
import { locale, t } from "../../../../i18n/store";
|
||||
import { getDefaultLanguage } from "../../../../utils/consts";
|
||||
import { formatDate, startOfDay } from "../../../../utils/dates";
|
||||
import { useFormDraft, restoreFields } from "../../../../utils/forms/useFormDraft.svelte";
|
||||
import {
|
||||
getLanguageDisplayName,
|
||||
primaryLanguage as pickPrimaryLanguage,
|
||||
@@ -98,12 +100,14 @@
|
||||
// translations, and the default can be removed like any other language
|
||||
// once a second one exists.
|
||||
const defaultLanguage = getDefaultLanguage();
|
||||
const baseLanguage = hero?.language || defaultLanguage;
|
||||
const languagesSeed = hero
|
||||
// Seeded once: later prop changes must not overwrite what the admin is editing
|
||||
const initialHero = untrack(() => hero);
|
||||
const baseLanguage = initialHero?.language || defaultLanguage;
|
||||
const languagesSeed = initialHero
|
||||
? [
|
||||
...new Set([
|
||||
baseLanguage,
|
||||
...(hero.languages ?? []).filter((code) => code !== baseLanguage),
|
||||
...(initialHero.languages ?? []).filter((code) => code !== baseLanguage),
|
||||
]),
|
||||
]
|
||||
: [defaultLanguage];
|
||||
@@ -111,9 +115,9 @@
|
||||
const initialFieldValues: Record<string, HeroFields> = {};
|
||||
for (const lang of languagesSeed) {
|
||||
initialFieldValues[lang] =
|
||||
lang === baseLanguage && hero
|
||||
? fieldsFromRecord(hero)
|
||||
: fieldsFromTranslations(hero?.translations?.[lang]);
|
||||
lang === baseLanguage && initialHero
|
||||
? fieldsFromRecord(initialHero)
|
||||
: fieldsFromTranslations(initialHero?.translations?.[lang]);
|
||||
}
|
||||
|
||||
let languages = $state<string[]>(languagesSeed);
|
||||
@@ -134,7 +138,7 @@
|
||||
|
||||
let startsAt = $state(new Date());
|
||||
|
||||
let media = $state<HeroMedia | undefined>(storedMedia(hero));
|
||||
let media = $state<HeroMedia | undefined>(storedMedia(initialHero));
|
||||
let isUploadOpen = $state(false);
|
||||
|
||||
let isPreviewOpen = $state(false);
|
||||
@@ -142,6 +146,37 @@
|
||||
|
||||
const isVideo = $derived(media?.type.startsWith("video/") ?? false);
|
||||
|
||||
/**
|
||||
* Nothing in this form is sensitive, so all of it can be kept.
|
||||
*/
|
||||
const { restored } = useFormDraft("admin-home-hero", () => ({
|
||||
fieldValues,
|
||||
languages,
|
||||
selectedLanguage,
|
||||
startsAt: startsAt.toISOString(),
|
||||
media,
|
||||
}));
|
||||
|
||||
if (restored) {
|
||||
restoreFields(fieldValues, restored.fieldValues);
|
||||
|
||||
if (restored.languages) {
|
||||
languages = restored.languages;
|
||||
}
|
||||
|
||||
if (restored.selectedLanguage) {
|
||||
selectedLanguage = restored.selectedLanguage;
|
||||
}
|
||||
|
||||
if (restored.startsAt) {
|
||||
startsAt = new Date(restored.startsAt);
|
||||
}
|
||||
|
||||
if (restored.media) {
|
||||
media = restored.media;
|
||||
}
|
||||
}
|
||||
|
||||
function storedMedia(record: HomeHeroRecord | null): HeroMedia | undefined {
|
||||
if (!record?.mediaUrl || !record.mediaType) {
|
||||
return undefined;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { actions } from "astro:actions";
|
||||
import { Modal, TableBodyCell } from "flowbite-svelte";
|
||||
import { tick } from "svelte";
|
||||
import { tick, untrack } from "svelte";
|
||||
|
||||
import HeroForm from "./HeroForm.svelte";
|
||||
import HeroPreviewModal from "./HeroPreviewModal.svelte";
|
||||
@@ -28,7 +28,7 @@
|
||||
|
||||
let { rows, onError, onSaved }: Props = $props();
|
||||
|
||||
let list = $state(rows);
|
||||
let list = $state(untrack(() => rows));
|
||||
|
||||
// rows is refreshed after a save; keep the local list in sync, while the
|
||||
// local deletions below continue to apply on top of the incoming list.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import ProjectsModalAnnotations from "./ProjectsModalAnnotations.svelte";
|
||||
import ProjectsModalPaid from "./ProjectsModalPaid.svelte";
|
||||
// Paid modal hidden until the API persists the paid amount.
|
||||
// import ProjectsModalPaid from "./ProjectsModalPaid.svelte";
|
||||
import ProjectsTable, { type ProjectRow, type ProjectSortKey } from "./ProjectsTable.svelte";
|
||||
import { t } from "../../../i18n/store";
|
||||
import {
|
||||
@@ -8,9 +9,8 @@
|
||||
apiProjectsIdPatch,
|
||||
apiAccountingsIdGet,
|
||||
apiUsersIdOrHandleGet,
|
||||
apiProjectSupportsmoneyTotalGetCollection,
|
||||
apiProjectsIdOrSlugGetUrl,
|
||||
apiProjectsGetCollectionUrl,
|
||||
apiProjectsmoneyTotalGetCollection,
|
||||
type Project,
|
||||
type Accounting,
|
||||
type User,
|
||||
@@ -24,9 +24,11 @@
|
||||
splitOrderParams,
|
||||
syncQueryFiltersToUrl,
|
||||
} from "../../../utils/queryParams";
|
||||
import Toast from "../../library/feedback/Toast.svelte";
|
||||
import Dashboard from "../AdminDashboard.svelte";
|
||||
|
||||
import type { ApiProjectsGetCollectionData } from "../../../openapi/client/types.gen";
|
||||
import type { ProjectStatus } from "../../../utils/projectStatus";
|
||||
|
||||
type ProjectsQuery = Partial<ApiProjectsGetCollectionData["query"]>;
|
||||
|
||||
@@ -56,6 +58,7 @@
|
||||
let filters: ProjectsQuery = $state(initialParams.filters);
|
||||
let projectRows = $state<ProjectRow[]>([]);
|
||||
let totalEarned = $state("—");
|
||||
let isTotalEarnedLoading = $state(false);
|
||||
|
||||
let accountingsCache = $state(new Map<string, Accounting>());
|
||||
let ownersCache = $state(new Map<string, User>());
|
||||
@@ -72,12 +75,14 @@
|
||||
});
|
||||
|
||||
let annotationsCache = $state(new Map<number, string>());
|
||||
let paidModalOpen = $state(false);
|
||||
// let paidModalOpen = $state(false);
|
||||
let annotationsModalOpen = $state(false);
|
||||
let paidValue = $state("");
|
||||
let maxAchievedValue = $state("");
|
||||
// let paidValue = $state("");
|
||||
// let maxAchievedValue = $state("");
|
||||
let annotationText = $state("");
|
||||
let selectedProjectId = $state(0);
|
||||
let showError = $state(false);
|
||||
let errorMessage = $state("");
|
||||
|
||||
let projectSlides = $derived([
|
||||
{ title: $t("pages.admin.projects.totalizers.selected"), amount: table.totalItems },
|
||||
@@ -85,37 +90,22 @@
|
||||
]);
|
||||
|
||||
/**
|
||||
* Fetches the total money earned for a given list of project IDs.
|
||||
* @param ids - Array of project IDs
|
||||
* Totals the money earned by every project matching the table filters, not only the current
|
||||
* page: `money_total` takes the same filters as the projects collection.
|
||||
*/
|
||||
async function fetchTotalEarned(ids: number[]) {
|
||||
if (ids.length === 0) {
|
||||
totalEarned = formatCurrency(0, import.meta.env.PUBLIC_DEFAULT_CURRENCY);
|
||||
async function fetchTotalEarned(projectFilters: ProjectsQuery) {
|
||||
isTotalEarnedLoading = true;
|
||||
const { data, error } = await apiProjectsmoneyTotalGetCollection({
|
||||
baseUrl: "/api/relay",
|
||||
query: projectFilters,
|
||||
});
|
||||
isTotalEarnedLoading = false;
|
||||
if (error || !data) {
|
||||
console.error("Failed to fetch money total:", error);
|
||||
totalEarned = "—";
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { data, error } = await apiProjectSupportsmoneyTotalGetCollection({
|
||||
baseUrl: "/api/relay",
|
||||
query: {
|
||||
"project[]": ids.map((id) =>
|
||||
apiProjectsIdOrSlugGetUrl.replace("{idOrSlug}", String(id)),
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error("Failed to fetch money total:", error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data) {
|
||||
const total = data.amount ?? 0;
|
||||
const currency = data.currency ?? import.meta.env.PUBLIC_DEFAULT_CURRENCY;
|
||||
totalEarned = formatCurrency(total, currency);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch money total", e);
|
||||
}
|
||||
totalEarned = formatCurrency(data.amount ?? 0, data.currency);
|
||||
}
|
||||
|
||||
function buildProjectsQuery(
|
||||
@@ -186,8 +176,6 @@
|
||||
const loadedProjects = toCollectionItems<Project>(collection);
|
||||
table.totalItems = getCollectionTotalItems(collection, response);
|
||||
|
||||
const projectIds = loadedProjects.map((p) => p.id).filter(Boolean) as number[];
|
||||
|
||||
const uniqueAccountingIris = [
|
||||
...new Set(loadedProjects.map((p) => p.accounting).filter(Boolean)),
|
||||
] as string[];
|
||||
@@ -223,7 +211,6 @@
|
||||
return data ? ([iri, data] as const) : null;
|
||||
}),
|
||||
),
|
||||
fetchTotalEarned(projectIds),
|
||||
]);
|
||||
|
||||
for (const [iri, accounting] of accountingResults.filter(Boolean) as [
|
||||
@@ -243,20 +230,26 @@
|
||||
const owner = project.owner ? ownersCache.get(project.owner) : undefined;
|
||||
const balance = accounting?.balance;
|
||||
const calendar = project.calendar;
|
||||
const min = project.budget?.minimum?.money;
|
||||
const opt = project.budget?.optimum?.money;
|
||||
|
||||
return {
|
||||
id: project.id ?? 0,
|
||||
name: project.title,
|
||||
slug: project.slug ?? "",
|
||||
slug: project.slug ?? String(project.id),
|
||||
promoter: owner?.displayName ?? owner?.email ?? "—",
|
||||
promoterHandle: owner?.handle ?? "",
|
||||
achieved: balance ? formatCurrency(balance.amount, balance.currency) : "—",
|
||||
paid: "—",
|
||||
paidMatchfunding: "—",
|
||||
status: project.status ?? "",
|
||||
status: project.status ?? "in_draft",
|
||||
datePublished: calendar?.release ?? "—",
|
||||
dateEnd1: calendar?.minimum ?? "—",
|
||||
dateEnd2: calendar?.optimum ?? "—",
|
||||
minOptim: "—",
|
||||
minOptim:
|
||||
min && opt
|
||||
? `${formatCurrency(min.amount, min.currency)} - ${formatCurrency(opt.amount, opt.currency)}`
|
||||
: "—",
|
||||
remaining: "—",
|
||||
annotationsCount: 0,
|
||||
annotations: "",
|
||||
@@ -280,6 +273,10 @@
|
||||
reloadProjects();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
fetchTotalEarned(filters);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const sortOption = sortFieldMap[table.selectedSort];
|
||||
|
||||
@@ -299,22 +296,32 @@
|
||||
table.currentPage = 1;
|
||||
}
|
||||
|
||||
async function handleStatusChange(projectId: number, status: string): Promise<void> {
|
||||
/** The API rejects transitions that break the project life-cycle; those surface as a toast. */
|
||||
async function handleStatusChange(projectId: number, status: ProjectStatus): Promise<boolean> {
|
||||
const { error } = await apiProjectsIdPatch({
|
||||
baseUrl: "/api/relay",
|
||||
path: { id: String(projectId) },
|
||||
body: { status: status as any },
|
||||
body: { status },
|
||||
});
|
||||
if (error) console.error("Failed to update project status:", error);
|
||||
if (error) {
|
||||
const detail = (error as { detail?: string | null }).detail;
|
||||
errorMessage = `${$t("pages.admin.projects.table.rows.details.statusChangeError")}${detail ? `: ${detail}` : ""}`;
|
||||
showError = true;
|
||||
return false;
|
||||
}
|
||||
const row = projectRows.find((p) => p.id === projectId);
|
||||
if (row) row.status = status;
|
||||
return true;
|
||||
}
|
||||
|
||||
function openPaidModal(project: ProjectRow, e: MouseEvent) {
|
||||
e.stopPropagation();
|
||||
selectedProjectId = project.id;
|
||||
paidValue = project.paid !== "—" ? project.paid : "";
|
||||
maxAchievedValue = project.achieved !== "—" ? project.achieved : "";
|
||||
paidModalOpen = true;
|
||||
}
|
||||
// Re-enable with `onOpenPaidModal={openPaidModal}` on <ProjectsTable> and the modal below.
|
||||
// function openPaidModal(project: ProjectRow, e: MouseEvent) {
|
||||
// e.stopPropagation();
|
||||
// selectedProjectId = project.id;
|
||||
// paidValue = project.paid !== "—" ? project.paid : "";
|
||||
// maxAchievedValue = project.achieved !== "—" ? project.achieved : "";
|
||||
// paidModalOpen = true;
|
||||
// }
|
||||
|
||||
function openAnnotationsModal(project: ProjectRow, e: MouseEvent) {
|
||||
e.stopPropagation();
|
||||
@@ -323,10 +330,10 @@
|
||||
annotationsModalOpen = true;
|
||||
}
|
||||
|
||||
function handleSavePaid() {
|
||||
reloadProjects();
|
||||
paidModalOpen = false;
|
||||
}
|
||||
// function handleSavePaid() {
|
||||
// reloadProjects();
|
||||
// paidModalOpen = false;
|
||||
// }
|
||||
|
||||
function handleSaveAnnotations() {
|
||||
annotationsCache = new Map(annotationsCache).set(selectedProjectId, annotationText);
|
||||
@@ -366,7 +373,7 @@
|
||||
}}
|
||||
slider={{
|
||||
slides: projectSlides,
|
||||
isLoading: table.isLoading,
|
||||
isLoading: table.isLoading || isTotalEarnedLoading,
|
||||
}}
|
||||
>
|
||||
<ProjectsTable
|
||||
@@ -381,17 +388,19 @@
|
||||
onItemsPerPageChange={table.handleItemsPerPageChange}
|
||||
onSortChange={table.handleSortChange}
|
||||
onStatusChange={handleStatusChange}
|
||||
onOpenPaidModal={openPaidModal}
|
||||
onOpenAnnotationsModal={openAnnotationsModal}
|
||||
/>
|
||||
</Dashboard>
|
||||
|
||||
<!-- Paid modal hidden until the API persists the paid amount.
|
||||
<ProjectsModalPaid
|
||||
bind:open={paidModalOpen}
|
||||
bind:paidValue
|
||||
maxAchieved={maxAchievedValue}
|
||||
onsave={handleSavePaid}
|
||||
/>
|
||||
-->
|
||||
<Toast floating variant="error" bind:showToast={showError}>{errorMessage}</Toast>
|
||||
<ProjectsModalAnnotations
|
||||
bind:open={annotationsModalOpen}
|
||||
bind:annotationText
|
||||
|
||||
@@ -1,24 +1,38 @@
|
||||
<script lang="ts">
|
||||
import Comments from "../../../components/icons/Comments.svelte";
|
||||
// Re-enable with the annotations button below.
|
||||
// import Comments from "../../../components/icons/Comments.svelte";
|
||||
import { t, locale } from "../../../i18n/store";
|
||||
import { formatDate } from "../../../utils/dates";
|
||||
import { extractId } from "../../../utils/extractId";
|
||||
import { PROJECT_STATUSES, projectStatusLabelKey } from "../../../utils/projectStatus";
|
||||
import Select from "../../library/inputs/Select.svelte";
|
||||
import ProjectPreviewModal from "../../project/edit/ProjectPreviewModal.svelte";
|
||||
import DetailsRow, { type DetailsField } from "../DetailsRow.svelte";
|
||||
|
||||
import type { ProjectRow } from "./ProjectsTable.svelte";
|
||||
import type { ProjectStatus } from "../../../utils/projectStatus";
|
||||
|
||||
interface Props {
|
||||
project: ProjectRow;
|
||||
onOpenAnnotationsModal: () => void;
|
||||
onChangeStatus?: (projectId: number) => void;
|
||||
onStatusChange: (projectId: number, status: ProjectStatus) => Promise<boolean>;
|
||||
userEmail?: string;
|
||||
}
|
||||
|
||||
let { project, onOpenAnnotationsModal, onChangeStatus, userEmail }: Props = $props();
|
||||
let { project, onOpenAnnotationsModal, onStatusChange, userEmail }: Props = $props();
|
||||
|
||||
// Bound to the select; reset to the project's status when the API rejects the change.
|
||||
let selectedStatus = $derived<string>(project.status);
|
||||
let isSavingStatus = $state(false);
|
||||
let previewOpen = $state(false);
|
||||
|
||||
async function handleStatusSelect(status: string) {
|
||||
if (status === project.status) return;
|
||||
isSavingStatus = true;
|
||||
const ok = await onStatusChange(project.id, status as ProjectStatus);
|
||||
isSavingStatus = false;
|
||||
if (!ok) selectedStatus = project.status;
|
||||
}
|
||||
|
||||
const fields: DetailsField[] = $derived([
|
||||
{
|
||||
label: $t("pages.admin.projects.table.rows.details.datePublished"),
|
||||
@@ -53,61 +67,49 @@
|
||||
},
|
||||
]);
|
||||
|
||||
function navigateToCharges() {
|
||||
if (!project.accounting) return;
|
||||
window.location.href = `/${$locale}/admin/charges?target=${encodeURIComponent(project.accounting)}`;
|
||||
}
|
||||
|
||||
function navigateToPromoter() {
|
||||
if (!project.owner) return;
|
||||
const ownerId = extractId(project.owner) || project.owner;
|
||||
window.location.href = `/${$locale}/user/${ownerId}`;
|
||||
}
|
||||
|
||||
function navigateToEdit() {
|
||||
const projectIdentifier = project.slug || project.id;
|
||||
if (!projectIdentifier) return;
|
||||
window.location.href = `/${$locale}/project/${projectIdentifier}/edit`;
|
||||
}
|
||||
|
||||
const isInCampaign = $derived(project.status === "in_campaign");
|
||||
|
||||
const actionKeys = ["promoter", "contributions", "campaignPageOrPreview", "edit"] as const;
|
||||
|
||||
function handleActionClick(key: (typeof actionKeys)[number]) {
|
||||
if (key === "contributions") navigateToCharges();
|
||||
if (key === "promoter") navigateToPromoter();
|
||||
if (key === "edit") navigateToEdit();
|
||||
if (key === "campaignPageOrPreview") {
|
||||
if (isInCampaign) {
|
||||
const projectIdentifier = project.slug || project.id;
|
||||
if (!projectIdentifier) return;
|
||||
window.location.href = `/${$locale}/project/${projectIdentifier}`;
|
||||
} else {
|
||||
previewOpen = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
const actionClass =
|
||||
"border-secondary text-secondary cursor-pointer rounded-full border bg-white px-5 py-2 text-sm";
|
||||
</script>
|
||||
|
||||
<DetailsRow {fields} columns={4}>
|
||||
{#snippet actions()}
|
||||
<div class="flex flex-row flex-wrap gap-3">
|
||||
{#each actionKeys as key (key)}
|
||||
<button
|
||||
type="button"
|
||||
class="border-secondary text-secondary cursor-pointer rounded-full border bg-white px-5 py-2 text-sm"
|
||||
onclick={() => handleActionClick(key)}
|
||||
<div class="flex flex-row flex-wrap items-center gap-3">
|
||||
<Select
|
||||
class="py-2 text-sm"
|
||||
labelText={$t("pages.admin.projects.table.rows.details.status")}
|
||||
bind:value={selectedStatus}
|
||||
disabled={isSavingStatus}
|
||||
onChange={handleStatusSelect}
|
||||
>
|
||||
{#each PROJECT_STATUSES as status (status)}
|
||||
<option value={status}>{$t(projectStatusLabelKey(status))}</option>
|
||||
{/each}
|
||||
</Select>
|
||||
{#if project.promoterHandle}
|
||||
<a class={actionClass} href={`/${$locale}/user/${project.promoterHandle}`}>
|
||||
{$t("pages.admin.projects.table.rows.details.btns.promoter")}
|
||||
</a>
|
||||
{/if}
|
||||
{#if project.accounting}
|
||||
<a
|
||||
class={actionClass}
|
||||
href={`/${$locale}/admin/charges?target=${encodeURIComponent(project.accounting)}`}
|
||||
>
|
||||
{key === "campaignPageOrPreview"
|
||||
? isInCampaign
|
||||
? $t("pages.admin.projects.table.rows.details.btns.campaignPage")
|
||||
: $t("pages.admin.projects.table.rows.details.btns.preview")
|
||||
: key === "edit"
|
||||
? $t("pages.admin.projects.table.rows.details.btns.edit")
|
||||
: $t(`pages.admin.projects.table.rows.details.btns.${key}`)}
|
||||
{$t("pages.admin.projects.table.rows.details.btns.contributions")}
|
||||
</a>
|
||||
{/if}
|
||||
<a class={actionClass} href={`/${$locale}/project/${project.slug}/edit`}>
|
||||
{$t("pages.admin.projects.table.rows.details.btns.edit")}
|
||||
</a>
|
||||
{#if project.status === "in_campaign"}
|
||||
<a class={actionClass} href={`/${$locale}/project/${project.slug}`}>
|
||||
{$t("pages.admin.projects.table.rows.details.btns.campaignPage")}
|
||||
</a>
|
||||
{:else}
|
||||
<button type="button" class={actionClass} onclick={() => (previewOpen = true)}>
|
||||
{$t("pages.admin.projects.table.rows.details.btns.preview")}
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
{#snippet footer()}
|
||||
@@ -125,6 +127,7 @@
|
||||
{$t("pages.admin.projects.table.rows.details.btns.certificates")}
|
||||
</button>
|
||||
-->
|
||||
<!-- Hidden until the API persists annotations: the modal only keeps them in memory.
|
||||
<button
|
||||
onclick={onOpenAnnotationsModal}
|
||||
class="text-secondary bg-variant1 flex min-h-10 cursor-pointer flex-row items-center gap-2 rounded-2xl px-4 py-2 font-bold"
|
||||
@@ -135,6 +138,7 @@
|
||||
({project.annotationsCount})
|
||||
{/if}
|
||||
</button>
|
||||
-->
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
@@ -5,15 +5,13 @@
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import TextArea from "../../library/inputs/TextArea.svelte";
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
annotationText = $bindable(""),
|
||||
onsave,
|
||||
} = $props<{
|
||||
interface Props {
|
||||
open: boolean;
|
||||
annotationText: string;
|
||||
onsave?: (text: string) => void;
|
||||
}>();
|
||||
}
|
||||
|
||||
let { open = $bindable(false), annotationText = $bindable(""), onsave }: Props = $props();
|
||||
</script>
|
||||
|
||||
<Modal
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts" module>
|
||||
import type { ProjectStatus } from "../../../utils/projectStatus";
|
||||
import type { DataTableHeader, SortOption } from "../../library/tables/DataTable.svelte";
|
||||
|
||||
export type ProjectRow = {
|
||||
@@ -6,10 +7,11 @@
|
||||
name: string;
|
||||
slug: string;
|
||||
promoter: string;
|
||||
promoterHandle: string;
|
||||
achieved: string;
|
||||
paid: string;
|
||||
paidMatchfunding: string;
|
||||
status: string;
|
||||
status: ProjectStatus;
|
||||
datePublished: string;
|
||||
dateEnd1: string;
|
||||
dateEnd2: string;
|
||||
@@ -46,7 +48,8 @@
|
||||
{ key: "pages.admin.projects.table.headers.name" },
|
||||
{ key: "pages.admin.projects.table.headers.promoter" },
|
||||
{ key: "pages.admin.projects.table.headers.achieved" },
|
||||
{ key: "pages.admin.projects.table.headers.paid" },
|
||||
// Hidden until the API provides the paid amount (also the cell below).
|
||||
// { key: "pages.admin.projects.table.headers.paid" },
|
||||
{ key: "pages.admin.projects.table.headers.process" },
|
||||
{ key: "", class: "w-12" },
|
||||
];
|
||||
@@ -54,13 +57,14 @@
|
||||
|
||||
<script lang="ts">
|
||||
import { TableBodyCell } from "flowbite-svelte";
|
||||
import { SvelteSet } from "svelte/reactivity";
|
||||
|
||||
import ProjectsDetailsRow from "./ProjectsDetailsRow.svelte";
|
||||
import { t } from "../../../i18n/store";
|
||||
import { ADMIN_ITEMS_PER_PAGE_OPTIONS } from "../../../utils/adminTable";
|
||||
import { projectStatusLabelKey } from "../../../utils/projectStatus";
|
||||
import Chevron from "../../icons/navigation/Chevron.svelte";
|
||||
import DataTable from "../../library/tables/DataTable.svelte";
|
||||
import Tag from "../../library/tags/Tag.svelte";
|
||||
|
||||
let {
|
||||
projects = [],
|
||||
@@ -76,7 +80,6 @@
|
||||
onStatusChange,
|
||||
onOpenPaidModal,
|
||||
onOpenAnnotationsModal,
|
||||
onChangeStatus,
|
||||
}: {
|
||||
projects: ProjectRow[];
|
||||
currentPage: number;
|
||||
@@ -88,85 +91,16 @@
|
||||
onPageChange?: (page: number) => void;
|
||||
onItemsPerPageChange?: (perPage: number) => void;
|
||||
onSortChange?: (sort: ProjectSortKey) => void;
|
||||
onStatusChange?: (projectId: number, status: string) => Promise<void>;
|
||||
onStatusChange: (projectId: number, status: ProjectStatus) => Promise<boolean>;
|
||||
onOpenPaidModal?: (project: ProjectRow, e: MouseEvent) => void;
|
||||
onOpenAnnotationsModal?: (project: ProjectRow, e: MouseEvent) => void;
|
||||
onChangeStatus?: (projectId: number) => void;
|
||||
} = $props();
|
||||
|
||||
let openRow = $state<number | null>(null);
|
||||
|
||||
const statusOptions = [
|
||||
{ value: "in_draft", label: $t("domain.project.status.in_draft") },
|
||||
{
|
||||
value: "to_campaign_review",
|
||||
label: $t("domain.project.status.to_campaign_review"),
|
||||
},
|
||||
{
|
||||
value: "in_campaign_review",
|
||||
label: $t("domain.project.status.in_campaign_review"),
|
||||
},
|
||||
{
|
||||
value: "in_campaign_review.to_change",
|
||||
label: $t("domain.project.status.in_campaign_review_to_change"),
|
||||
},
|
||||
{
|
||||
value: "in_campaign_review.to_review",
|
||||
label: $t("domain.project.status.in_campaign_review_to_review"),
|
||||
},
|
||||
{
|
||||
value: "campaign_review_rejected",
|
||||
label: $t("domain.project.status.campaign_review_rejected"),
|
||||
},
|
||||
{ value: "to_campaign", label: $t("domain.project.status.to_campaign") },
|
||||
{ value: "in_campaign", label: $t("domain.project.status.in_campaign") },
|
||||
{
|
||||
value: "campaign_failed",
|
||||
label: $t("domain.project.status.campaign_failed"),
|
||||
},
|
||||
{
|
||||
value: "campaign_cancelled",
|
||||
label: $t("domain.project.status.campaign_cancelled"),
|
||||
},
|
||||
{
|
||||
value: "to_funding_review",
|
||||
label: $t("domain.project.status.to_funding_review"),
|
||||
},
|
||||
{
|
||||
value: "in_funding_review",
|
||||
label: $t("domain.project.status.in_funding_review"),
|
||||
},
|
||||
{
|
||||
value: "in_funding_review.to_change",
|
||||
label: $t("domain.project.status.in_funding_review_to_change"),
|
||||
},
|
||||
{
|
||||
value: "in_funding_review.to_review",
|
||||
label: $t("domain.project.status.in_funding_review_to_review"),
|
||||
},
|
||||
{
|
||||
value: "funding_review_rejected",
|
||||
label: $t("domain.project.status.funding_review_rejected"),
|
||||
},
|
||||
{ value: "to_funding", label: $t("domain.project.status.to_funding") },
|
||||
{ value: "in_funding", label: $t("domain.project.status.in_funding") },
|
||||
{ value: "funding_paid", label: $t("domain.project.status.funding_paid") },
|
||||
];
|
||||
|
||||
function toggleRow(_row: ProjectRow, index: number): void {
|
||||
openRow = openRow === index ? null : index;
|
||||
}
|
||||
|
||||
const updatingStatus = new SvelteSet<number>();
|
||||
|
||||
async function handleStatusChangeInline(project: ProjectRow, newStatus: string) {
|
||||
updatingStatus.add(project.id);
|
||||
try {
|
||||
await onStatusChange?.(project.id, newStatus);
|
||||
} finally {
|
||||
updatingStatus.delete(project.id);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<DataTable
|
||||
@@ -199,6 +133,7 @@
|
||||
<TableBodyCell class="border-variant1 border-t border-b p-4">
|
||||
{project.achieved}
|
||||
</TableBodyCell>
|
||||
<!-- Hidden until the API provides the paid amount: the column shows "—" and the modal saves nothing.
|
||||
<TableBodyCell class="border-variant1 border-t border-b p-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<span>{project.paid}</span>
|
||||
@@ -211,19 +146,11 @@
|
||||
</button>
|
||||
</div>
|
||||
</TableBodyCell>
|
||||
-->
|
||||
<TableBodyCell class="border-variant1 border-t border-b p-4">
|
||||
<div onclick={(e) => e.stopPropagation()} role="presentation">
|
||||
<select
|
||||
class="border-secondary text-secondary rounded-sm border py-1 text-sm disabled:opacity-50"
|
||||
value={project.status}
|
||||
disabled={updatingStatus.has(project.id)}
|
||||
onchange={(e) => handleStatusChangeInline(project, e.currentTarget.value)}
|
||||
>
|
||||
{#each statusOptions as opt}
|
||||
<option value={opt.value}>{opt.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<Tag class="border-secondary max-w-56 rounded-md border">
|
||||
<span class="truncate">{$t(projectStatusLabelKey(project.status))}</span>
|
||||
</Tag>
|
||||
</TableBodyCell>
|
||||
<TableBodyCell
|
||||
class="border-variant1 text-content rounded-r-md border-t border-r border-b p-4 text-sm"
|
||||
@@ -241,7 +168,7 @@
|
||||
{project}
|
||||
onOpenAnnotationsModal={() =>
|
||||
onOpenAnnotationsModal?.(project, new MouseEvent("click"))}
|
||||
{onChangeStatus}
|
||||
{onStatusChange}
|
||||
userEmail={userEmailById.get(project.id)}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
@@ -7,10 +7,9 @@
|
||||
apiUsersGetCollectionUrl,
|
||||
type User,
|
||||
} from "../../../openapi/client/index.ts";
|
||||
import { debounce } from "../../../utils/debounce.ts";
|
||||
import { toCollectionItems } from "../../../utils/hydra";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import DropdownMenu from "../../library/dropdown/DropdownMenu.svelte";
|
||||
import DropdownSearch from "../../library/dropdown/DropdownSearch.svelte";
|
||||
import UserResultRow from "../../library/dropdown/UserResultRow.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
@@ -34,7 +33,6 @@
|
||||
onAssign: (iri: string, name: string) => void;
|
||||
} = $props();
|
||||
|
||||
let candidates = $state<DropdownOption[]>([]);
|
||||
let searchValue = $state("");
|
||||
let selected = $state<DropdownOption[]>([]);
|
||||
|
||||
@@ -47,24 +45,14 @@
|
||||
};
|
||||
}
|
||||
|
||||
const searchUsers = debounce(async (term: string) => {
|
||||
async function searchUsers(term: string, signal: AbortSignal): Promise<DropdownOption[]> {
|
||||
const { data } = await apiUsersGetCollection({
|
||||
baseUrl: "/api/relay",
|
||||
query: { q: term.trim(), itemsPerPage: 30 },
|
||||
query: { q: term, itemsPerPage: 30 },
|
||||
signal,
|
||||
});
|
||||
|
||||
candidates = toCollectionItems<User>(data).map(toOption);
|
||||
}, 250);
|
||||
|
||||
function handleSearch(value: string): void {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length < 2) {
|
||||
searchUsers.cancel();
|
||||
candidates = [];
|
||||
return;
|
||||
}
|
||||
|
||||
searchUsers(trimmed);
|
||||
return toCollectionItems<User>(data).map(toOption);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
@@ -109,17 +97,17 @@
|
||||
{$t("pages.admin.reviews.projects.table.rows.details.modals.assignAdvisor.description")}
|
||||
</p>
|
||||
|
||||
<DropdownMenu
|
||||
options={candidates}
|
||||
<DropdownSearch
|
||||
search={searchUsers}
|
||||
minChars={2}
|
||||
debounceMs={250}
|
||||
bind:selected
|
||||
bind:searchValue
|
||||
bind:value={searchValue}
|
||||
variant="basic"
|
||||
singleSelect
|
||||
hasSearch
|
||||
searchPlaceholder={$t(
|
||||
placeholder={$t(
|
||||
"pages.admin.reviews.projects.table.rows.details.modals.assignAdvisor.searchPlaceholder",
|
||||
)}
|
||||
onSearch={handleSearch}
|
||||
label={title}
|
||||
selectedFirst
|
||||
>
|
||||
@@ -128,7 +116,7 @@
|
||||
<UserResultRow user={option.raw as User} />
|
||||
{/if}
|
||||
{/snippet}
|
||||
</DropdownMenu>
|
||||
</DropdownSearch>
|
||||
|
||||
{#snippet footer()}
|
||||
<Button kind="secondary" disabled={!selected.length} onclick={confirm} class="w-fit">
|
||||
|
||||
@@ -2,10 +2,7 @@
|
||||
import { SvelteMap } from "svelte/reactivity";
|
||||
|
||||
import AssignAdvisorModal from "./AssignAdvisorModal.svelte";
|
||||
import ReviewProjectsTable, {
|
||||
type ProjectStatus,
|
||||
type ReviewProjectRow,
|
||||
} from "./ReviewProjectsTable.svelte";
|
||||
import ReviewProjectsTable, { type ReviewProjectRow } from "./ReviewProjectsTable.svelte";
|
||||
import { t } from "../../../i18n/store";
|
||||
import {
|
||||
apiProjectReviewAreasGetCollection,
|
||||
@@ -31,6 +28,7 @@
|
||||
|
||||
import type { ApiProjectReviewsGetCollectionData } from "../../../openapi/client/types.gen";
|
||||
import type { ProjectReviewRisk } from "../../../types/projectReview";
|
||||
import type { ProjectStatus } from "../../../utils/projectStatus";
|
||||
|
||||
type ReviewsQuery = Partial<ApiProjectReviewsGetCollectionData["query"]>;
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
<script lang="ts" module>
|
||||
import type { Project, ProjectReview } from "../../../openapi/client/index.ts";
|
||||
import type { ProjectReview } from "../../../openapi/client/index.ts";
|
||||
import type { ProjectReviewRisk } from "../../../types/projectReview";
|
||||
import type { ProjectStatus } from "../../../utils/projectStatus";
|
||||
import type { DataTableHeader } from "../../library/tables/DataTable.svelte";
|
||||
|
||||
export type ProjectStatus = NonNullable<Project["status"]>;
|
||||
|
||||
export type ReviewProjectRow = {
|
||||
id: number;
|
||||
name: string;
|
||||
@@ -50,7 +49,7 @@
|
||||
import { t, locale } from "../../../i18n/store";
|
||||
import { ADMIN_ITEMS_PER_PAGE_OPTIONS } from "../../../utils/adminTable";
|
||||
import { formatDate } from "../../../utils/dates";
|
||||
import { REVIEW_STATUSES_BY_TYPE } from "../../../utils/projectStatus";
|
||||
import { projectStatusLabelKey, REVIEW_STATUSES_BY_TYPE } from "../../../utils/projectStatus";
|
||||
import { RISK_SQUARE_CLASSES } from "../../../utils/review";
|
||||
import Comments from "../../icons/Comments.svelte";
|
||||
import Chevron from "../../icons/navigation/Chevron.svelte";
|
||||
@@ -106,9 +105,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
const statusLabel = (status: string) =>
|
||||
$t(`domain.project.status.${status.replaceAll(".", "_")}`);
|
||||
|
||||
/**
|
||||
* Statuses a project can move to for the kind of review it is going through.
|
||||
* Whatever status the project holds is always offered, so a review that
|
||||
@@ -190,7 +186,7 @@
|
||||
<option value="">—</option>
|
||||
{/if}
|
||||
{#each statusOptions(project) as status (status)}
|
||||
<option value={status}>{statusLabel(status)}</option>
|
||||
<option value={status}>{$t(projectStatusLabelKey(status))}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<script lang="ts" generics="T">
|
||||
import { Modal } from "flowbite-svelte";
|
||||
import { untrack } from "svelte";
|
||||
import { twMerge, type ClassNameValue } from "tailwind-merge";
|
||||
|
||||
import { t } from "../../../i18n/store";
|
||||
import { debounce } from "../../../utils/debounce";
|
||||
import { useFormDraft } from "../../../utils/forms/useFormDraft.svelte";
|
||||
import ActionableButton from "../../library/buttons/ActionableButton.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import DropdownMenu from "../../library/dropdown/DropdownMenu.svelte";
|
||||
import DropdownSearch from "../../library/dropdown/DropdownSearch.svelte";
|
||||
import Toast from "../../library/feedback/Toast.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
@@ -32,6 +33,9 @@
|
||||
|
||||
/** Persists the assigned values in slot order. */
|
||||
onSave: (slots: SlotContent<T>[]) => Promise<{ error?: { message: string } } | void>;
|
||||
|
||||
/** Identifies the draft of this editor, so two of them do not write over each other. */
|
||||
draftId?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -42,6 +46,7 @@
|
||||
labels,
|
||||
search,
|
||||
onSave,
|
||||
draftId = "slot-editor",
|
||||
}: Props = $props();
|
||||
|
||||
/**
|
||||
@@ -49,43 +54,38 @@
|
||||
* user put them instead of compacting them upwards. Gaps are only collapsed
|
||||
* at save time, which is what the persistence layer expects.
|
||||
*/
|
||||
let assignments = $state<(SlotContent<T> | undefined)[]>([...contents]);
|
||||
let assignments = $state<(SlotContent<T> | undefined)[]>(untrack(() => [...contents]));
|
||||
let pickerOpen = $state(false);
|
||||
let editingIndex = $state<number | null>(null);
|
||||
let query = $state("");
|
||||
let options = $state<DropdownOption[]>([]);
|
||||
let picked = $state<DropdownOption[]>([]);
|
||||
/** Last results, kept so confirming an option can recover the full value. */
|
||||
let candidates = $state<SlotContent<T>[]>([]);
|
||||
let showError = $state(false);
|
||||
let errorMessage = $state("");
|
||||
|
||||
const runSearch = debounce(async (term: string) => {
|
||||
candidates = await search(term);
|
||||
options = candidates.map((c, i) => ({
|
||||
id: String(i),
|
||||
label: c.label,
|
||||
selected: false,
|
||||
}));
|
||||
});
|
||||
/**
|
||||
* The assigned slots are what the editor holds, so they are what can be kept.
|
||||
*/
|
||||
const { restored } = useFormDraft(
|
||||
untrack(() => draftId),
|
||||
() => ({ assignments }),
|
||||
);
|
||||
|
||||
function handleSearch(term: string) {
|
||||
const trimmed = term.trim();
|
||||
if (restored?.assignments) {
|
||||
assignments = restored.assignments;
|
||||
}
|
||||
|
||||
if (trimmed.length < 2) {
|
||||
runSearch.cancel();
|
||||
options = [];
|
||||
candidates = [];
|
||||
return;
|
||||
}
|
||||
|
||||
runSearch(trimmed);
|
||||
async function searchOptions(term: string, signal: AbortSignal): Promise<DropdownOption[]> {
|
||||
const results = await search(term);
|
||||
// A superseded search must not replace the candidates the options index into.
|
||||
if (!signal.aborted) candidates = results;
|
||||
return results.map((c, i) => ({ id: String(i), label: c.label, selected: false }));
|
||||
}
|
||||
|
||||
function openPicker(index: number) {
|
||||
editingIndex = index;
|
||||
query = "";
|
||||
options = [];
|
||||
candidates = [];
|
||||
picked = [];
|
||||
pickerOpen = true;
|
||||
@@ -209,17 +209,16 @@
|
||||
{labels.searchPlaceholder}
|
||||
</span>
|
||||
{/if}
|
||||
<DropdownMenu
|
||||
<DropdownSearch
|
||||
variant="basic"
|
||||
hasSearch
|
||||
singleSelect
|
||||
clearable
|
||||
{options}
|
||||
search={searchOptions}
|
||||
minChars={2}
|
||||
bind:selected={picked}
|
||||
bind:searchValue={query}
|
||||
onSearch={handleSearch}
|
||||
bind:value={query}
|
||||
searchClasses="rounded-3xl border-secondary shadow-none"
|
||||
searchPlaceholder={labels.searchPlaceholder}
|
||||
placeholder={labels.searchPlaceholder}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -13,8 +13,9 @@
|
||||
import { formatDate } from "../../../utils/dates";
|
||||
import Close from "../../icons/navigation/Close.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import DropdownMenu from "../../library/dropdown/DropdownMenu.svelte";
|
||||
import DropdownSearch from "../../library/dropdown/DropdownSearch.svelte";
|
||||
import Toast from "../../library/feedback/Toast.svelte";
|
||||
import PasswordInput from "../../library/inputs/PasswordInput.svelte";
|
||||
import { chargeStatusStyles } from "../charges/ChargesTable.svelte";
|
||||
import DetailsRow, { type DetailsField } from "../DetailsRow.svelte";
|
||||
|
||||
@@ -39,6 +40,11 @@
|
||||
let savingRoles = $state(false);
|
||||
let showError = $state(false);
|
||||
let errorMessage = $state("");
|
||||
let passwordModal = $state(false);
|
||||
let newPassword = $state("");
|
||||
let savingPassword = $state(false);
|
||||
let passwordError = $state("");
|
||||
let passwordSuccess = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (user.accounting) {
|
||||
@@ -81,20 +87,20 @@
|
||||
return normalized.startsWith("ROLE_") ? normalized : `ROLE_${normalized}`;
|
||||
}
|
||||
|
||||
const roleOptions = $derived.by(() => {
|
||||
const search = roleSearch.trim().toLowerCase();
|
||||
function searchRoles(query: string): DropdownOption[] {
|
||||
const search = query.toLowerCase();
|
||||
const all = [...new Set([...user.roles, ...selectedRoles.map((o) => o.id)])].map(
|
||||
toRoleOption,
|
||||
);
|
||||
const matches = all.filter((o) => o.id.toLowerCase().includes(search));
|
||||
|
||||
const custom = toRoleId(roleSearch);
|
||||
const custom = toRoleId(query);
|
||||
if (custom && !all.some((o) => o.id === custom)) {
|
||||
matches.push(toRoleOption(custom));
|
||||
}
|
||||
|
||||
return matches;
|
||||
});
|
||||
}
|
||||
|
||||
async function saveRoles() {
|
||||
savingRoles = true;
|
||||
@@ -118,6 +124,48 @@
|
||||
onRolesUpdated?.(user.id, roles);
|
||||
}
|
||||
|
||||
function openPasswordModal() {
|
||||
newPassword = "";
|
||||
passwordError = "";
|
||||
passwordSuccess = false;
|
||||
passwordModal = true;
|
||||
}
|
||||
|
||||
async function savePassword() {
|
||||
passwordError = "";
|
||||
passwordSuccess = false;
|
||||
|
||||
if (!newPassword) {
|
||||
passwordError = $t("common.password.error.required");
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 8) {
|
||||
passwordError = $t("common.password.error.minLength");
|
||||
return;
|
||||
}
|
||||
|
||||
savingPassword = true;
|
||||
const { error, response } = await apiUsersIdPatch({
|
||||
baseUrl: "/api/relay",
|
||||
path: { id: String(user.id) },
|
||||
body: { password: newPassword },
|
||||
});
|
||||
savingPassword = false;
|
||||
|
||||
if (error) {
|
||||
errorMessage = $t(getErrorTranslationKey(createAuthError(response).type));
|
||||
showError = true;
|
||||
return;
|
||||
}
|
||||
|
||||
passwordSuccess = true;
|
||||
newPassword = "";
|
||||
setTimeout(() => {
|
||||
passwordModal = false;
|
||||
passwordSuccess = false;
|
||||
}, 800);
|
||||
}
|
||||
|
||||
function chargeDateFilterUrl(charge: GatewayCharge): string | undefined {
|
||||
if (!user.accounting || !charge.dateCreated) return;
|
||||
|
||||
@@ -204,6 +252,13 @@
|
||||
>
|
||||
{$t("pages.admin.users.table.rows.details.btns.roles")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="border-secondary text-secondary cursor-pointer rounded-full border bg-white px-5 py-2 text-sm"
|
||||
onclick={openPasswordModal}
|
||||
>
|
||||
{$t("common.password.change")}
|
||||
</button>
|
||||
</div>
|
||||
{/snippet}
|
||||
</DetailsRow>
|
||||
@@ -225,14 +280,14 @@
|
||||
</button>
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<DropdownMenu
|
||||
<DropdownSearch
|
||||
variant="multiselect"
|
||||
chips
|
||||
hasSearch
|
||||
searchPlaceholder={$t("pages.admin.users.table.rows.details.roles.placeholder")}
|
||||
options={roleOptions}
|
||||
search={searchRoles}
|
||||
debounceMs={0}
|
||||
placeholder={$t("pages.admin.users.table.rows.details.roles.placeholder")}
|
||||
bind:selected={selectedRoles}
|
||||
bind:searchValue={roleSearch}
|
||||
bind:value={roleSearch}
|
||||
/>
|
||||
<div class="flex justify-end">
|
||||
<Button kind="primary" disabled={savingRoles} onclick={saveRoles}>
|
||||
@@ -242,6 +297,39 @@
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
bind:open={passwordModal}
|
||||
title={$t("common.password.change")}
|
||||
dismissable={false}
|
||||
class="relative max-w-lg"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="text-secondary absolute inset-e-4 top-4 cursor-pointer bg-transparent p-1 shadow-none hover:opacity-80 focus:ring-0"
|
||||
onclick={() => (passwordModal = false)}
|
||||
aria-label={$t("common.close")}
|
||||
>
|
||||
<Close width="24" height="24" />
|
||||
</button>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<PasswordInput
|
||||
bind:value={newPassword}
|
||||
labelText={$t("common.password.new")}
|
||||
class="h-14"
|
||||
disabled={savingPassword}
|
||||
/>
|
||||
{#if passwordError}
|
||||
<p class="text-tertiary text-sm">{passwordError}</p>
|
||||
{/if}
|
||||
<div class="flex justify-end">
|
||||
<Button kind="primary" disabled={savingPassword} onclick={savePassword}>
|
||||
{$t("common.password.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
bind:open={chargesModal}
|
||||
title={$t("pages.admin.users.table.rows.details.recentCharges")}
|
||||
@@ -284,3 +372,6 @@
|
||||
</Modal>
|
||||
|
||||
<Toast floating variant="error" bind:showToast={showError}>{errorMessage}</Toast>
|
||||
<Toast floating variant="success" bind:showToast={passwordSuccess}>
|
||||
{$t("common.password.success")}
|
||||
</Toast>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import { locale, t } from "../../i18n/store";
|
||||
import { formatAddress } from "../../utils/formatAddress";
|
||||
import { useFormDraft } from "../../utils/forms/useFormDraft.svelte";
|
||||
import AddressForm from "../address/AddressForm.svelte";
|
||||
import Button from "../library/buttons/Button.svelte";
|
||||
import RadioButton from "../library/inputs/RadioButton.svelte";
|
||||
@@ -34,14 +35,33 @@
|
||||
let isSubmitting = $state(false);
|
||||
let addressForm = $state<AddressForm>();
|
||||
|
||||
/**
|
||||
* The address picked before the language was switched. It decides whether the fields of a
|
||||
* new address are shown at all, so it has to come back with them.
|
||||
*/
|
||||
const { restored } = useFormDraft("checkout-address-choice", () => ({ choice }));
|
||||
|
||||
/** Kept out of the state on purpose: it must only be applied once. */
|
||||
let pendingChoice: string | undefined = restored?.choice;
|
||||
|
||||
function takePendingChoice(): string | undefined {
|
||||
const choice = pendingChoice;
|
||||
|
||||
pendingChoice = undefined;
|
||||
|
||||
return choice;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
|
||||
choice = addresses.some((a) => a.id === selected?.id)
|
||||
const seed = addresses.some((a) => a.id === selected?.id)
|
||||
? String(selected!.id)
|
||||
: addresses.length
|
||||
? ""
|
||||
: NEW;
|
||||
|
||||
choice = takePendingChoice() ?? seed;
|
||||
});
|
||||
|
||||
async function save(event: SubmitEvent) {
|
||||
@@ -95,7 +115,7 @@
|
||||
/>
|
||||
|
||||
{#if choice === NEW}
|
||||
<AddressForm bind:this={addressForm} {userIri} />
|
||||
<AddressForm bind:this={addressForm} {userIri} draftId="checkout-address" />
|
||||
{/if}
|
||||
</form>
|
||||
{#snippet footer()}
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
<div class="grid w-full grid-cols-2 gap-6">
|
||||
<div class="border-grey overflow-hidden rounded-3xl border">
|
||||
<img
|
||||
src={project.video?.thumbnail}
|
||||
src={project.cover || project.video?.thumbnail}
|
||||
alt={project.title}
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { Modal } from "flowbite-svelte";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import { t } from "../../i18n/store";
|
||||
import { apiProjectSupportsIdPatch, type ProjectSupport } from "../../openapi/client";
|
||||
import { useFormDraft } from "../../utils/forms/useFormDraft.svelte";
|
||||
import Spinner from "../icons/status/Spinner.svelte";
|
||||
import Button from "../library/buttons/Button.svelte";
|
||||
import TextArea from "../library/inputs/TextArea.svelte";
|
||||
@@ -24,6 +26,31 @@
|
||||
let message = $state("");
|
||||
let isSubmitting = $state(false);
|
||||
|
||||
/** Identifies the draft of this comment, so two of them do not write over each other. */
|
||||
function commentDraftId(support: ProjectSupport): string {
|
||||
return `comment-${support.id ?? "new"}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The comment written before the language was switched. It is not sensitive, so it can
|
||||
* be kept.
|
||||
*/
|
||||
const { restored } = useFormDraft(
|
||||
untrack(() => commentDraftId(support)),
|
||||
() => ({ message }),
|
||||
);
|
||||
|
||||
/** Kept out of the state on purpose: it must only be applied once. */
|
||||
let pendingMessage: string | undefined = restored?.message;
|
||||
|
||||
function takePendingMessage(): string | undefined {
|
||||
const message = pendingMessage;
|
||||
|
||||
pendingMessage = undefined;
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
async function handleSubmit(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -55,7 +82,7 @@
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
message = support?.message ?? "";
|
||||
message = takePendingMessage() ?? support?.message ?? "";
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import { type Project, type ProjectSupport } from "../../openapi/client";
|
||||
import { client } from "../../openapi/client/client.gen";
|
||||
import { apiProjectsIdOrSlugGetUrl } from "../../openapi/client/operation-paths.gen";
|
||||
import { useFormDraft } from "../../utils/forms/useFormDraft.svelte";
|
||||
import RadioButton from "../library/inputs/RadioButton.svelte";
|
||||
import Title from "../library/typography/Title.svelte";
|
||||
|
||||
@@ -17,6 +18,12 @@
|
||||
|
||||
let type = $state<"organization" | "individual">("organization");
|
||||
|
||||
const { restored } = useFormDraft("checkout-feedback", () => ({ type }));
|
||||
|
||||
if (restored) {
|
||||
type = restored.type === "individual" ? "individual" : "organization";
|
||||
}
|
||||
|
||||
let feedbackItems = $derived(() =>
|
||||
projects.map((project) => {
|
||||
const iri = client.buildUrl({
|
||||
@@ -24,7 +31,7 @@
|
||||
path: { idOrSlug: project.id },
|
||||
});
|
||||
|
||||
const support = projectSupports.find((ps) => ps.project === iri)!;
|
||||
const support = projectSupports.find((ps) => iri.endsWith(ps.project!))!;
|
||||
|
||||
return { project, support };
|
||||
}),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { navigate } from "astro:transitions/client";
|
||||
|
||||
import { t } from "../../i18n/store";
|
||||
import { useFormDraft } from "../../utils/forms/useFormDraft.svelte";
|
||||
import Toast from "../library/feedback/Toast.svelte";
|
||||
import Checkbox from "../library/inputs/Checkbox.svelte";
|
||||
import PasswordInput from "../library/inputs/PasswordInput.svelte";
|
||||
@@ -16,6 +17,20 @@
|
||||
let errorMessage = $state("");
|
||||
let showErrorToast = $state(false);
|
||||
|
||||
/**
|
||||
* The identifier and the terms are worth keeping across a language switch; the password
|
||||
* is not, so it is never handed over to the storage.
|
||||
*/
|
||||
const { restored } = useFormDraft("checkout-login", () => ({
|
||||
identifier,
|
||||
acceptTerms,
|
||||
}));
|
||||
|
||||
if (restored) {
|
||||
identifier = restored.identifier ?? "";
|
||||
acceptTerms = restored.acceptTerms ?? false;
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: SubmitEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
import { locale, t } from "../../i18n/store";
|
||||
import { getDefaultCountry } from "../../utils/consts";
|
||||
import { useFormDraft, restoreFields } from "../../utils/forms/useFormDraft.svelte";
|
||||
import { getValidationParams } from "../../utils/validation";
|
||||
import { zRegisterForm } from "../../validation/registerValidation";
|
||||
import Spinner from "../icons/status/Spinner.svelte";
|
||||
@@ -88,6 +89,36 @@
|
||||
let formError = $state("");
|
||||
let showFormToast = $state(false);
|
||||
|
||||
/**
|
||||
* The fields worth keeping across a language switch. The password and the tax id are
|
||||
* left out on purpose: they are sensitive, and the visitor can type them again.
|
||||
*/
|
||||
const { restored } = useFormDraft("checkout-register", () => ({
|
||||
type: form.type,
|
||||
identifier: form.identifier,
|
||||
firstname: form.firstname,
|
||||
lastname: form.lastname,
|
||||
legalName: form.legalName,
|
||||
taxIdCountry: form.taxIdCountry,
|
||||
showTaxIdField,
|
||||
acceptTerms,
|
||||
}));
|
||||
|
||||
if (restored) {
|
||||
form.type = restored.type === "organization" ? "organization" : "individual";
|
||||
|
||||
restoreFields(form, restored, [
|
||||
"identifier",
|
||||
"firstname",
|
||||
"lastname",
|
||||
"legalName",
|
||||
"taxIdCountry",
|
||||
]);
|
||||
|
||||
showTaxIdField = restored.showTaxIdField ?? false;
|
||||
acceptTerms = restored.acceptTerms ?? false;
|
||||
}
|
||||
|
||||
function validate(field: FieldName) {
|
||||
// taxId validity depends on country and type, so it is checked by the schema refinement
|
||||
if (field === "taxId") {
|
||||
|
||||
@@ -12,12 +12,17 @@
|
||||
apiThemesIdOrSlugGetUrl,
|
||||
} from "../../openapi/client";
|
||||
import { client } from "../../openapi/client/client.gen";
|
||||
import { CAMPAIGN_MAX_END_DATE, CAMPAIGN_MIN_START_DATE } from "../../utils/dates";
|
||||
import { CAMPAIGN_MAX_END_DATE, CAMPAIGN_MIN_START_DATE, formatDate } from "../../utils/dates";
|
||||
import { useFormDraft, restoreFields } from "../../utils/forms/useFormDraft.svelte";
|
||||
import { getValidationParams } from "../../utils/validation";
|
||||
import {
|
||||
zCreateProjectForm,
|
||||
zProjectCampaignRelease,
|
||||
} from "../../validation/projectValidation";
|
||||
import BookmarkIcon from "../icons/actions/Bookmark.svelte";
|
||||
import CalendarIcon from "../icons/Calendar.svelte";
|
||||
import CategoryIcon from "../icons/Category.svelte";
|
||||
import LocationIcon from "../icons/Location.svelte";
|
||||
import ActionableButton, {
|
||||
type ActionableState,
|
||||
} from "../library/buttons/ActionableButton.svelte";
|
||||
@@ -28,7 +33,9 @@
|
||||
import TerritoryInput from "../library/inputs/TerritoryInput.svelte";
|
||||
import TextArea from "../library/inputs/TextArea.svelte";
|
||||
import TextInput from "../library/inputs/TextInput.svelte";
|
||||
import Tag from "../library/tags/Tag.svelte";
|
||||
import Title from "../library/typography/Title.svelte";
|
||||
import TerritoryTag from "../project/TerritoryTag.svelte";
|
||||
|
||||
import type z from "zod";
|
||||
|
||||
@@ -45,9 +52,59 @@
|
||||
});
|
||||
|
||||
let validation: Partial<Record<keyof typeof form, z.core.$ZodIssue[]>> = $state({});
|
||||
let isValid = $derived(Object.values(validation).every((issues) => !issues?.length));
|
||||
let submitState = $state<ActionableState>("actionable");
|
||||
let showError = $state(false);
|
||||
let selectedCategories = $state<Category[]>([]);
|
||||
let selectedThemes = $state<Theme[]>([]);
|
||||
|
||||
let titleSection: HTMLElement | undefined = $state();
|
||||
let subtitleSection: HTMLElement | undefined = $state();
|
||||
let categoriesSection: HTMLElement | undefined = $state();
|
||||
let themesSection: HTMLElement | undefined = $state();
|
||||
let territorySection: HTMLElement | undefined = $state();
|
||||
let releaseSection: HTMLElement | undefined = $state();
|
||||
|
||||
/**
|
||||
* Identifiers of the picked categories and themes.
|
||||
*
|
||||
* The tags themselves are rendered from them, so they are what has to be kept to bring
|
||||
* the selection back after a language switch.
|
||||
*/
|
||||
let selectedCategoryIds = $state<string[]>([]);
|
||||
let selectedThemeIds = $state<string[]>([]);
|
||||
/** Text of the territory search, which is what shows the picked place. */
|
||||
let territoryQuery = $state("");
|
||||
|
||||
/**
|
||||
* Nothing sensitive goes into this form, so everything it holds can be kept.
|
||||
*/
|
||||
const { restored } = useFormDraft("create-project", () => ({
|
||||
title: form.title ?? "",
|
||||
subtitle: form.subtitle ?? "",
|
||||
categoryIds: selectedCategoryIds,
|
||||
themeIds: selectedThemeIds,
|
||||
territory: form.territory,
|
||||
territoryQuery,
|
||||
release: form.calendar?.release,
|
||||
}));
|
||||
|
||||
if (restored) {
|
||||
restoreFields(form, restored, ["title", "subtitle", "territory"]);
|
||||
|
||||
const categoryIds = restored.categoryIds ?? [];
|
||||
const themeIds = restored.themeIds ?? [];
|
||||
|
||||
selectedCategoryIds = categoryIds;
|
||||
selectedThemeIds = themeIds;
|
||||
|
||||
form.themes = themesIri(themeIds);
|
||||
|
||||
territoryQuery = restored.territoryQuery ?? "";
|
||||
|
||||
if (restored.release) {
|
||||
form.calendar = { release: restored.release };
|
||||
}
|
||||
}
|
||||
|
||||
function validate(field: keyof typeof form) {
|
||||
const result = zCreateProjectForm.shape[field].safeParse(form[field]);
|
||||
@@ -56,7 +113,43 @@
|
||||
}
|
||||
|
||||
function hasError(field: keyof typeof form) {
|
||||
return validation[field] && validation[field].length > 0;
|
||||
return (validation[field]?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Form fields in the order they are displayed, so the first invalid one is
|
||||
* also the topmost one.
|
||||
*/
|
||||
const fieldSections: {
|
||||
field: keyof typeof form;
|
||||
getSection: () => HTMLElement | undefined;
|
||||
}[] = [
|
||||
{ field: "title", getSection: () => titleSection },
|
||||
{ field: "subtitle", getSection: () => subtitleSection },
|
||||
{ field: "categories", getSection: () => categoriesSection },
|
||||
{ field: "themes", getSection: () => themesSection },
|
||||
{ field: "territory", getSection: () => territorySection },
|
||||
{ field: "calendar", getSection: () => releaseSection },
|
||||
];
|
||||
|
||||
/**
|
||||
* Scrolls to the topmost invalid field and focuses it, so the user knows
|
||||
* which field has to be fixed.
|
||||
*/
|
||||
function focusFirstInvalidField() {
|
||||
const section = fieldSections.find(({ field }) => hasError(field))?.getSection();
|
||||
|
||||
if (!section) {
|
||||
return;
|
||||
}
|
||||
|
||||
section.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
|
||||
const focusable = section.querySelector<HTMLElement>(
|
||||
"input, textarea, select, button:not([disabled])",
|
||||
);
|
||||
|
||||
focusable?.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
function getValidationMessage(field: keyof typeof form) {
|
||||
@@ -74,6 +167,12 @@
|
||||
return $t("pages.project.create.validation.titleBadFormat");
|
||||
}
|
||||
|
||||
if (issue.code === "too_small" && field === "title") {
|
||||
return $t("pages.project.create.validation.titleTooShort", {
|
||||
min: String(issue.minimum),
|
||||
});
|
||||
}
|
||||
|
||||
if (issue.code === "too_small" && field === "subtitle") {
|
||||
return $t("pages.project.create.validation.subtitleMissing");
|
||||
}
|
||||
@@ -102,13 +201,29 @@
|
||||
return items.map(({ id }) => client.buildUrl({ url, path: { idOrSlug: String(id) } }));
|
||||
}
|
||||
|
||||
/** IRIs of the categories with those identifiers. */
|
||||
function categoriesIri(ids: string[]): string[] {
|
||||
return toIris(
|
||||
categories.filter((category) => category.id && ids.includes(category.id)),
|
||||
apiCategoriesIdOrSlugGetUrl,
|
||||
);
|
||||
}
|
||||
|
||||
/** IRIs of the themes with those identifiers. */
|
||||
function themesIri(ids: string[]): string[] {
|
||||
return toIris(
|
||||
themes.filter((theme) => theme.id && ids.includes(theme.id)),
|
||||
apiThemesIdOrSlugGetUrl,
|
||||
);
|
||||
}
|
||||
|
||||
function handleCategories(categories: Category[]) {
|
||||
// @ts-expect-error toIris may have fewer, but it gets validated
|
||||
form.categories = toIris(categories, apiCategoriesIdOrSlugGetUrl);
|
||||
selectedCategories = categories;
|
||||
validate("categories");
|
||||
}
|
||||
|
||||
function handleThemes(themes: Theme[]) {
|
||||
selectedThemes = themes;
|
||||
form.themes = toIris(themes, apiThemesIdOrSlugGetUrl);
|
||||
validate("themes");
|
||||
}
|
||||
@@ -163,6 +278,22 @@
|
||||
|
||||
validation[field] = [...(validation[field] ?? []), issue];
|
||||
}
|
||||
}
|
||||
|
||||
// The API allows a null release date, but a campaign cannot be created without it
|
||||
if (!form.calendar?.release && !hasError("calendar")) {
|
||||
validation.calendar = [
|
||||
{
|
||||
code: "custom",
|
||||
path: ["calendar"],
|
||||
message: "pages.project.create.validation.releaseMissing",
|
||||
input: form.calendar,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (Object.values(validation).some((issues) => issues?.length)) {
|
||||
focusFirstInvalidField();
|
||||
|
||||
throw new Error("Invalid project form");
|
||||
}
|
||||
@@ -177,6 +308,10 @@
|
||||
if (error) {
|
||||
if ("violations" in error) {
|
||||
handleViolations(error.violations ?? []);
|
||||
|
||||
if (hasError("title")) {
|
||||
focusFirstInvalidField();
|
||||
}
|
||||
} else {
|
||||
showError = true;
|
||||
}
|
||||
@@ -207,15 +342,17 @@
|
||||
<p class="text-black transition-all duration-300 ease-in-out">
|
||||
{$t("pages.project.create.description.description")}
|
||||
</p>
|
||||
<TextInput
|
||||
bind:value={form.title}
|
||||
onInput={() => validate("title")}
|
||||
helperText={$t("pages.project.create.description.titlePrompt")}
|
||||
placeholder={$t("pages.project.create.description.titlePlaceholder")}
|
||||
error={getValidationMessage("title")}
|
||||
required
|
||||
/>
|
||||
<div class="relative">
|
||||
<div bind:this={titleSection}>
|
||||
<TextInput
|
||||
bind:value={form.title}
|
||||
onInput={() => validate("title")}
|
||||
helperText={$t("pages.project.create.description.titlePrompt")}
|
||||
placeholder={$t("pages.project.create.description.titlePlaceholder")}
|
||||
error={getValidationMessage("title")}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="relative" bind:this={subtitleSection}>
|
||||
<TextArea
|
||||
bind:value={form.subtitle}
|
||||
onInput={() => validate("subtitle")}
|
||||
@@ -225,34 +362,36 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-4" bind:this={categoriesSection}>
|
||||
<Title level={2} variant="subsection">
|
||||
{$t("Choose a shelf")}
|
||||
</Title>
|
||||
<p
|
||||
class={twJoin(
|
||||
"transition-all duration-300 ease-in-out",
|
||||
hasError("categories") ? "text-tertiary" : "text-black",
|
||||
)}
|
||||
>
|
||||
{#if hasError("categories")}
|
||||
{getValidationMessage("categories")}
|
||||
{:else}
|
||||
{$t("pages.project.create.categories.subtitle")}
|
||||
{/if}
|
||||
<p class="text-black transition-all duration-300 ease-in-out">
|
||||
{$t("pages.project.create.categories.subtitle")}
|
||||
</p>
|
||||
<CategorySelect max={2} options={categories} onChange={handleCategories} />
|
||||
<CategorySelect
|
||||
max={2}
|
||||
options={categories}
|
||||
bind:selectedIds={selectedCategoryIds}
|
||||
onChange={handleCategories}
|
||||
error={getValidationMessage("categories")}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-4" bind:this={themesSection}>
|
||||
<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} />
|
||||
<CategorySelect
|
||||
max={1}
|
||||
options={themes}
|
||||
bind:selectedIds={selectedThemeIds}
|
||||
onChange={handleThemes}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-4" bind:this={territorySection}>
|
||||
<Title level={2} variant="subsection">
|
||||
{$t("pages.project.create.address.title")}
|
||||
</Title>
|
||||
@@ -261,11 +400,12 @@
|
||||
</p>
|
||||
<TerritoryInput
|
||||
placeholder={$t("pages.project.create.address.placeholder")}
|
||||
bind:value={territoryQuery}
|
||||
onInput={handleTerritory}
|
||||
error={getValidationMessage("territory")}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-4" bind:this={releaseSection}>
|
||||
<Title level={2} variant="subsection">
|
||||
{$t("pages.project.create.release.title")}
|
||||
</Title>
|
||||
@@ -282,32 +422,52 @@
|
||||
error={getValidationMessage("calendar")}
|
||||
/>
|
||||
</div>
|
||||
<ActionableButton
|
||||
type="submit"
|
||||
action={submit}
|
||||
bind:state={submitState}
|
||||
disabled={!isValid || submitState !== "actionable"}
|
||||
class="w-fit"
|
||||
>
|
||||
<ActionableButton type="submit" action={submit} bind:state={submitState} 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">
|
||||
<div class="mb-20 ml-auto">
|
||||
<BaseCard
|
||||
class="border-grey flex h-full max-h-126.5 w-full max-w-109.25 flex-col bg-white"
|
||||
class="border-grey flex w-full max-w-109.25 flex-col bg-white md:sticky md:top-(--sticky-top)"
|
||||
style="box-shadow: 0 35px 10px 0 rgba(0, 0, 0, 0.00), 0 22px 9px 0 rgba(0, 0, 0, 0.01), 0 13px 8px 0 rgba(0, 0, 0, 0.05), 0 6px 6px 0 rgba(0, 0, 0, 0.09), 0 1px 3px 0 rgba(0, 0, 0, 0.10);"
|
||||
>
|
||||
<Title level={2} variant="section" color="secondary" class="mb-2">
|
||||
{form.title || $t("pages.project.create.description.titlePlaceholder")}
|
||||
</Title>
|
||||
<p
|
||||
class="text-content w-full overflow-hidden text-base font-normal text-ellipsis whitespace-nowrap"
|
||||
>
|
||||
<p class="text-content line-clamp-4 w-full text-base font-normal break-words">
|
||||
{form.subtitle || $t("pages.project.create.description.subtitlePlaceholder")}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-2 pt-4">
|
||||
{#if selectedCategories.length}
|
||||
<Tag>
|
||||
<CategoryIcon width="24" height="24" />
|
||||
<span>{selectedCategories.map(({ name }) => name).join(", ")}</span>
|
||||
</Tag>
|
||||
{/if}
|
||||
{#if selectedThemes.length}
|
||||
<Tag>
|
||||
<BookmarkIcon />
|
||||
<span>{selectedThemes.map(({ name }) => name).join(", ")}</span>
|
||||
</Tag>
|
||||
{/if}
|
||||
{#if form.territory?.country}
|
||||
<TerritoryTag territory={form.territory} iconSize="24" class="border-0" />
|
||||
{:else}
|
||||
<Tag class="opacity-24">
|
||||
<LocationIcon width="24" height="24" />
|
||||
<span>{$t("pages.project.create.address.placeholder")}</span>
|
||||
</Tag>
|
||||
{/if}
|
||||
{#if form.calendar?.release}
|
||||
<Tag>
|
||||
<CalendarIcon width="24" height="24" />
|
||||
<span>{formatDate(new Date(form.calendar.release), $locale)}</span>
|
||||
</Tag>
|
||||
{/if}
|
||||
</div>
|
||||
</BaseCard>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
<!--
|
||||
The footer markup, shared by the site footer (`layouts/Footer.astro`, server-rendered
|
||||
without hydration) and the live preview of the footer editor.
|
||||
|
||||
Every editable element carries `data-edit` with its path in `FooterConfig`
|
||||
(e.g. "navColumns.0.links.1"), which the editor uses to jump to its field.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import FooterLink from "./FooterLink.svelte";
|
||||
import FooterPartnerImage from "./FooterPartnerImage.svelte";
|
||||
import {
|
||||
FOOTER_BRAND as brand,
|
||||
FOOTER_SOCIAL_ICONS,
|
||||
localized,
|
||||
} from "../../layouts/footer-data";
|
||||
import Title from "../library/typography/Title.svelte";
|
||||
|
||||
import type { Locale } from "../../i18n/locales";
|
||||
import type { FooterConfig } from "../../types/footer";
|
||||
|
||||
interface Props {
|
||||
config: FooterConfig;
|
||||
lang: Locale;
|
||||
/** Passed in rather than `$t`, which only renders the default locale on the server. */
|
||||
t: (key: string) => string;
|
||||
/** Keeps heading ids unique when the preview and the site footer share a page. */
|
||||
idPrefix?: string;
|
||||
}
|
||||
|
||||
let { config, lang, t, idPrefix = "footer" }: Props = $props();
|
||||
|
||||
// Groups without logos are not shown; the index is kept for the editor's `data-edit` paths.
|
||||
const partnerGroups = $derived(
|
||||
config.partnerGroups
|
||||
.map((group, index) => ({ group, index }))
|
||||
.filter(({ group }) => group.partners.length > 0),
|
||||
);
|
||||
|
||||
const showPartners = $derived(!config.hidden.partners && partnerGroups.length > 0);
|
||||
</script>
|
||||
|
||||
<footer class="text-variant1" aria-labelledby="{idPrefix}-heading">
|
||||
<h2 id="{idPrefix}-heading" class="sr-only">{t("common.footer.a11y.footerHeading")}</h2>
|
||||
|
||||
{#if showPartners}
|
||||
<section
|
||||
class="bg-purple-soft text-tertiary border-variant1 rounded-t-3xl border-x-2 border-t-2 pt-6 pb-12 sm:pt-8 sm:pb-14 md:pt-10 md:pb-16"
|
||||
aria-label={t("common.footer.a11y.partnerOrganizations")}
|
||||
>
|
||||
<div class="wrapper">
|
||||
<div
|
||||
class="flex flex-col gap-6 lg:flex-row lg:flex-wrap lg:items-center lg:justify-between lg:gap-8"
|
||||
>
|
||||
{#each partnerGroups as { group, index } (group)}
|
||||
<div class="flex flex-col gap-3 md:flex-row md:items-center md:gap-4">
|
||||
<div data-edit="partnerGroups.{index}">
|
||||
<Title level={3} variant="field" color="secondary">
|
||||
{localized(group.title, lang)}
|
||||
</Title>
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-wrap items-center gap-2 sm:gap-3"
|
||||
role="list"
|
||||
aria-label={localized(group.title, lang)}
|
||||
>
|
||||
{#each group.partners as partner, partnerIndex (partner)}
|
||||
<div data-edit="partnerGroups.{index}.partners.{partnerIndex}">
|
||||
<FooterPartnerImage
|
||||
src={partner.src}
|
||||
alt={partner.alt}
|
||||
href={partner.href || undefined}
|
||||
size="medium"
|
||||
class="rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
class={[
|
||||
"bg-secondary relative rounded-t-3xl bg-size-[116%_114%] bg-position-[-127%_42%] bg-no-repeat min-[700px]:bg-size-[64%_108%] min-[700px]:bg-position-[114%]",
|
||||
// Overlaps the logos band so its side borders run on behind the rounded corners.
|
||||
showPartners && "-mt-6",
|
||||
]}
|
||||
style="background-image: url('{brand.backgroundImage}');"
|
||||
>
|
||||
<section
|
||||
class="relative z-10 py-6 sm:py-8 md:py-10"
|
||||
aria-labelledby="{idPrefix}-navigation-heading"
|
||||
>
|
||||
<div class="wrapper">
|
||||
<div class="flex flex-col gap-8 lg:flex-row lg:justify-between lg:gap-8">
|
||||
{#if !config.hidden.navigation}
|
||||
<nav
|
||||
class="grid grid-cols-2 gap-6 sm:grid-cols-4 lg:flex lg:flex-row lg:gap-8 xl:gap-10"
|
||||
aria-label={t("common.footer.a11y.footerNavigation")}
|
||||
>
|
||||
<h2 id="{idPrefix}-navigation-heading" class="sr-only">
|
||||
{t("common.footer.a11y.footerNavigation")}
|
||||
</h2>
|
||||
|
||||
{#each config.navColumns as column, columnIndex (column)}
|
||||
<div class="space-y-2">
|
||||
<div data-edit="navColumns.{columnIndex}">
|
||||
<Title
|
||||
level={4}
|
||||
variant="field"
|
||||
color="purple-soft"
|
||||
class="leading-6"
|
||||
>
|
||||
{localized(column.title, lang)}
|
||||
</Title>
|
||||
</div>
|
||||
<ul class="space-y-1 text-xs leading-5 sm:text-sm sm:leading-6">
|
||||
{#each column.links as link, index (link)}
|
||||
<li data-edit="navColumns.{columnIndex}.links.{index}">
|
||||
<FooterLink href={link.href}>
|
||||
{localized(link.label, lang)}
|
||||
</FooterLink>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
{/each}
|
||||
</nav>
|
||||
{/if}
|
||||
|
||||
<div class="flex justify-center lg:ml-auto lg:justify-end">
|
||||
<div class="h-8 w-28 sm:h-10 sm:w-36">
|
||||
<img
|
||||
src={brand.logo.src}
|
||||
alt={brand.logo.alt}
|
||||
class="h-full w-full object-contain"
|
||||
loading="lazy"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
class="relative z-10 pb-6 sm:pb-8 md:pb-10"
|
||||
aria-labelledby="{idPrefix}-bottom-heading"
|
||||
>
|
||||
<div class="wrapper">
|
||||
<div
|
||||
class="flex flex-col gap-4 sm:gap-6 lg:flex-row lg:items-center lg:justify-between"
|
||||
>
|
||||
{#if !config.hidden.legal}
|
||||
<nav
|
||||
class="flex flex-wrap gap-4 sm:gap-6 lg:gap-8"
|
||||
aria-label={t("common.footer.a11y.legalNavigation")}
|
||||
>
|
||||
<h3 id="{idPrefix}-bottom-heading" class="sr-only">
|
||||
{t("common.footer.a11y.legalAndSocial")}
|
||||
</h3>
|
||||
{#each config.legalLinks as link, index (link)}
|
||||
<span data-edit="legalLinks.{index}">
|
||||
<FooterLink
|
||||
href={link.href}
|
||||
class="text-xs leading-4 font-medium"
|
||||
>
|
||||
{localized(link.label, lang)}
|
||||
</FooterLink>
|
||||
</span>
|
||||
{/each}
|
||||
</nav>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
class="flex flex-col gap-4 sm:gap-6 md:flex-row md:items-center lg:ml-auto"
|
||||
>
|
||||
{#if !config.hidden.social}
|
||||
<div
|
||||
class="flex items-center justify-center gap-2 lg:justify-start"
|
||||
role="list"
|
||||
aria-label={t("common.footer.a11y.socialLinks")}
|
||||
>
|
||||
{#each config.social as link, index (link)}
|
||||
{@const Icon = FOOTER_SOCIAL_ICONS[link.network]}
|
||||
<a
|
||||
href={link.href}
|
||||
data-edit="social.{index}"
|
||||
class="focus:ring-purple-soft focus:ring-offset-secondary rounded-sm transition-all duration-200 hover:opacity-80 focus:ring-2 focus:ring-offset-2 focus:outline-none"
|
||||
aria-label={t(`common.footer.a11y.social.${link.network}`)}
|
||||
>
|
||||
<Icon width="24" height="24" />
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="text-variant1 flex flex-col items-center lg:items-start">
|
||||
<img
|
||||
src={brand.platoniq.src}
|
||||
alt={brand.platoniq.alt}
|
||||
class="h-4 sm:h-5"
|
||||
loading="lazy"
|
||||
/>
|
||||
<div class="text-xs leading-normal font-light sm:text-sm">
|
||||
{t("common.footer.platoniq.foundation")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</footer>
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import { languagesList } from "../../i18n/locales";
|
||||
import { locale } from "../../i18n/store";
|
||||
import { persistFormDrafts } from "../../stores/formDraftsStore";
|
||||
import { setCookie } from "../../utils/cookies";
|
||||
import { getLanguageDisplayName } from "../../utils/lang";
|
||||
import Chevron from "../icons/navigation/Chevron.svelte";
|
||||
@@ -19,6 +20,10 @@
|
||||
return;
|
||||
}
|
||||
|
||||
// The page is about to be replaced by one in another language, so what the forms
|
||||
// hold is written down first.
|
||||
persistFormDrafts();
|
||||
|
||||
setCookie("preferred-lang", lang);
|
||||
|
||||
let pathParts = window.location.pathname.split("/").filter(Boolean);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<script lang="ts">
|
||||
import CampaignCard from "./CampaignCard.svelte";
|
||||
import CampaignsTabsNav from "./CampaignsTabsNav.svelte";
|
||||
import { t } from "../../i18n/store";
|
||||
import Carousel from "../library/layout/Carousel.svelte";
|
||||
|
||||
import type { ProposedCampaignTab } from "../../repositories/proposedCampaigns";
|
||||
import type { Campaign } from "../../types/campaign";
|
||||
|
||||
interface Props {
|
||||
campaignsByTab: Partial<Record<ProposedCampaignTab, Campaign[]>>;
|
||||
}
|
||||
|
||||
let { campaignsByTab }: Props = $props();
|
||||
|
||||
let activeTab = $state<ProposedCampaignTab>("ending-soon");
|
||||
|
||||
let activeCampaigns = $derived(campaignsByTab[activeTab] ?? []);
|
||||
|
||||
function handleTabChange(tabId: string) {
|
||||
activeTab = tabId as ProposedCampaignTab;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<CampaignsTabsNav {activeTab} onTabChange={handleTabChange} alignment="center" />
|
||||
|
||||
{#if activeCampaigns.length > 0}
|
||||
<Carousel itemsPerGroup={3} gap={24} showDots={false}>
|
||||
{#each activeCampaigns as campaign (campaign.slug)}
|
||||
<CampaignCard size="small" {campaign} />
|
||||
{/each}
|
||||
</Carousel>
|
||||
{:else}
|
||||
<p class="text-content text-base font-normal">{$t("common.noData")}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,50 +1,63 @@
|
||||
---
|
||||
import CampaignCard from "./CampaignCard.svelte";
|
||||
import Carousel from "../library/layout/Carousel.svelte";
|
||||
import CampaignsTabsNav from "./CampaignsTabsNav.svelte";
|
||||
import CampaignTabsCarousel from "./CampaignTabsCarousel.svelte";
|
||||
import type { Campaign } from "../../types/campaign";
|
||||
import {
|
||||
apiAccountingsIdGet,
|
||||
apiProjectsIdOrSlugGet,
|
||||
type Money,
|
||||
type Project,
|
||||
} from "../../openapi/client";
|
||||
import { getLanguage } from "../../middleware/utils";
|
||||
import { apiAccountingsIdGet, apiProjectsGetCollection, type Money } from "../../openapi/client";
|
||||
import { extractId } from "../../utils/extractId";
|
||||
import { proposedCampaignsRepository } from "../../repositories/proposedCampaigns";
|
||||
|
||||
import type { ProposedCampaignTab } from "../../repositories/proposedCampaigns";
|
||||
|
||||
const { t } = Astro.locals;
|
||||
const chosenProjects = {
|
||||
"salvem-el-delta-del-llobregat": "",
|
||||
"la-nuestra": "",
|
||||
"portal-de-ressenyes-sobre-pisos": "",
|
||||
};
|
||||
|
||||
// Mock campaign data - using same campaigns as the main Campaigns component
|
||||
const { data: projects } = await apiProjectsGetCollection({
|
||||
query: {
|
||||
"slug[]": Object.keys(chosenProjects),
|
||||
},
|
||||
headers: {
|
||||
"Accept-Language": getLanguage(Astro),
|
||||
},
|
||||
});
|
||||
const data = await proposedCampaignsRepository.get();
|
||||
const slots = (data?.slots ?? []).sort((a, b) => a.position - b.position);
|
||||
if (slots.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const campaigns: Campaign[] = await Promise.all(
|
||||
projects!.map(async (project) => {
|
||||
const resolved = (
|
||||
await Promise.all(
|
||||
slots.map(async (slot) => {
|
||||
const { data: project } = await apiProjectsIdOrSlugGet({
|
||||
path: { idOrSlug: String(slot.projectId) },
|
||||
headers: { "Accept-Language": getLanguage(Astro) },
|
||||
});
|
||||
|
||||
if (!project) return null;
|
||||
|
||||
return { slot, project };
|
||||
}),
|
||||
)
|
||||
).filter((r): r is { slot: (typeof slots)[number]; project: Project } => r !== null);
|
||||
|
||||
const campaignsByTab: Partial<Record<ProposedCampaignTab, Campaign[]>> = {};
|
||||
|
||||
await Promise.all(
|
||||
resolved.map(async ({ slot, project }) => {
|
||||
const { data: accounting } = await apiAccountingsIdGet({
|
||||
path: { id: extractId(project.accounting)! },
|
||||
});
|
||||
|
||||
return {
|
||||
const campaign = {
|
||||
...project,
|
||||
size: "small",
|
||||
size: "small" as const,
|
||||
slug: project.slug!,
|
||||
title: project.title!,
|
||||
image: project.cover || project.video?.thumbnail!,
|
||||
minimum: project.budget?.minimum?.money!,
|
||||
optimum: project.budget?.optimum?.money,
|
||||
obtained: accounting!.balance as Money,
|
||||
optimum: project.budget?.optimum?.money,
|
||||
} satisfies Campaign;
|
||||
|
||||
(campaignsByTab[slot.tab] ??= []).push(campaign);
|
||||
}),
|
||||
);
|
||||
|
||||
// Get campaigns for the currently active tab
|
||||
const displayCampaigns = campaigns.slice(0, 3);
|
||||
---
|
||||
|
||||
<section class="wrapper flex flex-col gap-6">
|
||||
@@ -53,19 +66,6 @@ const displayCampaigns = campaigns.slice(0, 3);
|
||||
<h2 class="text-2xl font-bold text-black">{t("pages.home.campaigns.tabsTitle")}</h2>
|
||||
</div>
|
||||
|
||||
<!-- Tab Navigation using shared Tabs component -->
|
||||
<div class="mx-auto">
|
||||
<CampaignsTabsNav client:visible />
|
||||
</div>
|
||||
|
||||
<!-- Campaigns Carousel -->
|
||||
<div>
|
||||
<Carousel client:visible itemsPerGroup={3} gap={24} showDots={false}>
|
||||
{
|
||||
displayCampaigns.map((campaign) => (
|
||||
<CampaignCard size="small" campaign={campaign} client:visible />
|
||||
))
|
||||
}
|
||||
</Carousel>
|
||||
</div>
|
||||
<!-- Tabs + Campaigns Carousel (one set of campaigns per tab) -->
|
||||
<CampaignTabsCarousel client:visible {campaignsByTab} />
|
||||
</section>
|
||||
|
||||
@@ -1,44 +1,41 @@
|
||||
<script lang="ts">
|
||||
import { t } from "../../i18n/store";
|
||||
import Clock from "../icons/Clock.svelte";
|
||||
import Flash from "../icons/media/Flash.svelte";
|
||||
import Tabs from "../library/layout/Tabs.svelte";
|
||||
|
||||
interface Props {
|
||||
activeTab?: string;
|
||||
onTabChange?: (tabId: string) => void;
|
||||
alignment?: "left" | "center";
|
||||
}
|
||||
|
||||
let { activeTab = "most-successful", onTabChange }: Props = $props();
|
||||
let { activeTab = "ending-soon", onTabChange, alignment = "left" }: Props = $props();
|
||||
</script>
|
||||
|
||||
{#snippet clockIconSnippet()}
|
||||
<Clock class="size-4" />
|
||||
{/snippet}
|
||||
|
||||
{#snippet flashIconSnippet()}
|
||||
<Flash class="size-4" />
|
||||
{/snippet}
|
||||
|
||||
<!-- The "ending soon" and "matchfunding" tabs below are disabled; re-add their
|
||||
icon snippets (Clock / Flames) together with the tab entries. -->
|
||||
|
||||
<Tabs
|
||||
tabs={[
|
||||
{
|
||||
id: "ending-soon",
|
||||
label: $t("pages.home.campaigns.tabs.endingSoon"),
|
||||
icon: clockIconSnippet,
|
||||
},
|
||||
{
|
||||
id: "most-successful",
|
||||
label: $t("pages.home.campaigns.tabs.mostSuccessful"),
|
||||
icon: flashIconSnippet,
|
||||
},
|
||||
// Uncomment when ready to enable
|
||||
// {
|
||||
// id: "ending-soon",
|
||||
// label: $t("pages.home.campaigns.tabs.endingSoon"),
|
||||
// icon: clockIconSnippet,
|
||||
// },
|
||||
// {
|
||||
// id: "matchfunding",
|
||||
// label: $t("pages.home.campaigns.tabs.withMatchfunding"),
|
||||
// icon: matchFundingIconSnippet,
|
||||
// },
|
||||
]}
|
||||
{activeTab}
|
||||
alignment="left"
|
||||
{alignment}
|
||||
useDataAttributes={false}
|
||||
{onTabChange}
|
||||
/>
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
<script lang="ts">
|
||||
import type { ClassNameValue } from "tailwind-merge";
|
||||
import { twMerge, type ClassNameValue } from "tailwind-merge";
|
||||
|
||||
let { class: classes } = $props<{
|
||||
interface Props {
|
||||
class?: ClassNameValue;
|
||||
}>();
|
||||
}
|
||||
|
||||
let { class: classes }: Props = $props();
|
||||
</script>
|
||||
|
||||
<svg
|
||||
class={classes}
|
||||
class={twMerge(classes)}
|
||||
width="26"
|
||||
height="26"
|
||||
viewBox="0 0 26 26"
|
||||
|
||||
@@ -35,8 +35,8 @@
|
||||
...rest
|
||||
}: Props = $props();
|
||||
|
||||
const anchorProps = rest as HTMLAnchorAttributes;
|
||||
const buttonProps = rest as HTMLButtonAttributes;
|
||||
const anchorProps = $derived(rest as HTMLAnchorAttributes);
|
||||
const buttonProps = $derived(rest as HTMLButtonAttributes);
|
||||
|
||||
const buttonClass = $derived(
|
||||
twMerge(
|
||||
|
||||
@@ -23,12 +23,10 @@
|
||||
args: {
|
||||
options,
|
||||
variant: "basic",
|
||||
hasSearch: false,
|
||||
selected: [],
|
||||
},
|
||||
argTypes: {
|
||||
variant: { control: "select", options: ["basic", "multiselect"] },
|
||||
hasSearch: { control: "boolean" },
|
||||
chips: { control: "boolean" },
|
||||
},
|
||||
});
|
||||
@@ -40,8 +38,6 @@
|
||||
|
||||
<Story name="MultiselectWithPreselected" args={{ variant: "multiselect", selected: preselected }} />
|
||||
|
||||
<Story name="WithSearch" args={{ variant: "basic", hasSearch: true }} />
|
||||
|
||||
<Story name="MultiselectWithSearch" args={{ variant: "multiselect", hasSearch: true }} />
|
||||
<Story name="Loading" args={{ variant: "basic", isOpen: true, loading: true }} />
|
||||
|
||||
<Story name="Chips" args={{ variant: "multiselect", chips: true, selected: preselected }} />
|
||||
|
||||
@@ -4,37 +4,37 @@
|
||||
|
||||
import DropdownItem from "./DropdownItem.svelte";
|
||||
import { t } from "../../../i18n/store";
|
||||
import SearchIcon from "../../icons/actions/Search.svelte";
|
||||
import Chevron from "../../icons/navigation/Chevron.svelte";
|
||||
import Close from "../../icons/navigation/Close.svelte";
|
||||
import Spinner from "../../icons/status/Spinner.svelte";
|
||||
import Tag from "../tags/Tag.svelte";
|
||||
|
||||
import type { DropdownOption, DropdownVariant } from "./dropdown.types";
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
type RenderedItem = DropdownOption & { position: "start" | "middle" | "end" };
|
||||
|
||||
interface Props {
|
||||
class?: ClassNameValue;
|
||||
searchClasses?: ClassNameValue;
|
||||
variant: DropdownVariant;
|
||||
options: DropdownOption[];
|
||||
selected?: DropdownOption[];
|
||||
onChange?: (option: DropdownOption) => void;
|
||||
hasSearch?: boolean;
|
||||
searchPlaceholder?: string;
|
||||
searchValue?: string;
|
||||
onSearch?: (value: string) => void;
|
||||
clearable?: boolean;
|
||||
onClear?: () => void;
|
||||
singleSelect?: boolean;
|
||||
onInputBlur?: (e?: FocusEvent) => void;
|
||||
/** Build the list with selected options at the top. */
|
||||
label?: string;
|
||||
/** Build the list with selected options at the top. */
|
||||
selectedFirst?: boolean;
|
||||
isOpen?: boolean;
|
||||
/** Shows a spinner in the list box instead of the options. */
|
||||
loading?: boolean;
|
||||
/** Shows the "no options" box when the list is empty. */
|
||||
showEmpty?: boolean;
|
||||
/** Collapsed trigger shows the current selection as removable pills. */
|
||||
chips?: boolean;
|
||||
/** Renders the body of one pill; defaults to the option label. */
|
||||
chip?: Snippet<[DropdownOption]>;
|
||||
/** Replaces the default chevron button. Receives the list id for `aria-controls`. */
|
||||
trigger?: Snippet<[string]>;
|
||||
/**
|
||||
* Extra classes for every list item, e.g. to change the text alignment.
|
||||
* Applied to the <button>/<label> element that holds the option label.
|
||||
@@ -49,34 +49,29 @@
|
||||
|
||||
let {
|
||||
class: classes = undefined,
|
||||
searchClasses = undefined,
|
||||
variant,
|
||||
options = $bindable([]),
|
||||
selected = $bindable([]),
|
||||
onChange,
|
||||
hasSearch = false,
|
||||
searchPlaceholder = $t("domain.search.bar.placeholder"),
|
||||
searchValue = $bindable(""),
|
||||
onSearch = undefined,
|
||||
clearable = false,
|
||||
onClear = undefined,
|
||||
singleSelect = false,
|
||||
onInputBlur = undefined,
|
||||
label = undefined,
|
||||
selectedFirst = false,
|
||||
isOpen = $bindable(false),
|
||||
loading = false,
|
||||
showEmpty = true,
|
||||
chips = false,
|
||||
chip = undefined,
|
||||
trigger = undefined,
|
||||
itemClass = undefined,
|
||||
row = undefined,
|
||||
}: Props = $props();
|
||||
|
||||
const listId = $props.id();
|
||||
|
||||
const hasHeader = $derived(hasSearch || !!label);
|
||||
const hasHeader = $derived(!!trigger || !!label);
|
||||
const showChips = $derived(chips && selected.length > 0 && !isOpen);
|
||||
|
||||
const renderedItems = $derived.by(() => {
|
||||
const renderedItems = $derived.by((): RenderedItem[] => {
|
||||
const selectedIds = new Set(selected.map((s) => s.id));
|
||||
|
||||
const merged: DropdownOption[] = selectedFirst
|
||||
@@ -103,17 +98,9 @@
|
||||
return selected.length > 0 && selected.some((s) => s.id === option.id);
|
||||
}
|
||||
|
||||
function handleClear() {
|
||||
searchValue = "";
|
||||
selected = [];
|
||||
isOpen = false;
|
||||
onClear?.();
|
||||
}
|
||||
|
||||
function handleItemChange(option: DropdownOption) {
|
||||
if (singleSelect) {
|
||||
selected = [{ ...option, selected: true }];
|
||||
if (hasSearch && !chips) searchValue = option.label;
|
||||
isOpen = false;
|
||||
} else if (option.selected && !isSelected(option)) {
|
||||
selected = [...selected, option];
|
||||
@@ -167,39 +154,8 @@
|
||||
</Tag>
|
||||
{/each}
|
||||
</div>
|
||||
{:else if hasSearch}
|
||||
<div
|
||||
class={twMerge(
|
||||
"group flex w-full items-center justify-between rounded-lg border border-gray-100 bg-white p-4 shadow-sm outline-none focus:outline-none",
|
||||
searchClasses,
|
||||
)}
|
||||
>
|
||||
<input
|
||||
class="max-h-6 w-full border-0 bg-white p-0 text-base/6 font-normal text-black ring-0 placeholder:opacity-48"
|
||||
type="text"
|
||||
placeholder={searchPlaceholder}
|
||||
aria-expanded={isOpen}
|
||||
aria-controls={listId}
|
||||
bind:value={searchValue}
|
||||
oninput={(e) => onSearch?.(e.currentTarget.value)}
|
||||
onblur={onInputBlur}
|
||||
onclick={() => {
|
||||
if (!isOpen) isOpen = true;
|
||||
}}
|
||||
/>
|
||||
<div class="absolute right-4 flex flex-row gap-1 bg-white">
|
||||
{#if clearable && searchValue}
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 hover:cursor-pointer hover:opacity-75"
|
||||
onclick={handleClear}
|
||||
>
|
||||
<Close width="20" height="20" />
|
||||
</button>
|
||||
{/if}
|
||||
<SearchIcon width="32" height="32" />
|
||||
</div>
|
||||
</div>
|
||||
{:else if trigger}
|
||||
{@render trigger(listId)}
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
@@ -219,9 +175,17 @@
|
||||
{/if}
|
||||
|
||||
{#if isOpen}
|
||||
{#if renderedItems.length}
|
||||
{#if loading}
|
||||
<div
|
||||
class="absolute top-full left-0 z-100 mt-2 w-full flex-col overflow-hidden rounded-lg bg-white shadow-2xl"
|
||||
class="absolute top-full left-0 z-100 mt-2 flex w-full justify-center rounded-lg bg-white p-4 shadow-2xl"
|
||||
>
|
||||
<Spinner />
|
||||
</div>
|
||||
{:else if renderedItems.length}
|
||||
<div
|
||||
id={listId}
|
||||
role="listbox"
|
||||
class="absolute top-full left-0 z-100 mt-2 max-h-80 w-full flex-col overflow-y-auto rounded-lg bg-white shadow-2xl"
|
||||
>
|
||||
{#each renderedItems as item}
|
||||
<DropdownItem
|
||||
@@ -237,7 +201,7 @@
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{:else if !hasSearch || searchValue.trim()}
|
||||
{:else if showEmpty}
|
||||
<p
|
||||
class="text-content absolute top-full left-0 z-100 mt-2 w-full rounded-lg bg-white p-4 text-base shadow-2xl"
|
||||
>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<script module lang="ts">
|
||||
import { defineMeta } from "@storybook/addon-svelte-csf";
|
||||
|
||||
import DropdownSearch from "./DropdownSearch.svelte";
|
||||
|
||||
const options = [
|
||||
{ id: "tech", label: "Technology", selected: false },
|
||||
{ id: "health", label: "Health", selected: false },
|
||||
{ id: "energy", label: "Energy", selected: false },
|
||||
{ id: "finance", label: "Finance", selected: false },
|
||||
{ id: "real-estate", label: "Real Estate", selected: false },
|
||||
];
|
||||
|
||||
const filter = (query: string) =>
|
||||
options.filter((o) => o.label.toLowerCase().includes(query.toLowerCase()));
|
||||
|
||||
/** Fake remote search, slow enough to show the spinner. */
|
||||
const remoteSearch = (query: string) =>
|
||||
new Promise<typeof options>((resolve) => setTimeout(() => resolve(filter(query)), 800));
|
||||
|
||||
const { Story } = defineMeta({
|
||||
component: DropdownSearch,
|
||||
title: "Library/Dropdown/DropdownSearch",
|
||||
tags: ["autodocs"],
|
||||
args: {
|
||||
variant: "basic",
|
||||
search: filter,
|
||||
debounceMs: 0,
|
||||
selected: [],
|
||||
},
|
||||
argTypes: {
|
||||
variant: { control: "select", options: ["basic", "multiselect"] },
|
||||
chips: { control: "boolean" },
|
||||
clearable: { control: "boolean" },
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<Story name="LocalFilter" args={{ singleSelect: true, clearable: true }} />
|
||||
|
||||
<Story
|
||||
name="RemoteSearch"
|
||||
args={{
|
||||
singleSelect: true,
|
||||
clearable: true,
|
||||
search: remoteSearch,
|
||||
minChars: 2,
|
||||
debounceMs: 300,
|
||||
}}
|
||||
/>
|
||||
|
||||
<Story name="MultiselectChips" args={{ variant: "multiselect", chips: true }} />
|
||||
@@ -0,0 +1,201 @@
|
||||
<!--
|
||||
@component
|
||||
`DropdownMenu` with a search input as trigger. Options come from `search`,
|
||||
called debounced on input and right away when the dropdown opens. A spinner
|
||||
fills the list box while a search is running.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { untrack } from "svelte";
|
||||
import { twMerge, type ClassNameValue } from "tailwind-merge";
|
||||
|
||||
import DropdownMenu from "./DropdownMenu.svelte";
|
||||
import { t } from "../../../i18n/store";
|
||||
import { debounce } from "../../../utils/debounce";
|
||||
import SearchIcon from "../../icons/actions/Search.svelte";
|
||||
import Close from "../../icons/navigation/Close.svelte";
|
||||
|
||||
import type { DropdownOption, DropdownVariant } from "./dropdown.types";
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
interface Props {
|
||||
class?: ClassNameValue;
|
||||
/** Extra classes for the search input box. */
|
||||
searchClasses?: ClassNameValue;
|
||||
variant: DropdownVariant;
|
||||
/** Resolves the trimmed query into options. May be sync for local filtering. */
|
||||
search: (
|
||||
query: string,
|
||||
signal: AbortSignal,
|
||||
) => DropdownOption[] | Promise<DropdownOption[]>;
|
||||
/** Text typed in the input. */
|
||||
value?: string;
|
||||
placeholder?: string;
|
||||
selected?: DropdownOption[];
|
||||
onChange?: (option: DropdownOption) => void;
|
||||
clearable?: boolean;
|
||||
singleSelect?: boolean;
|
||||
label?: string;
|
||||
selectedFirst?: boolean;
|
||||
/** Shorter queries don't search and empty the list. */
|
||||
minChars?: number;
|
||||
debounceMs?: number;
|
||||
chips?: boolean;
|
||||
itemClass?: ClassNameValue;
|
||||
/** Replaces the label of every list item, see `DropdownMenu`. */
|
||||
row?: Snippet<[DropdownOption]>;
|
||||
}
|
||||
|
||||
let {
|
||||
class: classes = undefined,
|
||||
searchClasses = undefined,
|
||||
variant,
|
||||
search,
|
||||
value = $bindable(""),
|
||||
placeholder = $t("domain.search.bar.placeholder"),
|
||||
selected = $bindable([]),
|
||||
onChange = undefined,
|
||||
clearable = false,
|
||||
singleSelect = false,
|
||||
label = undefined,
|
||||
selectedFirst = false,
|
||||
minChars = 0,
|
||||
debounceMs = 300,
|
||||
chips = false,
|
||||
itemClass = undefined,
|
||||
row = undefined,
|
||||
}: Props = $props();
|
||||
|
||||
let options = $state<DropdownOption[]>([]);
|
||||
let isLoading = $state(false);
|
||||
let isOpen = $state(false);
|
||||
|
||||
let controller: AbortController | undefined;
|
||||
|
||||
const canSearch = $derived(value.trim().length >= minChars);
|
||||
|
||||
// The delay is fixed per instance; reading it untracked keeps the debounced
|
||||
// function stable instead of rebuilding it on every prop read.
|
||||
const runSearch = debounce(
|
||||
(text: string) => void fetchOptions(text),
|
||||
untrack(() => debounceMs),
|
||||
);
|
||||
|
||||
async function fetchOptions(text: string) {
|
||||
// Cancel the in-flight request so a slow earlier response cannot
|
||||
// overwrite the options of a newer query.
|
||||
controller?.abort();
|
||||
const current = new AbortController();
|
||||
controller = current;
|
||||
|
||||
isLoading = true;
|
||||
|
||||
try {
|
||||
const results = await search(text.trim(), current.signal);
|
||||
if (current.signal.aborted) return;
|
||||
options = results;
|
||||
} catch (error) {
|
||||
if (current.signal.aborted) return;
|
||||
console.error("Dropdown search failed:", error);
|
||||
options = [];
|
||||
} finally {
|
||||
if (!current.signal.aborted) isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
runSearch.cancel();
|
||||
controller?.abort();
|
||||
options = [];
|
||||
isLoading = false;
|
||||
}
|
||||
|
||||
function handleInput() {
|
||||
// Opening searches right away, see the effect below.
|
||||
if (!isOpen) {
|
||||
isOpen = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!canSearch) return reset();
|
||||
|
||||
isLoading = true;
|
||||
runSearch(value);
|
||||
}
|
||||
|
||||
// Opened from the input or from the chips: refresh with the current query.
|
||||
$effect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
untrack(() => {
|
||||
if (!canSearch) return reset();
|
||||
|
||||
runSearch.cancel();
|
||||
void fetchOptions(value);
|
||||
});
|
||||
});
|
||||
|
||||
function handleChange(option: DropdownOption) {
|
||||
if (singleSelect && !chips) value = option.label;
|
||||
onChange?.(option);
|
||||
}
|
||||
|
||||
function handleClear() {
|
||||
reset();
|
||||
value = "";
|
||||
selected = [];
|
||||
isOpen = false;
|
||||
}
|
||||
|
||||
$effect(() => () => reset());
|
||||
</script>
|
||||
|
||||
<DropdownMenu
|
||||
class={classes}
|
||||
{variant}
|
||||
{options}
|
||||
bind:selected
|
||||
bind:isOpen
|
||||
onChange={handleChange}
|
||||
{singleSelect}
|
||||
{label}
|
||||
{selectedFirst}
|
||||
loading={isLoading}
|
||||
showEmpty={canSearch && !!value.trim()}
|
||||
{chips}
|
||||
{itemClass}
|
||||
{row}
|
||||
>
|
||||
{#snippet trigger(listId)}
|
||||
<div
|
||||
class={twMerge(
|
||||
"group flex w-full items-center justify-between rounded-lg border border-gray-100 bg-white p-4 shadow-sm outline-none focus:outline-none",
|
||||
searchClasses,
|
||||
)}
|
||||
>
|
||||
<input
|
||||
class="max-h-6 w-full border-0 bg-white p-0 text-base/6 font-normal text-black ring-0 placeholder:opacity-48"
|
||||
type="text"
|
||||
role="combobox"
|
||||
{placeholder}
|
||||
aria-expanded={isOpen}
|
||||
aria-controls={listId}
|
||||
bind:value
|
||||
oninput={handleInput}
|
||||
onclick={() => (isOpen = true)}
|
||||
/>
|
||||
<div class="absolute right-4 flex flex-row gap-1 bg-white">
|
||||
{#if clearable && value}
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 hover:cursor-pointer hover:opacity-75"
|
||||
aria-label={$t("common.remove")}
|
||||
onclick={handleClear}
|
||||
>
|
||||
<Close width="20" height="20" />
|
||||
</button>
|
||||
{/if}
|
||||
<SearchIcon width="32" height="32" />
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
</DropdownMenu>
|
||||
@@ -10,11 +10,13 @@
|
||||
open = $bindable(false),
|
||||
title,
|
||||
description,
|
||||
confirmText,
|
||||
onclick,
|
||||
}: {
|
||||
open: boolean;
|
||||
title: string;
|
||||
description: string;
|
||||
confirmText?: string;
|
||||
onclick: () => void | Promise<void>;
|
||||
} = $props();
|
||||
|
||||
@@ -54,7 +56,7 @@
|
||||
{#if isDeleting}
|
||||
<Spinner />
|
||||
{:else}
|
||||
{$t("common.delete")}
|
||||
{confirmText ?? $t("common.delete")}
|
||||
{/if}
|
||||
</Button>
|
||||
{/snippet}
|
||||
|
||||
@@ -121,7 +121,6 @@
|
||||
{:else if currentSubject?.options && operator && !singleSelect}
|
||||
<DropdownMenu
|
||||
chips
|
||||
searchClasses="border-secondary"
|
||||
variant="multiselect"
|
||||
options={dropdownOptions}
|
||||
bind:selected={dropdownSelected}
|
||||
|
||||
@@ -25,7 +25,13 @@
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<label for={id} class={twMerge("flex cursor-pointer items-center gap-4", classes)}>
|
||||
<label
|
||||
for={id}
|
||||
class={twMerge(
|
||||
"flex cursor-pointer items-center gap-4 has-disabled:cursor-not-allowed has-disabled:opacity-50",
|
||||
classes,
|
||||
)}
|
||||
>
|
||||
<input {id} bind:checked type="checkbox" class="peer sr-only" {...rest} />
|
||||
<div
|
||||
class="peer-focus-visible:outline-auto flex h-6 w-6 shrink-0 items-center justify-center rounded-[5px] border-[1.5px] transition-colors peer-focus-visible:ring-2 peer-focus-visible:outline-offset-2
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<script lang="ts">
|
||||
import { twJoin, twMerge, type ClassNameValue } from "tailwind-merge";
|
||||
|
||||
import { isHexColor } from "../../../utils/themeColors";
|
||||
import Warning from "../../icons/status/Warning.svelte";
|
||||
|
||||
interface Props {
|
||||
value?: string;
|
||||
id?: string;
|
||||
name?: string;
|
||||
labelText: string;
|
||||
helperText?: string;
|
||||
pickerLabel?: string;
|
||||
error?: string;
|
||||
contrastWarnings?: string[];
|
||||
disabled?: boolean;
|
||||
class?: ClassNameValue;
|
||||
}
|
||||
|
||||
let {
|
||||
value = $bindable(""),
|
||||
id = undefined,
|
||||
name = undefined,
|
||||
labelText,
|
||||
helperText = undefined,
|
||||
pickerLabel = labelText,
|
||||
error = undefined,
|
||||
contrastWarnings = [],
|
||||
disabled = false,
|
||||
class: classes = "",
|
||||
}: Props = $props();
|
||||
|
||||
const generatedId = $props.id();
|
||||
const finalId = $derived(id ?? generatedId);
|
||||
const pickerValue = $derived(isHexColor(value) ? value.slice(0, 7) : "#000000");
|
||||
|
||||
function handlePickerInput(event: Event) {
|
||||
const pickedColor = (event.currentTarget as HTMLInputElement).value;
|
||||
const alpha = value.length === 9 ? value.slice(7) : "";
|
||||
value = `${pickedColor}${alpha}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class={twMerge("relative flex flex-col gap-2", classes)}>
|
||||
<label for={finalId} class="text-secondary text-sm font-medium">
|
||||
{labelText}
|
||||
</label>
|
||||
<div
|
||||
class={twJoin(
|
||||
"border-secondary focus-within:ring-secondary flex items-center gap-3 rounded-lg border bg-white p-2 focus-within:ring-1",
|
||||
error && "border-tertiary",
|
||||
disabled && "cursor-not-allowed opacity-50",
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type="color"
|
||||
value={pickerValue}
|
||||
oninput={handlePickerInput}
|
||||
aria-label={pickerLabel}
|
||||
{disabled}
|
||||
class="h-10 w-12 shrink-0 cursor-pointer rounded border-0 bg-transparent p-0"
|
||||
/>
|
||||
<input
|
||||
bind:value
|
||||
id={finalId}
|
||||
{name}
|
||||
{disabled}
|
||||
type="text"
|
||||
inputmode="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
aria-invalid={Boolean(error)}
|
||||
aria-describedby={error || helperText ? `helper-${finalId}` : undefined}
|
||||
class={twMerge(
|
||||
"text-content min-w-0 flex-1 bg-transparent p-1 font-mono text-base uppercase outline-none",
|
||||
error && "text-tertiary",
|
||||
)}
|
||||
/>
|
||||
<span
|
||||
class="border-grey h-8 w-8 shrink-0 rounded-full border"
|
||||
style:background-color={isHexColor(value) ? value : "transparent"}
|
||||
aria-hidden="true"
|
||||
></span>
|
||||
</div>
|
||||
{#if error || helperText}
|
||||
<span
|
||||
id={`helper-${finalId}`}
|
||||
class={twJoin("text-xs", error ? "text-tertiary" : "text-content")}
|
||||
>
|
||||
{error || helperText}
|
||||
</span>
|
||||
{/if}
|
||||
{#if contrastWarnings.length}
|
||||
<div class="flex flex-col gap-1" aria-live="polite">
|
||||
{#each contrastWarnings as warning}
|
||||
<p
|
||||
class="bg-semantic-warning flex items-start gap-2 rounded-md p-2 text-xs text-black"
|
||||
>
|
||||
<Warning class="mt-0.5 size-4 shrink-0" />
|
||||
<span>{warning}</span>
|
||||
</p>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -48,7 +48,7 @@
|
||||
>
|
||||
<!-- Stop propagation: flowbite closes the dialog on any click that reaches it -->
|
||||
<div
|
||||
class="flex min-h-0 flex-col gap-8 overflow-y-auto rounded-3xl bg-white p-6 shadow-lg"
|
||||
class="flex min-h-0 w-full flex-col gap-8 overflow-y-auto rounded-3xl bg-white p-6 shadow-lg"
|
||||
role="presentation"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
placeholder?: string;
|
||||
helperText?: string;
|
||||
error?: string;
|
||||
disabled?: boolean;
|
||||
minChars?: number;
|
||||
debounceMs?: number;
|
||||
/** Wrap query matches in <mark> in the default row. */
|
||||
@@ -80,6 +81,7 @@
|
||||
placeholder = undefined,
|
||||
helperText = undefined,
|
||||
error = undefined,
|
||||
disabled = false,
|
||||
minChars = DEFAULT_MIN_CHARS,
|
||||
debounceMs = 300,
|
||||
highlight = true,
|
||||
@@ -205,7 +207,8 @@
|
||||
</script>
|
||||
|
||||
<div
|
||||
class={twMerge("relative flex w-full flex-col gap-2", classes)}
|
||||
class={twMerge("relative flex w-full flex-col gap-2", disabled && "opacity-50", classes)}
|
||||
inert={disabled}
|
||||
use:clickOutside={() => (isOpen = false)}
|
||||
>
|
||||
{#if multiple && selected.length > 0}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
internally, so any format other than "json" is a lossy projection of the document.
|
||||
|
||||
Content flows one way — there is no two-way binding. `minLength`/`maxLength` only colour the
|
||||
character counter; enforcement lives in stores/drafts/draftValidation.ts.
|
||||
character counter; enforcement lives in src/validation/.
|
||||
-->
|
||||
<script lang="ts" generics="F extends RichTextFormat = 'json'">
|
||||
import { Editor } from "@tiptap/core";
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
placeholder?: string;
|
||||
helperText?: string;
|
||||
error?: string;
|
||||
disabled?: boolean;
|
||||
onInput?: (territory: Territory) => void;
|
||||
onBlur?: () => void;
|
||||
multiple?: boolean;
|
||||
@@ -28,6 +29,7 @@
|
||||
placeholder,
|
||||
helperText,
|
||||
error = undefined,
|
||||
disabled = false,
|
||||
onInput = undefined,
|
||||
onBlur = undefined,
|
||||
multiple = false,
|
||||
@@ -95,6 +97,7 @@
|
||||
{placeholder}
|
||||
{helperText}
|
||||
{error}
|
||||
{disabled}
|
||||
onSelect={handleSelect}
|
||||
onChange={handleChange}
|
||||
onClear={handleClear}
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
),
|
||||
);
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let container = $state<HTMLDivElement>();
|
||||
|
||||
let totalGroups = $state(0);
|
||||
let totalItems = $state(0);
|
||||
@@ -316,7 +316,7 @@
|
||||
resizeObs = new ResizeObserver(() => {
|
||||
if (mounted && container) updateItemWidths();
|
||||
});
|
||||
resizeObs.observe(container);
|
||||
resizeObs.observe(container!);
|
||||
|
||||
mutationObs = new MutationObserver(() => {
|
||||
if (mounted && container) {
|
||||
@@ -324,7 +324,7 @@
|
||||
observeVisibility();
|
||||
}
|
||||
});
|
||||
mutationObs.observe(container, { childList: true, subtree: true });
|
||||
mutationObs.observe(container!, { childList: true, subtree: true });
|
||||
|
||||
window.addEventListener("resize", updateItemWidths);
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { twMerge, type ClassNameValue } from "tailwind-merge";
|
||||
|
||||
let { class: classes = "", children } = $props<{
|
||||
import type { Snippet } from "svelte";
|
||||
|
||||
interface Props {
|
||||
class?: ClassNameValue;
|
||||
children: any;
|
||||
}>();
|
||||
children: Snippet;
|
||||
}
|
||||
|
||||
let { class: classes = "", children }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class={twMerge("grid grid-cols-2 gap-6 lg:grid-cols-3", classes)}>
|
||||
|
||||
@@ -3,19 +3,21 @@
|
||||
import Chevron from "../../icons/navigation/Chevron.svelte";
|
||||
import PaginationNavButton from "../buttons/PaginationNavButton.svelte";
|
||||
|
||||
interface Props {
|
||||
currentPage?: number;
|
||||
totalItems?: number;
|
||||
itemsPerPage?: number;
|
||||
isLoading?: boolean;
|
||||
onPageChange?: (page: number) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
currentPage: currentPageProp = 1,
|
||||
totalItems: totalItemsProp = 0,
|
||||
itemsPerPage: itemsPerPageProp = 10,
|
||||
isLoading = false,
|
||||
onPageChange,
|
||||
} = $props<{
|
||||
currentPage?: number;
|
||||
totalItems?: number;
|
||||
itemsPerPage?: number;
|
||||
isLoading?: boolean;
|
||||
onPageChange?: (page: number) => void;
|
||||
}>();
|
||||
}: Props = $props();
|
||||
|
||||
const totalPages = $derived(Math.max(1, Math.ceil(totalItemsProp / itemsPerPageProp)));
|
||||
const page = $derived(Math.min(Math.max(1, currentPageProp), totalPages));
|
||||
|
||||
@@ -3,22 +3,22 @@
|
||||
|
||||
import { t } from "../../i18n/store";
|
||||
|
||||
let {
|
||||
src,
|
||||
title = $t("pages.project.view.video.title"),
|
||||
onReady = () => {},
|
||||
} = $props<{
|
||||
interface Props {
|
||||
src: string;
|
||||
title?: string;
|
||||
onReady?: () => void;
|
||||
}>();
|
||||
}
|
||||
|
||||
let { src, title = $t("pages.project.view.video.title"), onReady = () => {} }: Props = $props();
|
||||
|
||||
let iframe: HTMLIFrameElement;
|
||||
let player: any = $state(null);
|
||||
let isReady = $state(false);
|
||||
|
||||
// The link arrives already pointing at the instance's embed URL; only the
|
||||
// parameters of the player are missing.
|
||||
function makeEmbedSrc(url: string): string {
|
||||
const base = url.replace("/videos/watch/", "/videos/embed/").split("?")[0];
|
||||
const base = url.split("?")[0];
|
||||
const params = new URLSearchParams({
|
||||
api: "1",
|
||||
autoplay: "1",
|
||||
|
||||
@@ -1,124 +1,76 @@
|
||||
<script lang="ts">
|
||||
import PeerTube from "./PeerTube.svelte";
|
||||
import { t } from "../../i18n/store";
|
||||
import { detectVideo } from "../../utils/video";
|
||||
import Spinner from "../icons/status/Spinner.svelte";
|
||||
import Loader from "../library/feedback/Loader.svelte";
|
||||
|
||||
let {
|
||||
src,
|
||||
title = $t("pages.project.view.video.title"),
|
||||
thumbnails = "",
|
||||
poster = { src: "", alt: $t("pages.project.view.video.poster") },
|
||||
} = $props<{
|
||||
interface Props {
|
||||
src: string;
|
||||
title?: string;
|
||||
thumbnails?: string;
|
||||
thumbnail?: string;
|
||||
poster?: {
|
||||
src: string;
|
||||
alt: string;
|
||||
};
|
||||
}>();
|
||||
}
|
||||
|
||||
let {
|
||||
src,
|
||||
title = $t("pages.project.view.video.title"),
|
||||
thumbnail = "",
|
||||
poster = { src: "", alt: $t("pages.project.view.video.poster") },
|
||||
}: Props = $props();
|
||||
|
||||
let showIframe = $state(false);
|
||||
let isCheckingProvider = $state(true);
|
||||
let isYouTube = $state(false);
|
||||
let isVimeo = $state(false);
|
||||
let noVideoSrc = $state(false);
|
||||
let isPeerTube = $state(false);
|
||||
let isLoading = $state(false);
|
||||
let iframeEl: HTMLIFrameElement | null = $state(null);
|
||||
|
||||
let previewImage = $derived(poster.src || thumbnails);
|
||||
let previewImage = $derived(poster.src || thumbnail);
|
||||
|
||||
$effect(() => {
|
||||
noVideoSrc = !src;
|
||||
isYouTube = src.includes("youtube.com") || src.includes("youtu.be");
|
||||
isVimeo = src.includes("vimeo.com");
|
||||
isPeerTube = src.includes("/videos/watch/");
|
||||
isCheckingProvider = false;
|
||||
});
|
||||
|
||||
function normalizeYouTubeUrl(original: string): string {
|
||||
try {
|
||||
const url = new URL(original);
|
||||
let videoId = "";
|
||||
|
||||
if (url.hostname === "youtu.be") {
|
||||
videoId = url.pathname.slice(1);
|
||||
} else if (url.hostname.includes("youtube.com")) {
|
||||
if (url.pathname === "/watch") {
|
||||
videoId = url.searchParams.get("v") ?? "";
|
||||
} else if (url.pathname.startsWith("/embed/")) {
|
||||
videoId = url.pathname.split("/embed/")[1];
|
||||
}
|
||||
}
|
||||
|
||||
if (!videoId) return original;
|
||||
|
||||
const params = new URLSearchParams({
|
||||
autoplay: "1",
|
||||
rel: "0",
|
||||
modestbranding: "1",
|
||||
});
|
||||
|
||||
return `https://www.youtube.com/embed/${videoId}?${params.toString()}`;
|
||||
} catch {
|
||||
console.warn("Invalid YouTube URL", original);
|
||||
return original;
|
||||
}
|
||||
}
|
||||
// The link the author pasted points to a page, not to a player: the API
|
||||
// stores it as it was given, so the embeddable URL is worked out here.
|
||||
let source = $derived(detectVideo(src));
|
||||
let embedSrc = $derived(showIframe && source ? source.autoplayUrl : "");
|
||||
|
||||
function handlePlay() {
|
||||
if (!source) return;
|
||||
|
||||
isLoading = true;
|
||||
showIframe = true;
|
||||
|
||||
if (isYouTube) {
|
||||
src = normalizeYouTubeUrl(src);
|
||||
} else {
|
||||
const separator = src.includes("?") ? "&" : "?";
|
||||
src = `${src}${separator}autoplay=1`;
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
iframeEl?.focus();
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if isCheckingProvider}
|
||||
<div class="bg-grey flex h-full items-center justify-center rounded-lg">
|
||||
<Loader />
|
||||
</div>
|
||||
{:else if isPeerTube}
|
||||
{#snippet posterButton()}
|
||||
<button class="group relative h-full w-full" onclick={handlePlay} aria-label="Play video">
|
||||
<img
|
||||
src={previewImage}
|
||||
alt={poster.alt}
|
||||
class="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center bg-black/10 transition-colors duration-300 group-hover:bg-black/20"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-16 w-16 text-white opacity-90"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</button>
|
||||
{/snippet}
|
||||
|
||||
{#if source?.provider === "peertube"}
|
||||
<div class="relative h-full w-full overflow-hidden rounded-lg">
|
||||
{#if !showIframe}
|
||||
<button
|
||||
onclick={() => {
|
||||
showIframe = true;
|
||||
isLoading = true;
|
||||
}}
|
||||
aria-label="Play video"
|
||||
class="group relative h-full w-full"
|
||||
>
|
||||
<img
|
||||
src={previewImage}
|
||||
alt={poster.alt}
|
||||
class="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center bg-black/10 transition-colors duration-300 group-hover:bg-black/20"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-16 w-16 text-white opacity-90"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</button>
|
||||
{@render posterButton()}
|
||||
{:else}
|
||||
<div class="absolute inset-0 z-10 h-full w-full bg-black">
|
||||
{#if isLoading}
|
||||
@@ -128,47 +80,26 @@
|
||||
<Spinner />
|
||||
</div>
|
||||
{/if}
|
||||
<PeerTube {src} {title} onReady={() => (isLoading = false)} />
|
||||
<PeerTube src={source.embedUrl} {title} onReady={() => (isLoading = false)} />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if isYouTube || isVimeo}
|
||||
{:else if source?.provider === "youtube" || source?.provider === "vimeo"}
|
||||
<div class="relative h-full w-full overflow-hidden rounded-lg">
|
||||
{#if !showIframe}
|
||||
<button
|
||||
class="group relative h-full w-full"
|
||||
onclick={handlePlay}
|
||||
aria-label="Play video"
|
||||
>
|
||||
<img
|
||||
src={previewImage}
|
||||
alt={poster.alt}
|
||||
class="h-full w-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center bg-black/10 transition-colors duration-300 group-hover:bg-black/20"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-16 w-16 text-white opacity-90"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</button>
|
||||
{@render posterButton()}
|
||||
{:else}
|
||||
<div class="absolute inset-0 z-10 h-full w-full bg-black">
|
||||
{#if isLoading}
|
||||
<div class="absolute inset-0 z-20 flex items-center justify-center">
|
||||
<div
|
||||
class="pointer-events-none absolute inset-0 z-20 flex items-center justify-center"
|
||||
>
|
||||
<Spinner />
|
||||
</div>
|
||||
{/if}
|
||||
<iframe
|
||||
bind:this={iframeEl}
|
||||
{src}
|
||||
src={embedSrc}
|
||||
{title}
|
||||
class={`absolute inset-0 h-full w-full transition-opacity duration-500 ${isLoading ? "opacity-0" : "opacity-100"}`}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen"
|
||||
@@ -179,9 +110,18 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if noVideoSrc && previewImage}
|
||||
{:else if source?.provider === "file"}
|
||||
<!-- svelte-ignore a11y_media_has_caption -->
|
||||
<video
|
||||
src={source.embedUrl}
|
||||
poster={previewImage || undefined}
|
||||
controls
|
||||
playsinline
|
||||
class="h-full w-full rounded-lg bg-black object-contain"
|
||||
></video>
|
||||
{:else if !src && previewImage}
|
||||
<img src={previewImage} alt={poster.alt} class="h-full w-full rounded-lg object-cover" />
|
||||
{:else if noVideoSrc}
|
||||
{:else if !src}
|
||||
<div
|
||||
class="bg-grey text-content/70 flex h-full items-center justify-center rounded-lg p-4 text-sm"
|
||||
>
|
||||
|
||||
@@ -139,7 +139,7 @@
|
||||
...project,
|
||||
slug: project.slug!,
|
||||
title: project.title!,
|
||||
image: project.video?.thumbnail!,
|
||||
image: project.cover || project.video?.thumbnail!,
|
||||
minimum: project.budget?.minimum?.money!,
|
||||
optimum: project.budget?.optimum?.money,
|
||||
obtained: accounting.balance as Money,
|
||||
|
||||
@@ -1,37 +1,74 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from "svelte";
|
||||
import { twMerge, type ClassNameValue } from "tailwind-merge";
|
||||
|
||||
import MotivatingProjectsSection from "./manage/MotivatingProjectsSection.svelte";
|
||||
import { languagesList } from "../../i18n/locales";
|
||||
import { locale, t } from "../../i18n/store";
|
||||
import { apiUsersIdPatch } from "../../openapi/client";
|
||||
import { getCookie, setCookie } from "../../utils/cookies";
|
||||
import { useFormDraft } from "../../utils/forms/useFormDraft.svelte";
|
||||
import ActionableButton from "../library/buttons/ActionableButton.svelte";
|
||||
import Toast from "../library/feedback/Toast.svelte";
|
||||
import Checkbox from "../library/inputs/Checkbox.svelte";
|
||||
import Select from "../library/inputs/Select.svelte";
|
||||
import Title from "../library/typography/Title.svelte";
|
||||
|
||||
import type { Category } from "../../openapi/client";
|
||||
import type { Category, User } from "../../openapi/client";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
/** Categories to offer, read by the page from `apiCategoriesGetCollection` */
|
||||
categories?: Category[];
|
||||
class?: ClassNameValue;
|
||||
}
|
||||
|
||||
let { categories = [], class: classes = "" }: Props = $props();
|
||||
let { user, categories = [], class: classes = "" }: Props = $props();
|
||||
|
||||
let language: string = $state($locale ?? "es");
|
||||
// Seeded once: later prop changes must not overwrite what the user is editing
|
||||
const initialIsAnonymous = untrack(() => user.isAnonymous ?? false);
|
||||
let isAnonymous = $state(initialIsAnonymous);
|
||||
let savedIsAnonymous = initialIsAnonymous;
|
||||
let toast = $state(false);
|
||||
let errorToast = $state(false);
|
||||
let motivatingProjects: Category[] = $state([]);
|
||||
|
||||
const CATEGORIES_COOKIE = "preferred-categories";
|
||||
|
||||
/**
|
||||
* The preferences are kept while they are not saved yet: the categories picked and the
|
||||
* language chosen, which is itself one of the ways of switching the language.
|
||||
*/
|
||||
const { restored } = useFormDraft("manage-preferences", () => ({
|
||||
language,
|
||||
categoryIds: motivatingProjects.map((category) => String(category.id)),
|
||||
}));
|
||||
|
||||
const restoredCategoryIds = restored?.categoryIds;
|
||||
|
||||
if (restored?.language) {
|
||||
language = restored.language;
|
||||
}
|
||||
|
||||
if (restoredCategoryIds) {
|
||||
motivatingProjects = untrack(() => categories).filter((category) =>
|
||||
restoredCategoryIds.includes(String(category.id)),
|
||||
);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const stored = getCookie(CATEGORIES_COOKIE);
|
||||
if (!stored || motivatingProjects.length > 0 || categories.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A draft recovered after a language switch holds the newer choice, even when it is
|
||||
// an empty one.
|
||||
if (restoredCategoryIds) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const ids = JSON.parse(stored) as (string | number)[];
|
||||
motivatingProjects = categories.filter((category) =>
|
||||
@@ -42,8 +79,8 @@
|
||||
}
|
||||
});
|
||||
|
||||
/* The preferred language is the only preference this screen owns, and the API has no
|
||||
endpoint for it: it lives in a cookie, read back by `src/middleware/index.ts`. */
|
||||
/* The API has no endpoint for the preferred language: it lives in a cookie, read back by
|
||||
`src/middleware/index.ts`. Anonymity is the only preference stored on the `User`. */
|
||||
async function save() {
|
||||
setCookie("preferred-lang", language);
|
||||
|
||||
@@ -54,6 +91,21 @@
|
||||
|
||||
setCookie(CATEGORIES_COOKIE, JSON.stringify(ids));
|
||||
|
||||
if (isAnonymous !== savedIsAnonymous) {
|
||||
const { error } = await apiUsersIdPatch({
|
||||
baseUrl: "/api/relay",
|
||||
path: { id: String(user.id) },
|
||||
body: { isAnonymous },
|
||||
});
|
||||
|
||||
if (error) {
|
||||
errorToast = true;
|
||||
throw error;
|
||||
}
|
||||
|
||||
savedIsAnonymous = isAnonymous;
|
||||
}
|
||||
|
||||
toast = true;
|
||||
}
|
||||
|
||||
@@ -99,9 +151,23 @@
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="flex flex-col gap-3">
|
||||
<Title level={2} variant="subsection">
|
||||
{$t("pages.me.manage.preferences.privacy.title")}
|
||||
</Title>
|
||||
|
||||
<Checkbox
|
||||
bind:checked={isAnonymous}
|
||||
label={$t("pages.me.manage.preferences.privacy.anonymous")}
|
||||
class="mt-2 gap-2"
|
||||
/>
|
||||
</section>
|
||||
<MotivatingProjectsSection options={categories} bind:selected={motivatingProjects} />
|
||||
</form>
|
||||
|
||||
<Toast bind:showToast={toast} variant="success">
|
||||
{$t("pages.me.manage.preferences.toast.saved")}
|
||||
</Toast>
|
||||
<Toast bind:showToast={errorToast} variant="error">
|
||||
{$t("pages.me.manage.preferences.toast.error")}
|
||||
</Toast>
|
||||
|
||||
@@ -67,9 +67,9 @@
|
||||
slug: project.slug!,
|
||||
title: project.title!,
|
||||
image:
|
||||
project.video?.thumbnail ??
|
||||
project.video?.cover ??
|
||||
project.cover ??
|
||||
project.video?.cover ??
|
||||
project.video?.thumbnail ??
|
||||
"/images/project/placeholder-project-update.jpg",
|
||||
minimum: project.budget?.minimum?.money,
|
||||
optimum: project.budget?.optimum?.money,
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
import Tag from "../../library/tags/Tag.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
import type { AddressAddressUpdationDto } from "../../../openapi/client";
|
||||
import type { AddressAddressUpdationDtoJsonMergePatch } from "../../../openapi/client";
|
||||
import type { DefaultableAddress } from "../../../utils/defaultAddress";
|
||||
|
||||
let {
|
||||
@@ -70,7 +70,7 @@
|
||||
baseUrl: "/api/relay",
|
||||
path: { id: String(address.id) },
|
||||
// Pending in the API, see `DefaultableAddress`
|
||||
body: { isDefault: true } as AddressAddressUpdationDto,
|
||||
body: { isDefault: true } as AddressAddressUpdationDtoJsonMergePatch,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
@@ -169,7 +169,12 @@
|
||||
<!-- A fresh form per opening, seeded with the address being edited -->
|
||||
{#if formOpen}
|
||||
{#key editing}
|
||||
<AddressForm bind:this={addressForm} address={editing} {userIri} />
|
||||
<AddressForm
|
||||
bind:this={addressForm}
|
||||
address={editing}
|
||||
{userIri}
|
||||
draftId={`manage-address-${editing?.id ?? "new"}`}
|
||||
/>
|
||||
{/key}
|
||||
{/if}
|
||||
</form>
|
||||
|
||||
@@ -8,34 +8,46 @@
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { actions, isInputError } from "astro:actions";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import FormNotice from "./FormNotice.svelte";
|
||||
import ProfileHeader from "./ProfileHeader.svelte";
|
||||
import { locale, t } from "../../../i18n/store";
|
||||
import {
|
||||
apiUsersIdOrHandleGet,
|
||||
apiUsersIdPatch,
|
||||
type Organization,
|
||||
type Person,
|
||||
type Territory,
|
||||
type User,
|
||||
} from "../../../openapi/client";
|
||||
import { getCountries } from "../../../utils/countries";
|
||||
import { useFormDraft, restoreFields } from "../../../utils/forms/useFormDraft.svelte";
|
||||
import { normalizeForMatch } from "../../../utils/highlights";
|
||||
import { type SocialNetwork } from "../../../utils/socialLinks";
|
||||
import { getTerritoryDisplayName, UNKNOWN_COUNTRY_CODE } from "../../../utils/territory";
|
||||
import { trackChanges } from "../../../utils/trackChanges.svelte";
|
||||
import {
|
||||
GENDERS,
|
||||
LEGAL_FORMS,
|
||||
REFERRAL_SOURCES,
|
||||
TAX_ID_TYPES,
|
||||
zPersonalProfileForm,
|
||||
type PersonalProfileForm,
|
||||
} from "../../../validation/personalProfileValidation";
|
||||
import Spinner from "../../icons/status/Spinner.svelte";
|
||||
import ActionableButton from "../../library/buttons/ActionableButton.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
import Card from "../../library/cards/Card.svelte";
|
||||
import DropdownSearch from "../../library/dropdown/DropdownSearch.svelte";
|
||||
import Toast from "../../library/feedback/Toast.svelte";
|
||||
import Checkbox from "../../library/inputs/Checkbox.svelte";
|
||||
import PasswordInput from "../../library/inputs/PasswordInput.svelte";
|
||||
import Select from "../../library/inputs/Select.svelte";
|
||||
import TerritoryInput from "../../library/inputs/TerritoryInput.svelte";
|
||||
import TextInput from "../../library/inputs/TextInput.svelte";
|
||||
import Title from "../../library/typography/Title.svelte";
|
||||
|
||||
import type { DropdownOption } from "../../library/dropdown/dropdown.types";
|
||||
import type z from "zod";
|
||||
|
||||
type FieldName = keyof PersonalProfileForm;
|
||||
@@ -48,39 +60,118 @@
|
||||
|
||||
let { user, person, organization }: Props = $props();
|
||||
|
||||
// Seeded once: later prop changes must not overwrite what the user is editing
|
||||
const initial = untrack(() => ({ user, person, organization }));
|
||||
|
||||
const country =
|
||||
user.territory?.country === UNKNOWN_COUNTRY_CODE ? "" : (user.territory?.country ?? "");
|
||||
initial.user.territory?.country === UNKNOWN_COUNTRY_CODE
|
||||
? ""
|
||||
: (initial.user.territory?.country ?? "");
|
||||
|
||||
// Changing the profile kind belongs to the public section, here it only routes the tax id
|
||||
const isOrganization = user.type === "organization";
|
||||
const isOrganization = initial.user.type === "organization";
|
||||
|
||||
let form: PersonalProfileForm = $state({
|
||||
handle: user.handle,
|
||||
firstName: person?.firstName ?? "",
|
||||
lastName: person?.lastName ?? "",
|
||||
taxId: isOrganization ? "" : (person?.taxId ?? ""),
|
||||
// Only the fields edited since the last save travel in the payload
|
||||
const { form, changed, commit } = trackChanges<PersonalProfileForm>({
|
||||
handle: initial.user.handle,
|
||||
firstName: initial.person?.firstName ?? "",
|
||||
lastName: initial.person?.lastName ?? "",
|
||||
taxId: (isOrganization ? initial.organization?.taxId : initial.person?.taxId) ?? "",
|
||||
type: isOrganization ? "organization" : "individual",
|
||||
legalName: organization?.legalName ?? "",
|
||||
businessName: organization?.businessName ?? "",
|
||||
legalName: initial.organization?.legalName ?? "",
|
||||
businessName: initial.organization?.businessName ?? "",
|
||||
country,
|
||||
subLvl1: user.territory?.subLvl1 ?? "",
|
||||
subLvl2: user.territory?.subLvl2 ?? "",
|
||||
address: user.territory?.address ?? "",
|
||||
subLvl1: initial.user.territory?.subLvl1 ?? "",
|
||||
subLvl2: initial.user.territory?.subLvl2 ?? "",
|
||||
shareLocation: initial.user.shareLocation ?? false,
|
||||
referralSource: initial.user.referralSource ?? "",
|
||||
taxIdType:
|
||||
(isOrganization ? initial.organization?.taxIdType : initial.person?.taxIdType) ?? "",
|
||||
birthYear: initial.person?.birthYear ? String(initial.person.birthYear) : "",
|
||||
gender: initial.person?.gender ?? "",
|
||||
legalForm: initial.organization?.legalForm ?? "",
|
||||
publicEntity: initial.organization?.publicEntity ?? false,
|
||||
});
|
||||
|
||||
// Not persisted: the API has no visibility or anonymity flag
|
||||
let shareLocation = $state(false);
|
||||
const currentYear = new Date().getFullYear();
|
||||
const birthYears = Array.from({ length: currentYear - 1899 }, (_, i) => currentYear - i);
|
||||
|
||||
// Subdivisions are ISO codes, show them as "Subdivision, Country" in the search box
|
||||
let locality = $state(country ? getTerritoryDisplayName(user.territory!, $locale) : "");
|
||||
let countries = $derived(getCountries($locale));
|
||||
const initialLocality = country
|
||||
? getTerritoryDisplayName(initial.user.territory!, $locale)
|
||||
: "";
|
||||
let locality = $state(initialLocality);
|
||||
|
||||
const countryOptions: DropdownOption[] = $derived(
|
||||
getCountries($locale).map(({ code, name }) => ({ id: code, label: name, selected: false })),
|
||||
);
|
||||
const currentCountry = $derived(countryOptions.find((option) => option.id === form.country));
|
||||
|
||||
let countrySearch = $state("");
|
||||
|
||||
// The locality input can also set the country, so the shown text follows `form.country`.
|
||||
$effect(() => {
|
||||
countrySearch = currentCountry?.label ?? "";
|
||||
});
|
||||
|
||||
// Opening the dropdown searches the shown label: list every country instead of only that one.
|
||||
// Matching ignores accents (`normalizeForMatch`), like the resource search does.
|
||||
function searchCountries(query: string): DropdownOption[] {
|
||||
const needle = normalizeForMatch(query);
|
||||
|
||||
if (needle === normalizeForMatch(currentCountry?.label ?? "")) return countryOptions;
|
||||
|
||||
return countryOptions.filter((option) => normalizeForMatch(option.label).includes(needle));
|
||||
}
|
||||
|
||||
// Picking and clearing both write `selected`; the tax id rules depend on the country.
|
||||
function setCountry(picked: DropdownOption[]) {
|
||||
form.country = picked[0]?.id ?? "";
|
||||
validate("taxId");
|
||||
}
|
||||
|
||||
let validation = $state<Partial<Record<FieldName, z.core.$ZodIssue[]>>>({});
|
||||
let isSubmitting = $state(false);
|
||||
let showSuccess = $state(false);
|
||||
let showError = $state(false);
|
||||
let showNoChanges = $state(false);
|
||||
let formError = $state("");
|
||||
|
||||
/**
|
||||
* Everything the form holds but the tax id and its type, which are fiscal data and are
|
||||
* left out on purpose: the visitor types them again.
|
||||
*/
|
||||
const { restored } = useFormDraft("manage-personal-profile", () => ({
|
||||
handle: form.handle,
|
||||
firstName: form.firstName,
|
||||
lastName: form.lastName,
|
||||
type: form.type,
|
||||
legalName: form.legalName,
|
||||
businessName: form.businessName,
|
||||
country: form.country,
|
||||
subLvl1: form.subLvl1,
|
||||
subLvl2: form.subLvl2,
|
||||
shareLocation: form.shareLocation,
|
||||
referralSource: form.referralSource,
|
||||
birthYear: form.birthYear,
|
||||
gender: form.gender,
|
||||
legalForm: form.legalForm,
|
||||
publicEntity: form.publicEntity,
|
||||
locality,
|
||||
}));
|
||||
|
||||
if (restored) {
|
||||
const { locality: restoredLocality, ...fields } = restored;
|
||||
restoreFields(form, fields);
|
||||
locality = restoredLocality ?? initialLocality;
|
||||
}
|
||||
|
||||
let newPassword = $state("");
|
||||
let confirmPassword = $state("");
|
||||
let passwordError = $state("");
|
||||
let passwordSuccess = $state(false);
|
||||
let changingPassword = $state(false);
|
||||
|
||||
function handleLocality(territory: Territory) {
|
||||
form.country = territory.country ?? form.country;
|
||||
form.subLvl1 = territory.subLvl1 ?? "";
|
||||
@@ -104,12 +195,51 @@
|
||||
return $t(issue.message);
|
||||
}
|
||||
|
||||
async function handleSubmit(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
async function changePassword() {
|
||||
passwordError = "";
|
||||
passwordSuccess = false;
|
||||
|
||||
if (!newPassword) {
|
||||
passwordError = $t("common.password.error.required");
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 8) {
|
||||
passwordError = $t("common.password.error.minLength");
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
passwordError = $t("common.password.error.mismatch");
|
||||
return;
|
||||
}
|
||||
|
||||
changingPassword = true;
|
||||
const { error } = await apiUsersIdPatch({
|
||||
baseUrl: "/api/relay",
|
||||
path: { id: String(user.id) },
|
||||
body: { password: newPassword },
|
||||
});
|
||||
changingPassword = false;
|
||||
|
||||
if (error) {
|
||||
passwordError = $t("common.password.error.generic");
|
||||
return;
|
||||
}
|
||||
|
||||
newPassword = "";
|
||||
confirmPassword = "";
|
||||
passwordSuccess = true;
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
validation = {};
|
||||
showSuccess = false;
|
||||
showError = false;
|
||||
showNoChanges = false;
|
||||
|
||||
if (changed.size === 0) {
|
||||
showNoChanges = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const result = zPersonalProfileForm.safeParse(form);
|
||||
|
||||
@@ -124,7 +254,10 @@
|
||||
|
||||
isSubmitting = true;
|
||||
|
||||
const { data, error } = await actions.updatePersonalProfile(result.data);
|
||||
const { data, error } = await actions.updatePersonalProfile({
|
||||
form: result.data,
|
||||
changed: [...changed],
|
||||
});
|
||||
|
||||
isSubmitting = false;
|
||||
|
||||
@@ -147,7 +280,9 @@
|
||||
if (data.person) {
|
||||
form.firstName = data.person.firstName ?? "";
|
||||
form.lastName = data.person.lastName ?? "";
|
||||
form.taxId = data.person.taxId ?? "";
|
||||
if (form.type === "individual") {
|
||||
form.taxId = data.person.taxId ?? "";
|
||||
}
|
||||
}
|
||||
|
||||
user = await apiUsersIdOrHandleGet({
|
||||
@@ -155,6 +290,7 @@
|
||||
path: { idOrHandle: String(user.id) },
|
||||
}).then(({ data }) => data!);
|
||||
|
||||
commit();
|
||||
showSuccess = true;
|
||||
}
|
||||
</script>
|
||||
@@ -172,7 +308,7 @@
|
||||
handle={user.handle}
|
||||
/>
|
||||
|
||||
<form class="flex flex-col gap-6" onsubmit={handleSubmit} novalidate>
|
||||
<form class="flex flex-col gap-6" onsubmit={(event) => event.preventDefault()} novalidate>
|
||||
<Card class="items-start gap-6 p-8">
|
||||
{@render cardHeader($t("pages.me.manage.info.title"), $t("pages.me.manage.info.subtitle"))}
|
||||
|
||||
@@ -221,20 +357,31 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<Select
|
||||
bind:value={form.country}
|
||||
labelText={$t("pages.me.manage.info.country")}
|
||||
onChange={() => validate("taxId")}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="">{$t("common.select")}</option>
|
||||
{#each countries as { code, name } (code)}
|
||||
<option value={code}>{name}</option>
|
||||
{/each}
|
||||
</Select>
|
||||
<!-- `DropdownSearch` has no `disabled` prop, and a plain fieldset keeps the field inert
|
||||
while saving, like every other input in the form. -->
|
||||
<fieldset class="relative m-0 min-w-0 border-0 p-0" disabled={isSubmitting}>
|
||||
<span
|
||||
class="text-secondary absolute top-0 left-4 z-10 -translate-y-1/2 bg-white px-1 text-sm font-medium"
|
||||
class:opacity-50={isSubmitting}
|
||||
>
|
||||
{$t("pages.me.manage.info.country")}
|
||||
</span>
|
||||
<DropdownSearch
|
||||
variant="basic"
|
||||
singleSelect
|
||||
clearable
|
||||
debounceMs={0}
|
||||
search={searchCountries}
|
||||
placeholder={$t("common.select")}
|
||||
bind:value={countrySearch}
|
||||
bind:selected={() => (currentCountry ? [currentCountry] : []), setCountry}
|
||||
searchClasses="border-secondary h-14 shadow-none"
|
||||
/>
|
||||
</fieldset>
|
||||
<div class="relative">
|
||||
<span
|
||||
class="text-secondary absolute top-0 left-4 z-10 -translate-y-1/2 bg-white px-1 text-sm font-medium"
|
||||
class:opacity-50={isSubmitting}
|
||||
>
|
||||
{$t("pages.me.manage.info.locality")}
|
||||
</span>
|
||||
@@ -243,29 +390,20 @@
|
||||
placeholder={$t("pages.me.manage.info.localityPlaceholder")}
|
||||
searchClasses="border-secondary h-14 shadow-none"
|
||||
onInput={handleLocality}
|
||||
/>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<TextInput
|
||||
bind:value={form.address}
|
||||
labelText={$t("pages.me.manage.info.address")}
|
||||
class="h-14"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-2">
|
||||
<Checkbox
|
||||
bind:checked={shareLocation}
|
||||
label={$t("pages.me.manage.location.share")}
|
||||
class="gap-2"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</div>
|
||||
<Checkbox
|
||||
bind:checked={form.shareLocation}
|
||||
label={$t("pages.me.manage.location.share")}
|
||||
class="gap-2 md:col-span-2"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
|
||||
<Select
|
||||
bind:value={form.type}
|
||||
labelText={$t("pages.me.manage.info.type")}
|
||||
labelText={$t("pages.me.manage.info.userType")}
|
||||
onChange={() => validate("taxId")}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
@@ -276,6 +414,40 @@
|
||||
{$t("pages.checkout.register.form.userType.organization")}
|
||||
</option>
|
||||
</Select>
|
||||
|
||||
{#if form.type === "organization"}
|
||||
<Select
|
||||
bind:value={form.legalForm}
|
||||
labelText={$t("pages.me.manage.info.legalForm")}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="">{$t("common.select")}</option>
|
||||
{#each LEGAL_FORMS as value (value)}
|
||||
<option {value}>
|
||||
{$t(`pages.me.manage.info.legalFormOptions.${value}`)}
|
||||
</option>
|
||||
{/each}
|
||||
</Select>
|
||||
<Checkbox
|
||||
bind:checked={form.publicEntity}
|
||||
label={$t("pages.me.manage.info.publicEntity")}
|
||||
class="gap-2"
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<Select
|
||||
bind:value={form.taxIdType}
|
||||
labelText={$t("pages.me.manage.info.taxIdType")}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="">{$t("common.select")}</option>
|
||||
{#each TAX_ID_TYPES as value (value)}
|
||||
<option {value}>
|
||||
{$t(`pages.me.manage.info.taxIdTypeOptions.${value}`)}
|
||||
</option>
|
||||
{/each}
|
||||
</Select>
|
||||
<TextInput
|
||||
bind:value={form.taxId}
|
||||
labelText={$t("pages.me.manage.info.taxId")}
|
||||
@@ -286,6 +458,29 @@
|
||||
required={form.type === "organization"}
|
||||
/>
|
||||
|
||||
{#if form.type === "individual"}
|
||||
<Select
|
||||
bind:value={form.birthYear}
|
||||
labelText={$t("pages.me.manage.info.birthYear")}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="">{$t("common.select")}</option>
|
||||
{#each birthYears as year (year)}
|
||||
<option value={String(year)}>{year}</option>
|
||||
{/each}
|
||||
</Select>
|
||||
<Select
|
||||
bind:value={form.gender}
|
||||
labelText={$t("pages.me.manage.info.gender")}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="">{$t("common.select")}</option>
|
||||
{#each GENDERS as value (value)}
|
||||
<option {value}>{$t(`pages.me.manage.info.genderOptions.${value}`)}</option>
|
||||
{/each}
|
||||
</Select>
|
||||
{/if}
|
||||
|
||||
{#if form.type === "organization"}
|
||||
<h3 class="text-secondary text-lg leading-6 font-bold md:col-span-2">
|
||||
{$t("pages.me.manage.info.representative")}
|
||||
@@ -308,11 +503,75 @@
|
||||
<FormNotice text={$t("pages.me.manage.location.disclaimer")} />
|
||||
</Card>
|
||||
|
||||
<Card class="items-start gap-6 p-8">
|
||||
{@render cardHeader(
|
||||
$t("pages.me.manage.referral.title"),
|
||||
$t("pages.me.manage.referral.subtitle"),
|
||||
)}
|
||||
|
||||
<div class="grid w-full grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<Select
|
||||
bind:value={form.referralSource}
|
||||
labelText={$t("pages.me.manage.referral.label")}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<option value="">{$t("common.select")}</option>
|
||||
{#each REFERRAL_SOURCES as value (value)}
|
||||
<option {value}>
|
||||
{$t(`pages.me.manage.referral.options.${value}`)}
|
||||
</option>
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card class="items-start gap-6 p-8">
|
||||
{@render cardHeader(
|
||||
$t("pages.me.manage.password.title"),
|
||||
$t("pages.me.manage.password.subtitle"),
|
||||
)}
|
||||
|
||||
<div class="grid w-full grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<PasswordInput
|
||||
bind:value={newPassword}
|
||||
labelText={$t("common.password.new")}
|
||||
class="h-14"
|
||||
disabled={changingPassword}
|
||||
/>
|
||||
<PasswordInput
|
||||
bind:value={confirmPassword}
|
||||
labelText={$t("common.password.confirm")}
|
||||
class="h-14"
|
||||
disabled={changingPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if passwordError}
|
||||
<p class="text-tertiary text-sm">{passwordError}</p>
|
||||
{/if}
|
||||
|
||||
<div class="flex justify-end">
|
||||
<Button type="button" kind="ghost" disabled={changingPassword} onclick={changePassword}>
|
||||
{$t("common.password.change")}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{#if showSuccess}
|
||||
<Toast floating variant="success" bind:showToast={showSuccess}>
|
||||
{$t("pages.me.manage.personal.success")}
|
||||
</Toast>
|
||||
{/if}
|
||||
{#if showNoChanges}
|
||||
<Toast floating variant="notification" bind:showToast={showNoChanges}>
|
||||
{$t("pages.me.manage.noChanges")}
|
||||
</Toast>
|
||||
{/if}
|
||||
{#if passwordSuccess}
|
||||
<Toast floating variant="success" bind:showToast={passwordSuccess}>
|
||||
{$t("common.password.success")}
|
||||
</Toast>
|
||||
{/if}
|
||||
{#if showError}
|
||||
<Toast floating variant="error" bind:showToast={showError}>
|
||||
{formError}
|
||||
@@ -320,12 +579,8 @@
|
||||
{/if}
|
||||
|
||||
<div class="flex justify-end">
|
||||
<Button type="submit" kind="primary" disabled={isSubmitting}>
|
||||
{#if isSubmitting}
|
||||
<Spinner />
|
||||
{:else}
|
||||
{$t("pages.me.manage.save")}
|
||||
{/if}
|
||||
</Button>
|
||||
<ActionableButton action={handleSubmit} autoreset={2000} class="w-fit">
|
||||
{$t("pages.me.manage.save")}
|
||||
</ActionableButton>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -10,12 +10,15 @@
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { actions, isInputError } from "astro:actions";
|
||||
import { untrack } from "svelte";
|
||||
|
||||
import ProfileHeader from "./ProfileHeader.svelte";
|
||||
import ProfileIdentityRow from "./ProfileIdentityRow.svelte";
|
||||
import ProfileSocialsCard from "./ProfileSocialsCard.svelte";
|
||||
import { t } from "../../../i18n/store";
|
||||
import { useFormDraft, restoreFields } from "../../../utils/forms/useFormDraft.svelte";
|
||||
import { toSocialLinks, type SocialNetwork } from "../../../utils/socialLinks";
|
||||
import { trackChanges } from "../../../utils/trackChanges.svelte";
|
||||
import { zProfileForm, type ProfileForm } from "../../../validation/publicProfileValidation";
|
||||
import Spinner from "../../icons/status/Spinner.svelte";
|
||||
import Button from "../../library/buttons/Button.svelte";
|
||||
@@ -33,20 +36,47 @@
|
||||
|
||||
let { user }: Props = $props();
|
||||
|
||||
let form: ProfileForm = $state({
|
||||
avatar: user.avatar || undefined,
|
||||
description: user.description ?? "",
|
||||
links: toSocialLinks((user.links ?? []).flatMap((link) => link.url ?? [])),
|
||||
// Seeded once: later prop changes must not overwrite what the user is editing
|
||||
const initialUser = untrack(() => user);
|
||||
|
||||
const initialDisplayName = initialUser.displayName ?? initialUser.handle;
|
||||
|
||||
// Only the fields edited since the last save travel in the payload
|
||||
const { form, changed, commit } = trackChanges<ProfileForm>({
|
||||
avatar: initialUser.avatar || undefined,
|
||||
description: initialUser.description ?? "",
|
||||
links: toSocialLinks((initialUser.links ?? []).flatMap((link) => link.url ?? [])),
|
||||
});
|
||||
|
||||
let displayName = $state(user.displayName ?? user.handle);
|
||||
let displayName = $state(initialDisplayName);
|
||||
|
||||
let validation = $state<Partial<Record<FieldName, z.core.$ZodIssue[]>>>({});
|
||||
let isSubmitting = $state(false);
|
||||
let showSuccess = $state(false);
|
||||
let showError = $state(false);
|
||||
let showNoChanges = $state(false);
|
||||
let formError = $state("");
|
||||
|
||||
/**
|
||||
* Nothing in this form is sensitive, so all of it can be kept.
|
||||
*/
|
||||
const { restored } = useFormDraft("manage-public-profile", () => ({
|
||||
avatar: form.avatar,
|
||||
description: form.description,
|
||||
links: form.links,
|
||||
displayName,
|
||||
}));
|
||||
|
||||
if (restored) {
|
||||
restoreFields(form, restored, ["avatar", "description"]);
|
||||
|
||||
displayName = restored.displayName ?? initialDisplayName;
|
||||
|
||||
if (restored.links) {
|
||||
Object.assign(form.links, restored.links);
|
||||
}
|
||||
}
|
||||
|
||||
function validate(field: FieldName) {
|
||||
// taxId and organization fields depend on other values, so they go through the refinement
|
||||
const result = zProfileForm.safeParse(form);
|
||||
@@ -70,6 +100,12 @@
|
||||
validation = {};
|
||||
showSuccess = false;
|
||||
showError = false;
|
||||
showNoChanges = false;
|
||||
|
||||
if (changed.size === 0) {
|
||||
showNoChanges = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const result = zProfileForm.safeParse(form);
|
||||
|
||||
@@ -84,7 +120,10 @@
|
||||
|
||||
isSubmitting = true;
|
||||
|
||||
const { data, error } = await actions.updatePublicProfile(result.data);
|
||||
const { data, error } = await actions.updatePublicProfile({
|
||||
form: result.data,
|
||||
changed: [...changed],
|
||||
});
|
||||
|
||||
isSubmitting = false;
|
||||
|
||||
@@ -106,6 +145,7 @@
|
||||
displayName = data.user.displayName ?? data.user.handle;
|
||||
// The API resolves each link (scheme, redirects), show what was stored
|
||||
form.links = toSocialLinks((data.user.links ?? []).flatMap((link) => link.url ?? []));
|
||||
commit();
|
||||
showSuccess = true;
|
||||
}
|
||||
|
||||
@@ -146,6 +186,9 @@
|
||||
<Toast floating variant="success" bind:showToast={showSuccess}>
|
||||
{$t("pages.me.manage.success")}
|
||||
</Toast>
|
||||
<Toast floating variant="notification" bind:showToast={showNoChanges}>
|
||||
{$t("pages.me.manage.noChanges")}
|
||||
</Toast>
|
||||
<Toast floating variant="error" bind:showToast={showError}>
|
||||
{formError}
|
||||
</Toast>
|
||||
|
||||
@@ -64,7 +64,7 @@ export const ME_SECTIONS: MeSection[] = [
|
||||
/**
|
||||
* Sidebar entries for the profile tab, in the shape `WithSidebar` expects. Read out of
|
||||
* `ME_SECTIONS` so a new profile section only has to be declared once, see
|
||||
* `admin/home/subsections.ts` for the same trick on the admin side.
|
||||
* `adminSections.ts` for the same trick on the admin side.
|
||||
*/
|
||||
export const PROFILE_NAV_ITEMS: AdminSidebarItem[] = (
|
||||
ME_SECTIONS.find((section) => section.href === PROFILE_PATHS.root)?.subSections ?? []
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
|
||||
import type { ProjectBudgetItem, Project } from "../../openapi/client/index";
|
||||
|
||||
let { project } = $props<{
|
||||
interface Props {
|
||||
project: Project;
|
||||
}>();
|
||||
}
|
||||
|
||||
let { project }: Props = $props();
|
||||
|
||||
const legendEntries = Object.entries(budgetTypeColors) as [ProjectBudgetItem["type"], string][];
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import { t } from "../../i18n/store";
|
||||
import { apiProjectSupportsGetCollection } from "../../openapi/client/index";
|
||||
import { formatCurrency } from "../../utils/currencies";
|
||||
import Goteo from "../icons/Goteo.svelte";
|
||||
import ActionableButton from "../library/buttons/ActionableButton.svelte";
|
||||
import Loader from "../library/feedback/Loader.svelte";
|
||||
import Grid from "../library/layout/Grid.svelte";
|
||||
@@ -24,7 +25,8 @@
|
||||
|
||||
const projectId = $derived(project.id?.toString());
|
||||
|
||||
let projectsSupportItems = $state<ProjectSupport[]>([]);
|
||||
let supportItems = $state<ProjectSupport[]>([]);
|
||||
let matchfundingItems = $state<ProjectSupport[]>([]);
|
||||
|
||||
let selectedProjectSupport: ProjectSupport | null = $state(null);
|
||||
|
||||
@@ -33,49 +35,44 @@
|
||||
let hasMore = $state(false);
|
||||
let currentPage = $state(1);
|
||||
|
||||
const groupedItems = $derived.by(() =>
|
||||
projectsSupportItems.reduce(
|
||||
(groups, item) => {
|
||||
const type = item.matchfunding ? "matchfunding" : "default";
|
||||
(groups[type] ??= []).push(item);
|
||||
return groups;
|
||||
},
|
||||
{} as Record<string, typeof projectsSupportItems>,
|
||||
),
|
||||
);
|
||||
|
||||
const PAGE_SIZE = 30;
|
||||
const FIRST_PAGE_SIZE = 29;
|
||||
|
||||
async function fetchPage(page: number): Promise<ProjectSupport[]> {
|
||||
const itemsPerPage = page === 1 ? FIRST_PAGE_SIZE : PAGE_SIZE;
|
||||
const { data } = await apiProjectSupportsGetCollection({
|
||||
query: { project: projectId, anonymous: false, page, itemsPerPage },
|
||||
query: {
|
||||
project: projectId,
|
||||
anonymous: false,
|
||||
matchfunding: false,
|
||||
page,
|
||||
itemsPerPage: PAGE_SIZE,
|
||||
},
|
||||
});
|
||||
|
||||
const items = (data as ProjectSupport[]) ?? [];
|
||||
hasMore = items.length === itemsPerPage;
|
||||
hasMore = items.length === PAGE_SIZE;
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
const matchfundingCount = $derived(groupedItems.matchfunding?.length ?? 0);
|
||||
const hasMatchfunding = $derived(matchfundingCount > 0);
|
||||
const isSingleMatchfunding = $derived(matchfundingCount === 1);
|
||||
const hasMatchfunding = $derived(matchfundingItems.length > 0);
|
||||
const isSingleMatchfunding = $derived(matchfundingItems.length === 1);
|
||||
|
||||
// Without matchers the anonymous card shares the grid: hold back the last loaded
|
||||
// item while more pages remain so rows stay full.
|
||||
const visibleDefaultItems = $derived(
|
||||
hasMatchfunding
|
||||
? groupedItems.default
|
||||
: groupedItems.default?.slice(
|
||||
0,
|
||||
PAGE_SIZE - 1 + Math.max(0, (currentPage - 1) * PAGE_SIZE),
|
||||
),
|
||||
hasMatchfunding || !hasMore ? supportItems : supportItems.slice(0, -1),
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
fetchPage(1)
|
||||
.then((items) => {
|
||||
projectsSupportItems = items;
|
||||
Promise.all([
|
||||
apiProjectSupportsGetCollection({
|
||||
query: { project: projectId, matchfunding: true },
|
||||
}),
|
||||
fetchPage(1),
|
||||
])
|
||||
.then(([{ data: matchers }, items]) => {
|
||||
matchfundingItems = (matchers as ProjectSupport[]) ?? [];
|
||||
supportItems = items;
|
||||
})
|
||||
.finally(() => {
|
||||
isLoaded = true;
|
||||
@@ -85,7 +82,7 @@
|
||||
async function loadMore() {
|
||||
const nextPage = currentPage + 1;
|
||||
const supports = await fetchPage(nextPage);
|
||||
projectsSupportItems = [...projectsSupportItems, ...supports];
|
||||
supportItems = [...supportItems, ...supports];
|
||||
currentPage = nextPage;
|
||||
}
|
||||
</script>
|
||||
@@ -104,7 +101,7 @@
|
||||
<Grid
|
||||
class={`grid-cols-1 gap-6 ${isSingleMatchfunding ? "md:grid-cols-2 lg:grid-cols-2" : "md:grid-cols-3"}`}
|
||||
>
|
||||
{#each groupedItems.matchfunding as item (item.id)}
|
||||
{#each matchfundingItems as item (item.id)}
|
||||
<ProjectCommunityMatchfunding
|
||||
{item}
|
||||
bind:openModal
|
||||
@@ -148,9 +145,15 @@
|
||||
role="presentation"
|
||||
>
|
||||
<div class="flex flex-row items-center justify-between gap-4">
|
||||
<div>
|
||||
<div class="flex h-16 w-16 items-center justify-center rounded-lg">😀</div>
|
||||
</div>
|
||||
{#if selectedProjectSupport.displayImage}
|
||||
<img
|
||||
src={selectedProjectSupport.displayImage}
|
||||
alt={selectedProjectSupport.displayName}
|
||||
class="h-16 w-16 shrink-0 rounded-xl object-cover"
|
||||
/>
|
||||
{:else}
|
||||
<Goteo />
|
||||
{/if}
|
||||
<div class="flex flex-col items-end">
|
||||
<div class="font-bold text-black">
|
||||
{$t("pages.project.view.tabs.community.contribution")}
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="border-grey flex h-58 w-full cursor-pointer overflow-hidden rounded-4xl border bg-white shadow-sm transition-shadow duration-200 ease-in-out hover:shadow-lg md:flex-row"
|
||||
class="flex h-58 w-full cursor-pointer overflow-hidden rounded-4xl bg-white shadow-sm transition-shadow duration-200 ease-in-out hover:shadow-lg md:flex-row"
|
||||
>
|
||||
<div class="flex h-full w-2/5 shrink-0 overflow-hidden">
|
||||
<img
|
||||
@@ -37,7 +37,9 @@
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex w-full flex-col justify-center gap-4 p-6">
|
||||
<div
|
||||
class="border-grey flex w-full flex-col justify-center gap-4 rounded-r-4xl border border-l-0 p-6"
|
||||
>
|
||||
<div class="flex flex-col gap-1">
|
||||
{#if money === undefined}
|
||||
<Spinner />
|
||||
|
||||
@@ -6,14 +6,18 @@
|
||||
</script>
|
||||
|
||||
<button
|
||||
class="border-grey flex w-full cursor-pointer overflow-hidden rounded-4xl border bg-white shadow-sm transition-shadow duration-200 ease-in-out hover:shadow-lg"
|
||||
class="flex w-full cursor-pointer overflow-hidden rounded-4xl bg-white text-left shadow-sm transition-shadow duration-200 ease-in-out hover:shadow-lg"
|
||||
onclick={() => {
|
||||
selectedProjectSupport = item;
|
||||
openModal = true;
|
||||
}}
|
||||
>
|
||||
<div class="bg-tertiary flex w-1/3 shrink-0 items-center justify-center p-6"></div>
|
||||
<div class="flex w-2/3 flex-col gap-4 p-6">
|
||||
<div class="bg-tertiary flex w-2/5 shrink-0 items-center justify-center p-6">
|
||||
{#if item.displayImage}
|
||||
<img src={item.displayImage} alt={item.displayName} class="max-h-full object-contain" />
|
||||
{/if}
|
||||
</div>
|
||||
<div class="border-grey flex w-3/5 flex-col gap-4 rounded-r-4xl border border-l-0 p-6">
|
||||
<div class="flex flex-col items-end gap-1">
|
||||
<div class="text-sm font-bold text-black">
|
||||
{$t("pages.project.view.tabs.community.contribution")}
|
||||
|
||||
@@ -5,10 +5,12 @@
|
||||
|
||||
import type { Project, Accounting } from "../../openapi/client/index";
|
||||
|
||||
let { project, accounting } = $props<{
|
||||
interface Props {
|
||||
project: Project;
|
||||
accounting: Accounting;
|
||||
}>();
|
||||
}
|
||||
|
||||
let { project, accounting }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-6 lg:flex-row lg:items-center">
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user