From d034ddf9904b3a6ed4d659e3b590bb21c2f72eea Mon Sep 17 00:00:00 2001 From: rasm-its Date: Fri, 9 Oct 2026 18:00:24 +0200 Subject: [PATCH] Security patch for contact --- dist/exports/client.d.ts | 2 + dist/exports/client.js | 1 + dist/exports/client.js.map | 2 +- dist/index.d.ts | 1 + dist/index.js | 1 + dist/index.js.map | 2 +- dist/modules/forms/index.d.ts | 2 + dist/modules/forms/index.js | 1 + dist/modules/forms/index.js.map | 2 +- dist/modules/forms/useContactForm.d.ts | 64 +++++++++ dist/modules/forms/useContactForm.js | 126 ++++++++++++++++++ dist/modules/forms/useContactForm.js.map | 1 + dist/modules/i18n/index.d.ts | 1 + dist/modules/i18n/index.js | 1 + dist/modules/i18n/index.js.map | 2 +- dist/modules/i18n/resolveLocalized.d.ts | 13 ++ dist/modules/i18n/resolveLocalized.js | 31 +++++ dist/modules/i18n/resolveLocalized.js.map | 1 + src/exports/client.ts | 6 + src/index.ts | 3 +- src/modules/forms/index.ts | 2 + src/modules/forms/useContactForm.ts | 152 ++++++++++++++++++++++ src/modules/i18n/index.ts | 1 + src/modules/i18n/resolveLocalized.ts | 24 ++++ 24 files changed, 437 insertions(+), 5 deletions(-) create mode 100644 dist/modules/forms/useContactForm.d.ts create mode 100644 dist/modules/forms/useContactForm.js create mode 100644 dist/modules/forms/useContactForm.js.map create mode 100644 dist/modules/i18n/resolveLocalized.d.ts create mode 100644 dist/modules/i18n/resolveLocalized.js create mode 100644 dist/modules/i18n/resolveLocalized.js.map create mode 100644 src/modules/forms/useContactForm.ts create mode 100644 src/modules/i18n/resolveLocalized.ts diff --git a/dist/exports/client.d.ts b/dist/exports/client.d.ts index a1f9e3f..de31c6d 100644 --- a/dist/exports/client.d.ts +++ b/dist/exports/client.d.ts @@ -12,6 +12,8 @@ export { Analytics } from '../modules/analytics/client.js'; */ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js'; export type { CookieBannerClassNames } from '../modules/consent/client.js'; +export { useContactForm } from '../modules/forms/useContactForm.js'; +export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js'; export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath, } from '../modules/i18n/index.js'; export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'; export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js'; diff --git a/dist/exports/client.js b/dist/exports/client.js index 9b515d4..82f06ea 100644 --- a/dist/exports/client.js +++ b/dist/exports/client.js @@ -10,6 +10,7 @@ export { Analytics } from '../modules/analytics/client.js'; * components. Kept separate from the main entry so server bundles don't pull in * client-only code. */ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js'; +export { useContactForm } from '../modules/forms/useContactForm.js'; // Pure i18n path helpers — no server/RSC deps, safe to import in client // components (e.g. a LanguageSwitcher that computes locale URLs on the client). export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js'; diff --git a/dist/exports/client.js.map b/dist/exports/client.js.map index a579617..eff1202 100644 --- a/dist/exports/client.js.map +++ b/dist/exports/client.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"} \ No newline at end of file +{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","useContactForm","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index f68ddd3..9f8c445 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -24,6 +24,7 @@ export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefiniti export type { LocaleMiddlewareResult } from './modules/i18n/index.js'; export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'; export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'; +export { resolveLocalized } from './modules/i18n/index.js'; export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'; export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage, } from './modules/notifications/index.js'; export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'; diff --git a/dist/index.js b/dist/index.js index 471a6a1..fcaa37e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -15,6 +15,7 @@ export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueR export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js'; export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'; export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'; +export { resolveLocalized } from './modules/i18n/index.js'; export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'; export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js'; export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'; diff --git a/dist/index.js.map b/dist/index.js.map index ff4d44b..b26d3a0 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport {\n A11Y_COOKIE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n DEFAULT_CONSENT,\n getConsentTexts,\n parseConsent,\n REJECT_ALL_CONSENT,\n serializeConsent,\n setDefaultConsent,\n updateConsent,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\nexport type {\n ContentCollectionOption,\n ContentOption,\n ResolvedRoute,\n} from './modules/content/index.js'\nexport {\n archiveFieldName,\n buildArchivePath,\n buildEntryPath,\n getArchiveEntries,\n parsePageParam,\n resolveRoute,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport type {\n FormsCollectionOverrides,\n FormsFieldsOverride,\n FormsOption,\n} from './modules/forms/types.js'\nexport { createContentHelpers } from './modules/frontend/index.js'\nexport {\n buildPreventDeleteSystemPage,\n buildRevalidateHook,\n buildValidateUniqueRole,\n setPublishedAtHook,\n trackSlugHistoryHook,\n} from './modules/hooks/index.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'\nexport {\n getNotificationTexts,\n NOTIFICATION_FALLBACK,\n resolveFormMessage,\n} from './modules/notifications/index.js'\nexport type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteIntegrations,\n getSiteSettings,\n SITE_INTEGRATIONS_SLUG,\n SITE_SETTINGS_SLUG,\n} from './modules/payload/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\n\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'\nexport type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'\nexport { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'\nexport {\n buildAutoFillMetaHook,\n buildRobots,\n buildSitemapEntries,\n createMetadataGenerator,\n createPageMetadata,\n injectAutoFillMeta,\n} from './modules/seo/index.js'\nexport {\n createLlmsTxtRoute,\n createManifestHandler,\n createSitemapRouteHandler,\n} from './modules/seo/index.js'\nexport {\n buildIconsMetadata,\n buildOrganizationJsonLd,\n validateFaviconField,\n} from './modules/seo/index.js'\nexport {\n buildBreadcrumbJsonLd,\n buildSiteNavigationJsonLd,\n buildWebSiteJsonLd,\n} from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport {\n buildFaqJsonLd,\n buildLocalBusinessJsonLd,\n buildServiceJsonLd,\n} from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml } from './modules/seo/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\n"],"names":["adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y","getAnalyticsConfig","ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","DEFAULT_CONSENT","getConsentTexts","parseConsent","REJECT_ALL_CONSENT","serializeConsent","setDefaultConsent","updateConsent","archiveFieldName","buildArchivePath","buildEntryPath","getArchiveEntries","parsePageParam","resolveRoute","graphAdapter","mailAdapter","panelSmtpAdapter","buildFormsPlugin","createContentHelpers","buildPreventDeleteSystemPage","buildRevalidateHook","buildValidateUniqueRole","setPublishedAtHook","trackSlugHistoryHook","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildWebSiteJsonLd","buildFaqJsonLd","buildLocalBusinessJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildSlugField","toSlug","buildR2Storage","ipalKit"],"mappings":"AACA,SACEA,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,QACT,4BAA2B;AAClC,SACEC,WAAW,EACXC,YAAY,EACZC,cAAc,EACdC,SAAS,EACTC,aAAa,QACR,mCAAkC;AAGzC,SAASC,kBAAkB,QAAQ,+BAA8B;AACjE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,QACR,6BAA4B;AAOnC,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,cAAc,EACdC,iBAAiB,EACjBC,cAAc,EACdC,YAAY,QACP,6BAA4B;AAEnC,SAASC,YAAY,QAAQ,kCAAiC;AAE9D,SAASC,WAAW,QAAQ,iCAAgC;AAE5D,4EAA4E;AAC5E,gFAAgF;AAChF,gFAAgF;AAChF,SAASC,gBAAgB,QAAQ,sCAAqC;AAEtE,SAASC,gBAAgB,QAAQ,uCAAsC;AAMvE,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SACEC,4BAA4B,EAC5BC,mBAAmB,EACnBC,uBAAuB,EACvBC,kBAAkB,EAClBC,oBAAoB,QACf,2BAA0B;AAEjC,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,cAAc,EACdC,mBAAmB,EACnBC,iBAAiB,EACjBC,aAAa,EACbC,kBAAkB,EAClBC,mBAAmB,EACnBC,eAAe,EACfC,gBAAgB,QACX,0BAAyB;AAEhC,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,0BAAyB;AAC5F,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,0BAAyB;AAC5E,SAASC,iBAAiB,EAAEC,qBAAqB,QAAQ,2BAA0B;AACnF,SACEC,oBAAoB,EACpBC,qBAAqB,EACrBC,kBAAkB,QACb,mCAAkC;AAGzC,SAASC,qBAAqB,EAAEC,iBAAiB,QAAQ,2BAA0B;AAEnF,SACEC,SAAS,EACTC,mBAAmB,EACnBC,eAAe,EACfC,sBAAsB,EACtBC,kBAAkB,QACb,6BAA4B;AACnC,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SAASC,QAAQ,QAAQ,8BAA6B;AAKtD,SAASC,uBAAuB,EAAEC,aAAa,EAAEC,YAAY,QAAQ,yBAAwB;AAE7F,SACEC,qBAAqB,EACrBC,WAAW,EACXC,mBAAmB,EACnBC,uBAAuB,EACvBC,kBAAkB,EAClBC,kBAAkB,QACb,yBAAwB;AAC/B,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,yBAAyB,QACpB,yBAAwB;AAC/B,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,oBAAoB,QACf,yBAAwB;AAC/B,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,kBAAkB,QACb,yBAAwB;AAC/B,qFAAqF;AACrF,SACEC,cAAc,EACdC,wBAAwB,EACxBC,kBAAkB,QACb,yBAAwB;AAC/B,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,cAAc,EAAEC,MAAM,QAAQ,0BAAyB;AAChE,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,OAAO,QAAQ,cAAa"} \ No newline at end of file +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport {\n A11Y_COOKIE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n DEFAULT_CONSENT,\n getConsentTexts,\n parseConsent,\n REJECT_ALL_CONSENT,\n serializeConsent,\n setDefaultConsent,\n updateConsent,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\nexport type {\n ContentCollectionOption,\n ContentOption,\n ResolvedRoute,\n} from './modules/content/index.js'\nexport {\n archiveFieldName,\n buildArchivePath,\n buildEntryPath,\n getArchiveEntries,\n parsePageParam,\n resolveRoute,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport type {\n FormsCollectionOverrides,\n FormsFieldsOverride,\n FormsOption,\n} from './modules/forms/types.js'\nexport { createContentHelpers } from './modules/frontend/index.js'\nexport {\n buildPreventDeleteSystemPage,\n buildRevalidateHook,\n buildValidateUniqueRole,\n setPublishedAtHook,\n trackSlugHistoryHook,\n} from './modules/hooks/index.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\nexport { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'\nexport {\n getNotificationTexts,\n NOTIFICATION_FALLBACK,\n resolveFormMessage,\n} from './modules/notifications/index.js'\nexport type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteIntegrations,\n getSiteSettings,\n SITE_INTEGRATIONS_SLUG,\n SITE_SETTINGS_SLUG,\n} from './modules/payload/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\n\nexport { buildCsp } from './modules/security/index.js'\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'\nexport type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'\nexport { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'\nexport {\n buildAutoFillMetaHook,\n buildRobots,\n buildSitemapEntries,\n createMetadataGenerator,\n createPageMetadata,\n injectAutoFillMeta,\n} from './modules/seo/index.js'\nexport {\n createLlmsTxtRoute,\n createManifestHandler,\n createSitemapRouteHandler,\n} from './modules/seo/index.js'\nexport {\n buildIconsMetadata,\n buildOrganizationJsonLd,\n validateFaviconField,\n} from './modules/seo/index.js'\nexport {\n buildBreadcrumbJsonLd,\n buildSiteNavigationJsonLd,\n buildWebSiteJsonLd,\n} from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport {\n buildFaqJsonLd,\n buildLocalBusinessJsonLd,\n buildServiceJsonLd,\n} from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml } from './modules/seo/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\n"],"names":["adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y","getAnalyticsConfig","ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","DEFAULT_CONSENT","getConsentTexts","parseConsent","REJECT_ALL_CONSENT","serializeConsent","setDefaultConsent","updateConsent","archiveFieldName","buildArchivePath","buildEntryPath","getArchiveEntries","parsePageParam","resolveRoute","graphAdapter","mailAdapter","panelSmtpAdapter","buildFormsPlugin","createContentHelpers","buildPreventDeleteSystemPage","buildRevalidateHook","buildValidateUniqueRole","setPublishedAtHook","trackSlugHistoryHook","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildWebSiteJsonLd","buildFaqJsonLd","buildLocalBusinessJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildSlugField","toSlug","buildR2Storage","ipalKit"],"mappings":"AACA,SACEA,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,QACT,4BAA2B;AAClC,SACEC,WAAW,EACXC,YAAY,EACZC,cAAc,EACdC,SAAS,EACTC,aAAa,QACR,mCAAkC;AAGzC,SAASC,kBAAkB,QAAQ,+BAA8B;AACjE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,QACR,6BAA4B;AAOnC,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,cAAc,EACdC,iBAAiB,EACjBC,cAAc,EACdC,YAAY,QACP,6BAA4B;AAEnC,SAASC,YAAY,QAAQ,kCAAiC;AAE9D,SAASC,WAAW,QAAQ,iCAAgC;AAE5D,4EAA4E;AAC5E,gFAAgF;AAChF,gFAAgF;AAChF,SAASC,gBAAgB,QAAQ,sCAAqC;AAEtE,SAASC,gBAAgB,QAAQ,uCAAsC;AAMvE,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SACEC,4BAA4B,EAC5BC,mBAAmB,EACnBC,uBAAuB,EACvBC,kBAAkB,EAClBC,oBAAoB,QACf,2BAA0B;AAEjC,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,cAAc,EACdC,mBAAmB,EACnBC,iBAAiB,EACjBC,aAAa,EACbC,kBAAkB,EAClBC,mBAAmB,EACnBC,eAAe,EACfC,gBAAgB,QACX,0BAAyB;AAEhC,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,0BAAyB;AAC5F,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,0BAAyB;AAC5E,SAASC,gBAAgB,QAAQ,0BAAyB;AAC1D,SAASC,iBAAiB,EAAEC,qBAAqB,QAAQ,2BAA0B;AACnF,SACEC,oBAAoB,EACpBC,qBAAqB,EACrBC,kBAAkB,QACb,mCAAkC;AAGzC,SAASC,qBAAqB,EAAEC,iBAAiB,QAAQ,2BAA0B;AAEnF,SACEC,SAAS,EACTC,mBAAmB,EACnBC,eAAe,EACfC,sBAAsB,EACtBC,kBAAkB,QACb,6BAA4B;AACnC,SAASC,oBAAoB,QAAQ,8BAA6B;AAElE,SAASC,QAAQ,QAAQ,8BAA6B;AAItD,SAASC,uBAAuB,EAAEC,aAAa,EAAEC,YAAY,QAAQ,yBAAwB;AAE7F,SACEC,qBAAqB,EACrBC,WAAW,EACXC,mBAAmB,EACnBC,uBAAuB,EACvBC,kBAAkB,EAClBC,kBAAkB,QACb,yBAAwB;AAC/B,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,yBAAyB,QACpB,yBAAwB;AAC/B,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,oBAAoB,QACf,yBAAwB;AAC/B,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,kBAAkB,QACb,yBAAwB;AAC/B,qFAAqF;AACrF,SACEC,cAAc,EACdC,wBAAwB,EACxBC,kBAAkB,QACb,yBAAwB;AAC/B,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,cAAc,EAAEC,MAAM,QAAQ,0BAAyB;AAChE,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,OAAO,QAAQ,cAAa"} \ No newline at end of file diff --git a/dist/modules/forms/index.d.ts b/dist/modules/forms/index.d.ts index ace80ae..7b94fbf 100644 --- a/dist/modules/forms/index.d.ts +++ b/dist/modules/forms/index.d.ts @@ -4,5 +4,7 @@ export type { RateLimitArgs } from './rateLimit.js'; export { submitForm } from './submitForm.js'; export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'; export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'; +export { useContactForm } from './useContactForm.js'; +export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'; export { validateSubmission } from './validateSubmission.js'; export type { FormValidationResult } from './validateSubmission.js'; diff --git a/dist/modules/forms/index.js b/dist/modules/forms/index.js index 384833d..0b05c07 100644 --- a/dist/modules/forms/index.js +++ b/dist/modules/forms/index.js @@ -3,6 +3,7 @@ export { buildFormsPlugin } from './formsPluginConfig.js'; export { checkRateLimit } from './rateLimit.js'; export { submitForm } from './submitForm.js'; +export { useContactForm } from './useContactForm.js'; export { validateSubmission } from './validateSubmission.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/forms/index.js.map b/dist/modules/forms/index.js.map index 00c6df4..5951c1b 100644 --- a/dist/modules/forms/index.js.map +++ b/dist/modules/forms/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,kBAAkB,QAAQ,0BAAyB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,SAASC,kBAAkB,QAAQ,0BAAyB"} \ No newline at end of file diff --git a/dist/modules/forms/useContactForm.d.ts b/dist/modules/forms/useContactForm.d.ts new file mode 100644 index 0000000..43c0a2b --- /dev/null +++ b/dist/modules/forms/useContactForm.d.ts @@ -0,0 +1,64 @@ +import type { SubmitFormResult } from './submitForm.js'; +/** Field values the form tracks. Projects add/remove keys freely. */ +export type ContactFormValues = { + consent: boolean; + email: string; + message: string; + name: string; + phone: string; + topic: string; +}; +export type ContactFormErrors = Partial>; +/** + * The project's server action that calls submitForm (server-only, holds the + * Turnstile secret). The hook is a client hook, so it can't call submitForm + * directly — the project injects its action. + */ +export type SubmitAction = (values: ContactFormValues, turnstileToken?: string) => Promise<{ + message?: string; + success: boolean; +} | SubmitFormResult>; +type UseContactFormOptions = { + /** Generic error message shown when the action throws. */ + errorFallback?: string; + initialTopic?: string; + /** Minimum message length. Default 10. */ + minMessageLength?: number; + /** Whether consent is required (project passes true when consentText shown). */ + requireConsent?: boolean; + /** Whether a topic must be chosen (project passes this when topics exist). */ + requireTopic?: boolean; + /** Require a Turnstile token before submit (when the widget is shown). */ + requireTurnstile?: boolean; + submitAction: SubmitAction; +}; +/** + * All contact-form logic (state, validation, Turnstile token, submit, success) + * WITHOUT any markup — the project owns 100% of the look. Replaces the ~150 + * lines of identical logic copied into every project's ContactForm, while the + * project keeps full control over field layout and styling. + * + * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey), + * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) }) + * // in JSX — your own fields/classes: + * f.setField('name', e.target.value)} + * className={f.errors.name ? 'border-red-500' : '…'} /> + * + *
…
+ * {f.isSuccess && } + */ +export declare function useContactForm(options: UseContactFormOptions): { + errorMessage: string | null; + errors: Partial>; + handleSubmit: (e: { + preventDefault: () => void; + }) => Promise; + isSubmitting: boolean; + isSuccess: boolean; + reset: () => void; + setField: (key: K, value: ContactFormValues[K]) => void; + setTurnstileToken: import("react").Dispatch>; + turnstileToken: string | null; + values: ContactFormValues; +}; +export {}; diff --git a/dist/modules/forms/useContactForm.js b/dist/modules/forms/useContactForm.js new file mode 100644 index 0000000..4c9c7d3 --- /dev/null +++ b/dist/modules/forms/useContactForm.js @@ -0,0 +1,126 @@ +'use client'; +import { useCallback, useState } from 'react'; +const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/; +const EMPTY = { + name: '', + consent: false, + email: '', + message: '', + phone: '', + topic: '' +}; +/** + * All contact-form logic (state, validation, Turnstile token, submit, success) + * WITHOUT any markup — the project owns 100% of the look. Replaces the ~150 + * lines of identical logic copied into every project's ContactForm, while the + * project keeps full control over field layout and styling. + * + * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey), + * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) }) + * // in JSX — your own fields/classes: + * f.setField('name', e.target.value)} + * className={f.errors.name ? 'border-red-500' : '…'} /> + * + *
…
+ * {f.isSuccess && } + */ export function useContactForm(options) { + const { errorFallback = 'Something went wrong. Please try again.', initialTopic = '', minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options; + const [values, setValues] = useState({ + ...EMPTY, + topic: initialTopic + }); + const [errors, setErrors] = useState({}); + const [isSubmitting, setIsSubmitting] = useState(false); + const [isSuccess, setIsSuccess] = useState(false); + const [errorMessage, setErrorMessage] = useState(null); + const [turnstileToken, setTurnstileToken] = useState(null); + const setField = useCallback((key, value)=>{ + setValues((prev)=>({ + ...prev, + [key]: value + })); + }, []); + const validate = useCallback(()=>{ + const errs = {}; + if (!values.name.trim()) { + errs.name = true; + } + if (!values.email.trim() || !EMAIL_RE.test(values.email)) { + errs.email = true; + } + if (requireTopic && !values.topic) { + errs.topic = true; + } + if (!values.message.trim() || values.message.length < minMessageLength) { + errs.message = true; + } + if (requireConsent && !values.consent) { + errs.consent = true; + } + setErrors(errs); + return Object.keys(errs).length === 0; + }, [ + values, + requireTopic, + requireConsent, + minMessageLength + ]); + const handleSubmit = useCallback(async (e)=>{ + e.preventDefault(); + setErrorMessage(null); + if (!validate()) { + return; + } + if (requireTurnstile && !turnstileToken) { + setErrorMessage(errorFallback); + return; + } + setIsSubmitting(true); + try { + const result = await submitAction(values, turnstileToken ?? undefined); + if (result.success) { + setIsSuccess(true); + setTurnstileToken(null); + } else { + setErrorMessage('message' in result && result.message || errorFallback); + } + } catch (err) { + setErrorMessage(err instanceof Error ? err.message : errorFallback); + } finally{ + setIsSubmitting(false); + } + }, [ + validate, + requireTurnstile, + turnstileToken, + submitAction, + values, + errorFallback + ]); + const reset = useCallback(()=>{ + setValues({ + ...EMPTY, + topic: initialTopic + }); + setErrors({}); + setIsSuccess(false); + setErrorMessage(null); + setTurnstileToken(null); + }, [ + initialTopic + ]); + return { + errorMessage, + errors, + handleSubmit, + isSubmitting, + isSuccess, + reset, + setField, + setTurnstileToken, + turnstileToken, + values + }; +} + +//# sourceMappingURL=useContactForm.js.map \ No newline at end of file diff --git a/dist/modules/forms/useContactForm.js.map b/dist/modules/forms/useContactForm.js.map new file mode 100644 index 0000000..1133c21 --- /dev/null +++ b/dist/modules/forms/useContactForm.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/forms/useContactForm.ts"],"sourcesContent":["'use client'\n\nimport { useCallback, useState } from 'react'\n\nimport type { SubmitFormResult } from './submitForm.js'\n\n/** Field values the form tracks. Projects add/remove keys freely. */\nexport type ContactFormValues = {\n consent: boolean\n email: string\n message: string\n name: string\n phone: string\n topic: string\n}\n\nexport type ContactFormErrors = Partial>\n\n/**\n * The project's server action that calls submitForm (server-only, holds the\n * Turnstile secret). The hook is a client hook, so it can't call submitForm\n * directly — the project injects its action.\n */\nexport type SubmitAction = (\n values: ContactFormValues,\n turnstileToken?: string,\n) => Promise<{ message?: string; success: boolean } | SubmitFormResult>\n\ntype UseContactFormOptions = {\n /** Generic error message shown when the action throws. */\n errorFallback?: string\n initialTopic?: string\n /** Minimum message length. Default 10. */\n minMessageLength?: number\n /** Whether consent is required (project passes true when consentText shown). */\n requireConsent?: boolean\n /** Whether a topic must be chosen (project passes this when topics exist). */\n requireTopic?: boolean\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n submitAction: SubmitAction\n}\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@][^\\s.@]*\\.[^\\s@]+$/\nconst EMPTY: ContactFormValues = {\n name: '',\n consent: false,\n email: '',\n message: '',\n phone: '',\n topic: '',\n}\n\n/**\n * All contact-form logic (state, validation, Turnstile token, submit, success)\n * WITHOUT any markup — the project owns 100% of the look. Replaces the ~150\n * lines of identical logic copied into every project's ContactForm, while the\n * project keeps full control over field layout and styling.\n *\n * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),\n * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })\n * // in JSX — your own fields/classes:\n * f.setField('name', e.target.value)}\n * className={f.errors.name ? 'border-red-500' : '…'} />\n * \n *
…
\n * {f.isSuccess && }\n */\nexport function useContactForm(options: UseContactFormOptions) {\n const {\n errorFallback = 'Something went wrong. Please try again.',\n initialTopic = '',\n minMessageLength = 10,\n requireConsent = false,\n requireTopic = false,\n requireTurnstile = false,\n submitAction,\n } = options\n\n const [values, setValues] = useState({ ...EMPTY, topic: initialTopic })\n const [errors, setErrors] = useState({})\n const [isSubmitting, setIsSubmitting] = useState(false)\n const [isSuccess, setIsSuccess] = useState(false)\n const [errorMessage, setErrorMessage] = useState(null)\n const [turnstileToken, setTurnstileToken] = useState(null)\n\n const setField = useCallback(\n (key: K, value: ContactFormValues[K]) => {\n setValues((prev) => ({ ...prev, [key]: value }))\n },\n [],\n )\n\n const validate = useCallback((): boolean => {\n const errs: ContactFormErrors = {}\n if (!values.name.trim()) {errs.name = true}\n if (!values.email.trim() || !EMAIL_RE.test(values.email)) {errs.email = true}\n if (requireTopic && !values.topic) {errs.topic = true}\n if (!values.message.trim() || values.message.length < minMessageLength) {errs.message = true}\n if (requireConsent && !values.consent) {errs.consent = true}\n setErrors(errs)\n return Object.keys(errs).length === 0\n }, [values, requireTopic, requireConsent, minMessageLength])\n\n const handleSubmit = useCallback(\n async (e: { preventDefault: () => void }) => {\n e.preventDefault()\n setErrorMessage(null)\n if (!validate()) {return}\n if (requireTurnstile && !turnstileToken) {\n setErrorMessage(errorFallback)\n return\n }\n setIsSubmitting(true)\n try {\n const result = await submitAction(values, turnstileToken ?? undefined)\n if (result.success) {\n setIsSuccess(true)\n setTurnstileToken(null)\n } else {\n setErrorMessage(('message' in result && result.message) || errorFallback)\n }\n } catch (err) {\n setErrorMessage(err instanceof Error ? err.message : errorFallback)\n } finally {\n setIsSubmitting(false)\n }\n },\n [validate, requireTurnstile, turnstileToken, submitAction, values, errorFallback],\n )\n\n const reset = useCallback(() => {\n setValues({ ...EMPTY, topic: initialTopic })\n setErrors({})\n setIsSuccess(false)\n setErrorMessage(null)\n setTurnstileToken(null)\n }, [initialTopic])\n\n return {\n errorMessage,\n errors,\n handleSubmit,\n isSubmitting,\n isSuccess,\n reset,\n setField,\n setTurnstileToken,\n turnstileToken,\n values,\n }\n}\n"],"names":["useCallback","useState","EMAIL_RE","EMPTY","name","consent","email","message","phone","topic","useContactForm","options","errorFallback","initialTopic","minMessageLength","requireConsent","requireTopic","requireTurnstile","submitAction","values","setValues","errors","setErrors","isSubmitting","setIsSubmitting","isSuccess","setIsSuccess","errorMessage","setErrorMessage","turnstileToken","setTurnstileToken","setField","key","value","prev","validate","errs","trim","test","length","Object","keys","handleSubmit","e","preventDefault","result","undefined","success","err","Error","reset"],"mappings":"AAAA;AAEA,SAASA,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAyC7C,MAAMC,WAAW;AACjB,MAAMC,QAA2B;IAC/BC,MAAM;IACNC,SAAS;IACTC,OAAO;IACPC,SAAS;IACTC,OAAO;IACPC,OAAO;AACT;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,eAAeC,OAA8B;IAC3D,MAAM,EACJC,gBAAgB,yCAAyC,EACzDC,eAAe,EAAE,EACjBC,mBAAmB,EAAE,EACrBC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACpBC,mBAAmB,KAAK,EACxBC,YAAY,EACb,GAAGP;IAEJ,MAAM,CAACQ,QAAQC,UAAU,GAAGnB,SAA4B;QAAE,GAAGE,KAAK;QAAEM,OAAOI;IAAa;IACxF,MAAM,CAACQ,QAAQC,UAAU,GAAGrB,SAA4B,CAAC;IACzD,MAAM,CAACsB,cAAcC,gBAAgB,GAAGvB,SAAS;IACjD,MAAM,CAACwB,WAAWC,aAAa,GAAGzB,SAAS;IAC3C,MAAM,CAAC0B,cAAcC,gBAAgB,GAAG3B,SAAwB;IAChE,MAAM,CAAC4B,gBAAgBC,kBAAkB,GAAG7B,SAAwB;IAEpE,MAAM8B,WAAW/B,YACf,CAAoCgC,KAAQC;QAC1Cb,UAAU,CAACc,OAAU,CAAA;gBAAE,GAAGA,IAAI;gBAAE,CAACF,IAAI,EAAEC;YAAM,CAAA;IAC/C,GACA,EAAE;IAGJ,MAAME,WAAWnC,YAAY;QAC3B,MAAMoC,OAA0B,CAAC;QACjC,IAAI,CAACjB,OAAOf,IAAI,CAACiC,IAAI,IAAI;YAACD,KAAKhC,IAAI,GAAG;QAAI;QAC1C,IAAI,CAACe,OAAOb,KAAK,CAAC+B,IAAI,MAAM,CAACnC,SAASoC,IAAI,CAACnB,OAAOb,KAAK,GAAG;YAAC8B,KAAK9B,KAAK,GAAG;QAAI;QAC5E,IAAIU,gBAAgB,CAACG,OAAOV,KAAK,EAAE;YAAC2B,KAAK3B,KAAK,GAAG;QAAI;QACrD,IAAI,CAACU,OAAOZ,OAAO,CAAC8B,IAAI,MAAMlB,OAAOZ,OAAO,CAACgC,MAAM,GAAGzB,kBAAkB;YAACsB,KAAK7B,OAAO,GAAG;QAAI;QAC5F,IAAIQ,kBAAkB,CAACI,OAAOd,OAAO,EAAE;YAAC+B,KAAK/B,OAAO,GAAG;QAAI;QAC3DiB,UAAUc;QACV,OAAOI,OAAOC,IAAI,CAACL,MAAMG,MAAM,KAAK;IACtC,GAAG;QAACpB;QAAQH;QAAcD;QAAgBD;KAAiB;IAE3D,MAAM4B,eAAe1C,YACnB,OAAO2C;QACLA,EAAEC,cAAc;QAChBhB,gBAAgB;QAChB,IAAI,CAACO,YAAY;YAAC;QAAM;QACxB,IAAIlB,oBAAoB,CAACY,gBAAgB;YACvCD,gBAAgBhB;YAChB;QACF;QACAY,gBAAgB;QAChB,IAAI;YACF,MAAMqB,SAAS,MAAM3B,aAAaC,QAAQU,kBAAkBiB;YAC5D,IAAID,OAAOE,OAAO,EAAE;gBAClBrB,aAAa;gBACbI,kBAAkB;YACpB,OAAO;gBACLF,gBAAgB,AAAC,aAAaiB,UAAUA,OAAOtC,OAAO,IAAKK;YAC7D;QACF,EAAE,OAAOoC,KAAK;YACZpB,gBAAgBoB,eAAeC,QAAQD,IAAIzC,OAAO,GAAGK;QACvD,SAAU;YACRY,gBAAgB;QAClB;IACF,GACA;QAACW;QAAUlB;QAAkBY;QAAgBX;QAAcC;QAAQP;KAAc;IAGnF,MAAMsC,QAAQlD,YAAY;QACxBoB,UAAU;YAAE,GAAGjB,KAAK;YAAEM,OAAOI;QAAa;QAC1CS,UAAU,CAAC;QACXI,aAAa;QACbE,gBAAgB;QAChBE,kBAAkB;IACpB,GAAG;QAACjB;KAAa;IAEjB,OAAO;QACLc;QACAN;QACAqB;QACAnB;QACAE;QACAyB;QACAnB;QACAD;QACAD;QACAV;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/i18n/index.d.ts b/dist/modules/i18n/index.d.ts index 68f97ca..eee5ea5 100644 --- a/dist/modules/i18n/index.d.ts +++ b/dist/modules/i18n/index.d.ts @@ -12,5 +12,6 @@ export { buildLocalizationConfig } from './localizationConfig.js'; export { buildLocalizedPath, switchLocalePath } from './localizedPath.js'; export type { LocalizedSlugs } from './localizedPath.js'; export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'; +export { resolveLocalized } from './resolveLocalized.js'; export type { I18nConfig, LocaleDefinition } from './types.js'; export { validateI18nConfig } from './validation.js'; diff --git a/dist/modules/i18n/index.js b/dist/modules/i18n/index.js index b9f6ef6..3441690 100644 --- a/dist/modules/i18n/index.js +++ b/dist/modules/i18n/index.js @@ -8,6 +8,7 @@ export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMidd export { buildLocalizationConfig } from './localizationConfig.js'; export { buildLocalizedPath, switchLocalePath } from './localizedPath.js'; export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'; +export { resolveLocalized } from './resolveLocalized.js'; export { validateI18nConfig } from './validation.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/i18n/index.js.map b/dist/modules/i18n/index.js.map index 1a83f85..7878742 100644 --- a/dist/modules/i18n/index.js.map +++ b/dist/modules/i18n/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n} from './AlternateLinksContext.js'\nexport type { AlternateLinks } from './AlternateLinksContext.js'\nexport { AlternateLinksUpdater } from './AlternateLinksUpdater.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { LanguageSwitcher } from './LanguageSwitcher.js'\nexport type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","LanguageSwitcher","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","validateI18nConfig"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,QACf,6BAA4B;AAEnC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAE/F,SAASC,kBAAkB,QAAQ,kBAAiB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n} from './AlternateLinksContext.js'\nexport type { AlternateLinks } from './AlternateLinksContext.js'\nexport { AlternateLinksUpdater } from './AlternateLinksUpdater.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { LanguageSwitcher } from './LanguageSwitcher.js'\nexport type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport { resolveLocalized } from './resolveLocalized.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","LanguageSwitcher","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","resolveLocalized","validateI18nConfig"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,QACf,6BAA4B;AAEnC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAC/F,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,kBAAkB,QAAQ,kBAAiB"} \ No newline at end of file diff --git a/dist/modules/i18n/resolveLocalized.d.ts b/dist/modules/i18n/resolveLocalized.d.ts new file mode 100644 index 0000000..2871f0b --- /dev/null +++ b/dist/modules/i18n/resolveLocalized.d.ts @@ -0,0 +1,13 @@ +/** + * Resolves a possibly-localized value to a string for the given locale. + * Payload returns a localized field as a plain string (current locale) OR, with + * locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles + * both, with a safe fallback to the first available value — replacing the + * hand-rolled `getSafeString` with `any` copied into every project (JSON-LD, + * rich text, form topics, …). + * + * import { resolveLocalized } from '@intecion/ipal-kit' + * const name = resolveLocalized(item.label, locale) // '' if nothing + * const city = resolveLocalized(company.city, locale, '—') // custom fallback + */ +export declare function resolveLocalized(value: unknown, locale: string, fallback?: string): string; diff --git a/dist/modules/i18n/resolveLocalized.js b/dist/modules/i18n/resolveLocalized.js new file mode 100644 index 0000000..03d540d --- /dev/null +++ b/dist/modules/i18n/resolveLocalized.js @@ -0,0 +1,31 @@ +/** + * Resolves a possibly-localized value to a string for the given locale. + * Payload returns a localized field as a plain string (current locale) OR, with + * locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles + * both, with a safe fallback to the first available value — replacing the + * hand-rolled `getSafeString` with `any` copied into every project (JSON-LD, + * rich text, form topics, …). + * + * import { resolveLocalized } from '@intecion/ipal-kit' + * const name = resolveLocalized(item.label, locale) // '' if nothing + * const city = resolveLocalized(company.city, locale, '—') // custom fallback + */ export function resolveLocalized(value, locale, fallback = '') { + if (value == null) { + return fallback; + } + if (typeof value === 'string') { + return value; + } + if (typeof value === 'object') { + const map = value; + const forLocale = map[locale]; + if (typeof forLocale === 'string') { + return forLocale; + } + const first = Object.values(map).find((v)=>typeof v === 'string'); + return first ?? fallback; + } + return String(value); +} + +//# sourceMappingURL=resolveLocalized.js.map \ No newline at end of file diff --git a/dist/modules/i18n/resolveLocalized.js.map b/dist/modules/i18n/resolveLocalized.js.map new file mode 100644 index 0000000..b1ad257 --- /dev/null +++ b/dist/modules/i18n/resolveLocalized.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/i18n/resolveLocalized.ts"],"sourcesContent":["/**\n * Resolves a possibly-localized value to a string for the given locale.\n * Payload returns a localized field as a plain string (current locale) OR, with\n * locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles\n * both, with a safe fallback to the first available value — replacing the\n * hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,\n * rich text, form topics, …).\n *\n * import { resolveLocalized } from '@intecion/ipal-kit'\n * const name = resolveLocalized(item.label, locale) // '' if nothing\n * const city = resolveLocalized(company.city, locale, '—') // custom fallback\n */\nexport function resolveLocalized(value: unknown, locale: string, fallback = ''): string {\n if (value == null) {return fallback}\n if (typeof value === 'string') {return value}\n if (typeof value === 'object') {\n const map = value as Record\n const forLocale = map[locale]\n if (typeof forLocale === 'string') {return forLocale}\n const first = Object.values(map).find((v) => typeof v === 'string')\n return (first) ?? fallback\n }\n return String(value)\n}\n"],"names":["resolveLocalized","value","locale","fallback","map","forLocale","first","Object","values","find","v","String"],"mappings":"AAAA;;;;;;;;;;;CAWC,GACD,OAAO,SAASA,iBAAiBC,KAAc,EAAEC,MAAc,EAAEC,WAAW,EAAE;IAC5E,IAAIF,SAAS,MAAM;QAAC,OAAOE;IAAQ;IACnC,IAAI,OAAOF,UAAU,UAAU;QAAC,OAAOA;IAAK;IAC5C,IAAI,OAAOA,UAAU,UAAU;QAC7B,MAAMG,MAAMH;QACZ,MAAMI,YAAYD,GAAG,CAACF,OAAO;QAC7B,IAAI,OAAOG,cAAc,UAAU;YAAC,OAAOA;QAAS;QACpD,MAAMC,QAAQC,OAAOC,MAAM,CAACJ,KAAKK,IAAI,CAAC,CAACC,IAAM,OAAOA,MAAM;QAC1D,OAAO,AAACJ,SAAUH;IACpB;IACA,OAAOQ,OAAOV;AAChB"} \ No newline at end of file diff --git a/src/exports/client.ts b/src/exports/client.ts index 1ac082f..2f9ac0a 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -24,6 +24,12 @@ export { } from '../modules/consent/client.js' export type { CookieBannerClassNames } from '../modules/consent/client.js' +export { useContactForm } from '../modules/forms/useContactForm.js' +export type { + ContactFormErrors, + ContactFormValues, + SubmitAction, +} from '../modules/forms/useContactForm.js' // Pure i18n path helpers — no server/RSC deps, safe to import in client // components (e.g. a LanguageSwitcher that computes locale URLs on the client). export { diff --git a/src/index.ts b/src/index.ts index 479d2a3..29a2d91 100644 --- a/src/index.ts +++ b/src/index.ts @@ -91,6 +91,7 @@ export { export type { LocaleMiddlewareResult } from './modules/i18n/index.js' export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js' export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js' +export { resolveLocalized } from './modules/i18n/index.js' export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js' export { getNotificationTexts, @@ -109,8 +110,8 @@ export { SITE_SETTINGS_SLUG, } from './modules/payload/index.js' export { buildSecurityHeaders } from './modules/security/index.js' -export { buildCsp } from './modules/security/index.js' +export { buildCsp } from './modules/security/index.js' export type { BuildCspArgs } from './modules/security/index.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js' diff --git a/src/modules/forms/index.ts b/src/modules/forms/index.ts index 984e590..31f8326 100644 --- a/src/modules/forms/index.ts +++ b/src/modules/forms/index.ts @@ -6,5 +6,7 @@ export type { RateLimitArgs } from './rateLimit.js' export { submitForm } from './submitForm.js' export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js' export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js' +export { useContactForm } from './useContactForm.js' +export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js' export { validateSubmission } from './validateSubmission.js' export type { FormValidationResult } from './validateSubmission.js' diff --git a/src/modules/forms/useContactForm.ts b/src/modules/forms/useContactForm.ts new file mode 100644 index 0000000..dec75ee --- /dev/null +++ b/src/modules/forms/useContactForm.ts @@ -0,0 +1,152 @@ +'use client' + +import { useCallback, useState } from 'react' + +import type { SubmitFormResult } from './submitForm.js' + +/** Field values the form tracks. Projects add/remove keys freely. */ +export type ContactFormValues = { + consent: boolean + email: string + message: string + name: string + phone: string + topic: string +} + +export type ContactFormErrors = Partial> + +/** + * The project's server action that calls submitForm (server-only, holds the + * Turnstile secret). The hook is a client hook, so it can't call submitForm + * directly — the project injects its action. + */ +export type SubmitAction = ( + values: ContactFormValues, + turnstileToken?: string, +) => Promise<{ message?: string; success: boolean } | SubmitFormResult> + +type UseContactFormOptions = { + /** Generic error message shown when the action throws. */ + errorFallback?: string + initialTopic?: string + /** Minimum message length. Default 10. */ + minMessageLength?: number + /** Whether consent is required (project passes true when consentText shown). */ + requireConsent?: boolean + /** Whether a topic must be chosen (project passes this when topics exist). */ + requireTopic?: boolean + /** Require a Turnstile token before submit (when the widget is shown). */ + requireTurnstile?: boolean + submitAction: SubmitAction +} + +const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/ +const EMPTY: ContactFormValues = { + name: '', + consent: false, + email: '', + message: '', + phone: '', + topic: '', +} + +/** + * All contact-form logic (state, validation, Turnstile token, submit, success) + * WITHOUT any markup — the project owns 100% of the look. Replaces the ~150 + * lines of identical logic copied into every project's ContactForm, while the + * project keeps full control over field layout and styling. + * + * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey), + * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) }) + * // in JSX — your own fields/classes: + * f.setField('name', e.target.value)} + * className={f.errors.name ? 'border-red-500' : '…'} /> + * + *
…
+ * {f.isSuccess && } + */ +export function useContactForm(options: UseContactFormOptions) { + const { + errorFallback = 'Something went wrong. Please try again.', + initialTopic = '', + minMessageLength = 10, + requireConsent = false, + requireTopic = false, + requireTurnstile = false, + submitAction, + } = options + + const [values, setValues] = useState({ ...EMPTY, topic: initialTopic }) + const [errors, setErrors] = useState({}) + const [isSubmitting, setIsSubmitting] = useState(false) + const [isSuccess, setIsSuccess] = useState(false) + const [errorMessage, setErrorMessage] = useState(null) + const [turnstileToken, setTurnstileToken] = useState(null) + + const setField = useCallback( + (key: K, value: ContactFormValues[K]) => { + setValues((prev) => ({ ...prev, [key]: value })) + }, + [], + ) + + const validate = useCallback((): boolean => { + const errs: ContactFormErrors = {} + if (!values.name.trim()) {errs.name = true} + if (!values.email.trim() || !EMAIL_RE.test(values.email)) {errs.email = true} + if (requireTopic && !values.topic) {errs.topic = true} + if (!values.message.trim() || values.message.length < minMessageLength) {errs.message = true} + if (requireConsent && !values.consent) {errs.consent = true} + setErrors(errs) + return Object.keys(errs).length === 0 + }, [values, requireTopic, requireConsent, minMessageLength]) + + const handleSubmit = useCallback( + async (e: { preventDefault: () => void }) => { + e.preventDefault() + setErrorMessage(null) + if (!validate()) {return} + if (requireTurnstile && !turnstileToken) { + setErrorMessage(errorFallback) + return + } + setIsSubmitting(true) + try { + const result = await submitAction(values, turnstileToken ?? undefined) + if (result.success) { + setIsSuccess(true) + setTurnstileToken(null) + } else { + setErrorMessage(('message' in result && result.message) || errorFallback) + } + } catch (err) { + setErrorMessage(err instanceof Error ? err.message : errorFallback) + } finally { + setIsSubmitting(false) + } + }, + [validate, requireTurnstile, turnstileToken, submitAction, values, errorFallback], + ) + + const reset = useCallback(() => { + setValues({ ...EMPTY, topic: initialTopic }) + setErrors({}) + setIsSuccess(false) + setErrorMessage(null) + setTurnstileToken(null) + }, [initialTopic]) + + return { + errorMessage, + errors, + handleSubmit, + isSubmitting, + isSuccess, + reset, + setField, + setTurnstileToken, + turnstileToken, + values, + } +} diff --git a/src/modules/i18n/index.ts b/src/modules/i18n/index.ts index 14120ea..f0436d6 100644 --- a/src/modules/i18n/index.ts +++ b/src/modules/i18n/index.ts @@ -16,5 +16,6 @@ export { buildLocalizationConfig } from './localizationConfig.js' export { buildLocalizedPath, switchLocalePath } from './localizedPath.js' export type { LocalizedSlugs } from './localizedPath.js' export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js' +export { resolveLocalized } from './resolveLocalized.js' export type { I18nConfig, LocaleDefinition } from './types.js' export { validateI18nConfig } from './validation.js' diff --git a/src/modules/i18n/resolveLocalized.ts b/src/modules/i18n/resolveLocalized.ts new file mode 100644 index 0000000..4006299 --- /dev/null +++ b/src/modules/i18n/resolveLocalized.ts @@ -0,0 +1,24 @@ +/** + * Resolves a possibly-localized value to a string for the given locale. + * Payload returns a localized field as a plain string (current locale) OR, with + * locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles + * both, with a safe fallback to the first available value — replacing the + * hand-rolled `getSafeString` with `any` copied into every project (JSON-LD, + * rich text, form topics, …). + * + * import { resolveLocalized } from '@intecion/ipal-kit' + * const name = resolveLocalized(item.label, locale) // '' if nothing + * const city = resolveLocalized(company.city, locale, '—') // custom fallback + */ +export function resolveLocalized(value: unknown, locale: string, fallback = ''): string { + if (value == null) {return fallback} + if (typeof value === 'string') {return value} + if (typeof value === 'object') { + const map = value as Record + const forLocale = map[locale] + if (typeof forLocale === 'string') {return forLocale} + const first = Object.values(map).find((v) => typeof v === 'string') + return (first) ?? fallback + } + return String(value) +}