diff --git a/dist/exports/client.d.ts b/dist/exports/client.d.ts index de31c6d..2aae0c9 100644 --- a/dist/exports/client.d.ts +++ b/dist/exports/client.d.ts @@ -14,6 +14,10 @@ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentCont 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 { useForm } from '../modules/forms/useForm.js'; +export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'; +export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from '../modules/forms/validators.js'; +export type { Rule } from '../modules/forms/validators.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 82f06ea..14346b7 100644 --- a/dist/exports/client.js +++ b/dist/exports/client.js @@ -11,6 +11,8 @@ export { Analytics } from '../modules/analytics/client.js'; * client-only code. */ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js'; export { useContactForm } from '../modules/forms/useContactForm.js'; +export { useForm } from '../modules/forms/useForm.js'; +export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from '../modules/forms/validators.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 eff1202..b5245bd 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'\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 +{"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'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.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","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","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,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,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 9f8c445..e2e8d72 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -17,6 +17,9 @@ export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'; export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'; export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'; export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption, } from './modules/forms/types.js'; +export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'; +export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './modules/forms/validators.js'; +export type { Rule } from './modules/forms/validators.js'; export { createContentHelpers } from './modules/frontend/index.js'; export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js'; export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'; diff --git a/dist/index.js b/dist/index.js index fcaa37e..e071f48 100644 --- a/dist/index.js +++ b/dist/index.js @@ -10,6 +10,10 @@ export { mailAdapter } from './modules/email/mailAdapter.js'; // Payload loads the config (or runs generate:importmap) as a plain Node script. export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'; export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'; +// Validation rules are pure — exported server-side too, for re-validating a +// submission inside a server action. (useForm/useContactForm are client-only → +// '@intecion/ipal-kit/client'.) +export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './modules/forms/validators.js'; export { createContentHelpers } from './modules/frontend/index.js'; export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js'; export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js'; diff --git a/dist/index.js.map b/dist/index.js.map index b26d3a0..7bbbb36 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 { 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 +{"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 type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './modules/forms/validators.js'\nexport type { Rule } from './modules/forms/validators.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'\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","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","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":"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"} \ No newline at end of file diff --git a/dist/modules/forms/index.d.ts b/dist/modules/forms/index.d.ts index 7b94fbf..eb64d62 100644 --- a/dist/modules/forms/index.d.ts +++ b/dist/modules/forms/index.d.ts @@ -6,5 +6,9 @@ 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 { useForm } from './useForm.js'; +export type { FormErrors, FormSubmitAction, Validator } from './useForm.js'; export { validateSubmission } from './validateSubmission.js'; export type { FormValidationResult } from './validateSubmission.js'; +export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './validators.js'; +export type { Rule } from './validators.js'; diff --git a/dist/modules/forms/index.js b/dist/modules/forms/index.js index 0b05c07..47068a7 100644 --- a/dist/modules/forms/index.js +++ b/dist/modules/forms/index.js @@ -4,6 +4,10 @@ export { buildFormsPlugin } from './formsPluginConfig.js'; export { checkRateLimit } from './rateLimit.js'; export { submitForm } from './submitForm.js'; export { useContactForm } from './useContactForm.js'; +// Generic form engine (any field set) + the standard contact-form preset. +export { useForm } from './useForm.js'; export { validateSubmission } from './validateSubmission.js'; +// Composable validation rules (pure — safe on server or client). +export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './validators.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 5951c1b..341d8c6 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 { 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 +{"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'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"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,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"} \ No newline at end of file diff --git a/dist/modules/forms/useContactForm.d.ts b/dist/modules/forms/useContactForm.d.ts index 43c0a2b..78ef1c3 100644 --- a/dist/modules/forms/useContactForm.d.ts +++ b/dist/modules/forms/useContactForm.d.ts @@ -1,5 +1,9 @@ -import type { SubmitFormResult } from './submitForm.js'; -/** Field values the form tracks. Projects add/remove keys freely. */ +import { type FormSubmitAction } from './useForm.js'; +/** + * Field values of the STANDARD contact form. This is a preset shape — projects + * that need a different field set (or dynamic builder fields) should use + * `useForm` directly instead, where the shape is fully open. + */ export type ContactFormValues = { consent: boolean; email: string; @@ -8,20 +12,14 @@ export type ContactFormValues = { 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>; +export type ContactFormErrors = Partial>; +export type SubmitAction = FormSubmitAction; type UseContactFormOptions = { - /** Generic error message shown when the action throws. */ + /** Generic error message shown when the action fails/throws. */ errorFallback?: string; initialTopic?: string; + /** Override the per-field error message (shown via `errors.`). */ + messages?: Partial>; /** Minimum message length. Default 10. */ minMessageLength?: number; /** Whether consent is required (project passes true when consentText shown). */ @@ -33,32 +31,30 @@ type UseContactFormOptions = { 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. + * Zero-config preset over `useForm` for the everyday contact form: standard + * fields (name/email/phone/topic/message/consent) and standard rules, wired + * for you. Markup and styling stay 100% in the project — this only removes the + * duplicated logic. * * 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 && } + * + * Need custom or dynamic fields? Drop the preset and call `useForm` + validators. */ export declare function useContactForm(options: UseContactFormOptions): { - errorMessage: string | null; - errors: Partial>; - handleSubmit: (e: { - preventDefault: () => void; - }) => Promise; + values: ContactFormValues; + errors: Partial>; isSubmitting: boolean; isSuccess: boolean; - reset: () => void; - setField: (key: K, value: ContactFormValues[K]) => void; - setTurnstileToken: import("react").Dispatch>; + errorMessage: string | null; turnstileToken: string | null; - values: ContactFormValues; + setField: (key: K, value: ContactFormValues[K]) => void; + setValues: import("react").Dispatch>; + setErrors: import("react").Dispatch>>>; + setTurnstileToken: import("react").Dispatch>; + handleSubmit: (e?: { + preventDefault?: (() => void) | undefined; + } | undefined) => Promise; + reset: () => void; }; export {}; diff --git a/dist/modules/forms/useContactForm.js b/dist/modules/forms/useContactForm.js index 4c9c7d3..1a052f2 100644 --- a/dist/modules/forms/useContactForm.js +++ b/dist/modules/forms/useContactForm.js @@ -1,126 +1,61 @@ 'use client'; -import { useCallback, useState } from 'react'; -const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/; -const EMPTY = { - name: '', - consent: false, - email: '', - message: '', - phone: '', - topic: '' -}; +import { useMemo } from 'react'; +import { useForm } from './useForm.js'; +import { buildValidator, checked, email, minLength, required } from './validators.js'; /** - * 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. + * Zero-config preset over `useForm` for the everyday contact form: standard + * fields (name/email/phone/topic/message/consent) and standard rules, wired + * for you. Markup and styling stay 100% in the project — this only removes the + * duplicated logic. * * 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 && } + * + * Need custom or dynamic fields? Drop the preset and call `useForm` + validators. */ 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, + const { errorFallback, initialTopic = '', messages, minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options; + const validate = useMemo(()=>buildValidator({ + name: [ + required(messages?.name) + ], + email: [ + required(messages?.email), + email(messages?.email) + ], + ...requireTopic ? { + topic: [ + required(messages?.topic) + ] + } : {}, + message: [ + required(messages?.message), + minLength(minMessageLength, messages?.message) + ], + ...requireConsent ? { + consent: [ + checked(messages?.consent) + ] + } : {} + }), [ requireTopic, requireConsent, - minMessageLength + minMessageLength, + messages ]); - 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, + return useForm({ + errorFallback, + initialValues: { + name: '', + consent: false, + email: '', + message: '', + phone: '', topic: initialTopic - }); - setErrors({}); - setIsSuccess(false); - setErrorMessage(null); - setTurnstileToken(null); - }, [ - initialTopic - ]); - return { - errorMessage, - errors, - handleSubmit, - isSubmitting, - isSuccess, - reset, - setField, - setTurnstileToken, - turnstileToken, - values - }; + }, + requireTurnstile, + submitAction, + validate + }); } //# 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 index 1133c21..d8cf270 100644 --- a/dist/modules/forms/useContactForm.js.map +++ b/dist/modules/forms/useContactForm.js.map @@ -1 +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 +{"version":3,"sources":["../../../src/modules/forms/useContactForm.ts"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\n\nimport { type FormSubmitAction, useForm } from './useForm.js'\nimport { buildValidator, checked, email, minLength, required } from './validators.js'\n\n/**\n * Field values of the STANDARD contact form. This is a preset shape — projects\n * that need a different field set (or dynamic builder fields) should use\n * `useForm` directly instead, where the shape is fully open.\n */\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>\nexport type SubmitAction = FormSubmitAction\n\ntype UseContactFormOptions = {\n /** Generic error message shown when the action fails/throws. */\n errorFallback?: string\n initialTopic?: string\n /** Override the per-field error message (shown via `errors.`). */\n messages?: Partial>\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\n/**\n * Zero-config preset over `useForm` for the everyday contact form: standard\n * fields (name/email/phone/topic/message/consent) and standard rules, wired\n * for you. Markup and styling stay 100% in the project — this only removes the\n * duplicated logic.\n *\n * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),\n * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })\n *\n * Need custom or dynamic fields? Drop the preset and call `useForm` + validators.\n */\nexport function useContactForm(options: UseContactFormOptions) {\n const {\n errorFallback,\n initialTopic = '',\n messages,\n minMessageLength = 10,\n requireConsent = false,\n requireTopic = false,\n requireTurnstile = false,\n submitAction,\n } = options\n\n const validate = useMemo(\n () =>\n buildValidator({\n name: [required(messages?.name)],\n email: [required(messages?.email), email(messages?.email)],\n ...(requireTopic ? { topic: [required(messages?.topic)] } : {}),\n message: [required(messages?.message), minLength(minMessageLength, messages?.message)],\n ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),\n }),\n [requireTopic, requireConsent, minMessageLength, messages],\n )\n\n return useForm({\n errorFallback,\n initialValues: {\n name: '',\n consent: false,\n email: '',\n message: '',\n phone: '',\n topic: initialTopic,\n },\n requireTurnstile,\n submitAction,\n validate,\n })\n}\n"],"names":["useMemo","useForm","buildValidator","checked","email","minLength","required","useContactForm","options","errorFallback","initialTopic","messages","minMessageLength","requireConsent","requireTopic","requireTurnstile","submitAction","validate","name","topic","message","consent","initialValues","phone"],"mappings":"AAAA;AAEA,SAASA,OAAO,QAAQ,QAAO;AAE/B,SAAgCC,OAAO,QAAQ,eAAc;AAC7D,SAASC,cAAc,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,kBAAiB;AAoCrF;;;;;;;;;;CAUC,GACD,OAAO,SAASC,eAAeC,OAA8B;IAC3D,MAAM,EACJC,aAAa,EACbC,eAAe,EAAE,EACjBC,QAAQ,EACRC,mBAAmB,EAAE,EACrBC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACpBC,mBAAmB,KAAK,EACxBC,YAAY,EACb,GAAGR;IAEJ,MAAMS,WAAWjB,QACf,IACEE,eAAkC;YAChCgB,MAAM;gBAACZ,SAASK,UAAUO;aAAM;YAChCd,OAAO;gBAACE,SAASK,UAAUP;gBAAQA,MAAMO,UAAUP;aAAO;YAC1D,GAAIU,eAAe;gBAAEK,OAAO;oBAACb,SAASK,UAAUQ;iBAAO;YAAC,IAAI,CAAC,CAAC;YAC9DC,SAAS;gBAACd,SAASK,UAAUS;gBAAUf,UAAUO,kBAAkBD,UAAUS;aAAS;YACtF,GAAIP,iBAAiB;gBAAEQ,SAAS;oBAAClB,QAAQQ,UAAUU;iBAAS;YAAC,IAAI,CAAC,CAAC;QACrE,IACF;QAACP;QAAcD;QAAgBD;QAAkBD;KAAS;IAG5D,OAAOV,QAA2B;QAChCQ;QACAa,eAAe;YACbJ,MAAM;YACNG,SAAS;YACTjB,OAAO;YACPgB,SAAS;YACTG,OAAO;YACPJ,OAAOT;QACT;QACAK;QACAC;QACAC;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/forms/useForm.d.ts b/dist/modules/forms/useForm.d.ts new file mode 100644 index 0000000..eec804d --- /dev/null +++ b/dist/modules/forms/useForm.d.ts @@ -0,0 +1,70 @@ +/** + * Error map: a field key → its error message. A field is "in error" iff it has + * a key here, so `errors.email` is both the truthy flag (for a red border) AND + * the message (to display). Empty object = valid. + */ +export type FormErrors = Partial>; +/** + * The project's server action that calls submitForm (server-only, holds the + * Turnstile secret). This hook is a client hook, so it can't call submitForm + * directly — the project injects its action. The result only needs `success` + * plus an optional `message`; richer shapes (SubmitFormResult) satisfy it. + */ +export type FormSubmitAction = (values: T, turnstileToken?: string) => Promise<{ + success: boolean; + message?: string; +}>; +/** Turns the current values into an error map. Empty map = valid. */ +export type Validator = (values: T) => FormErrors; +type UseFormOptions> = { + /** Defines the field set AND the reset state. Any shape you like. */ + initialValues: T; + submitAction: FormSubmitAction; + /** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */ + validate?: Validator; + /** Require a Turnstile token before submit (when the widget is shown). */ + requireTurnstile?: boolean; + /** Generic error message shown when the action fails/throws with no message. */ + errorFallback?: string; + /** Clear a field's error as soon as the user edits it. Default true. */ + clearErrorOnChange?: boolean; +}; +/** + * Fully generic form engine: state, validation, Turnstile token, submit, + * success/error — WITHOUT any markup. The project owns 100% of the look AND + * the field set: there is no baked-in shape here. Replaces the identical + * ~150 lines of form plumbing copied into every project. + * + * The field set comes from `initialValues`; the rules come from `validate` + * (so dynamic/builder-driven forms just build both at runtime). For the + * everyday contact form use the `useContactForm` preset instead — it wires + * the standard fields and rules for you. + * + * const f = useForm({ + * initialValues: { email: '', message: '' }, + * submitAction, // your server action + * validate: buildValidator({ email: [required(), email()], message: [required()] }), + * requireTurnstile: Boolean(siteKey), + * }) + * f.setField('email', e.target.value)} + * className={f.errors.email ? 'border-red-500' : '…'} /> + *
…
+ */ +export declare function useForm>(options: UseFormOptions): { + values: T; + errors: Partial>; + isSubmitting: boolean; + isSuccess: boolean; + errorMessage: string | null; + turnstileToken: string | null; + setField: (key: K, value: T[K]) => void; + setValues: import("react").Dispatch>; + setErrors: import("react").Dispatch>>>; + setTurnstileToken: import("react").Dispatch>; + handleSubmit: (e?: { + preventDefault?: () => void; + }) => Promise; + reset: () => void; +}; +export {}; diff --git a/dist/modules/forms/useForm.js b/dist/modules/forms/useForm.js new file mode 100644 index 0000000..b503015 --- /dev/null +++ b/dist/modules/forms/useForm.js @@ -0,0 +1,122 @@ +'use client'; +import { useState, useCallback, useRef, useMemo } from 'react'; +/** + * Fully generic form engine: state, validation, Turnstile token, submit, + * success/error — WITHOUT any markup. The project owns 100% of the look AND + * the field set: there is no baked-in shape here. Replaces the identical + * ~150 lines of form plumbing copied into every project. + * + * The field set comes from `initialValues`; the rules come from `validate` + * (so dynamic/builder-driven forms just build both at runtime). For the + * everyday contact form use the `useContactForm` preset instead — it wires + * the standard fields and rules for you. + * + * const f = useForm({ + * initialValues: { email: '', message: '' }, + * submitAction, // your server action + * validate: buildValidator({ email: [required(), email()], message: [required()] }), + * requireTurnstile: Boolean(siteKey), + * }) + * f.setField('email', e.target.value)} + * className={f.errors.email ? 'border-red-500' : '…'} /> + *
…
+ */ export function useForm(options) { + const { initialValues, submitAction, validate, requireTurnstile = false, errorFallback = 'Something went wrong. Please try again.', clearErrorOnChange = true } = options; + // Freeze the initial snapshot so `reset` is stable even though callers pass a + // fresh object literal every render. + const initialRef = useRef(initialValues); + const [values, setValues] = useState(initialRef.current); + 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 + })); + if (clearErrorOnChange) { + setErrors((prev)=>{ + if (!prev[key]) return prev; + const next = { + ...prev + }; + delete next[key]; + return next; + }); + } + }, [ + clearErrorOnChange + ]); + // Validate against the LATEST values via a ref, so handleSubmit stays stable + // and never reads a stale snapshot. + const valuesRef = useRef(values); + valuesRef.current = values; + const validateRef = useRef(validate); + validateRef.current = validate; + const handleSubmit = useCallback(async (e)=>{ + e?.preventDefault?.(); + setErrorMessage(null); + const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}; + setErrors(errs); + if (Object.keys(errs).length > 0) return; + if (requireTurnstile && !turnstileToken) { + setErrorMessage(errorFallback); + return; + } + setIsSubmitting(true); + try { + const result = await submitAction(valuesRef.current, turnstileToken ?? undefined); + if (result.success) { + setIsSuccess(true); + setTurnstileToken(null); + } else { + setErrorMessage(result.message || errorFallback); + } + } catch (err) { + setErrorMessage(err instanceof Error ? err.message : errorFallback); + } finally{ + setIsSubmitting(false); + } + }, [ + requireTurnstile, + turnstileToken, + submitAction, + errorFallback + ]); + const reset = useCallback(()=>{ + setValues(initialRef.current); + setErrors({}); + setIsSuccess(false); + setErrorMessage(null); + setTurnstileToken(null); + }, []); + return useMemo(()=>({ + values, + errors, + isSubmitting, + isSuccess, + errorMessage, + turnstileToken, + setField, + setValues, + setErrors, + setTurnstileToken, + handleSubmit, + reset + }), [ + values, + errors, + isSubmitting, + isSuccess, + errorMessage, + turnstileToken, + setField, + handleSubmit, + reset + ]); +} + +//# sourceMappingURL=useForm.js.map \ No newline at end of file diff --git a/dist/modules/forms/useForm.js.map b/dist/modules/forms/useForm.js.map new file mode 100644 index 0000000..1e68aac --- /dev/null +++ b/dist/modules/forms/useForm.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/forms/useForm.ts"],"sourcesContent":["'use client'\n\nimport { useState, useCallback, useRef, useMemo } from 'react'\n\n/**\n * Error map: a field key → its error message. A field is \"in error\" iff it has\n * a key here, so `errors.email` is both the truthy flag (for a red border) AND\n * the message (to display). Empty object = valid.\n */\nexport type FormErrors = Partial>\n\n/**\n * The project's server action that calls submitForm (server-only, holds the\n * Turnstile secret). This hook is a client hook, so it can't call submitForm\n * directly — the project injects its action. The result only needs `success`\n * plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.\n */\nexport type FormSubmitAction = (\n values: T,\n turnstileToken?: string,\n) => Promise<{ success: boolean; message?: string }>\n\n/** Turns the current values into an error map. Empty map = valid. */\nexport type Validator = (values: T) => FormErrors\n\ntype UseFormOptions> = {\n /** Defines the field set AND the reset state. Any shape you like. */\n initialValues: T\n submitAction: FormSubmitAction\n /** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */\n validate?: Validator\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n /** Generic error message shown when the action fails/throws with no message. */\n errorFallback?: string\n /** Clear a field's error as soon as the user edits it. Default true. */\n clearErrorOnChange?: boolean\n}\n\n/**\n * Fully generic form engine: state, validation, Turnstile token, submit,\n * success/error — WITHOUT any markup. The project owns 100% of the look AND\n * the field set: there is no baked-in shape here. Replaces the identical\n * ~150 lines of form plumbing copied into every project.\n *\n * The field set comes from `initialValues`; the rules come from `validate`\n * (so dynamic/builder-driven forms just build both at runtime). For the\n * everyday contact form use the `useContactForm` preset instead — it wires\n * the standard fields and rules for you.\n *\n * const f = useForm({\n * initialValues: { email: '', message: '' },\n * submitAction, // your server action\n * validate: buildValidator({ email: [required(), email()], message: [required()] }),\n * requireTurnstile: Boolean(siteKey),\n * })\n * f.setField('email', e.target.value)}\n * className={f.errors.email ? 'border-red-500' : '…'} />\n *
…
\n */\nexport function useForm>(options: UseFormOptions) {\n const {\n initialValues,\n submitAction,\n validate,\n requireTurnstile = false,\n errorFallback = 'Something went wrong. Please try again.',\n clearErrorOnChange = true,\n } = options\n\n // Freeze the initial snapshot so `reset` is stable even though callers pass a\n // fresh object literal every render.\n const initialRef = useRef(initialValues)\n\n const [values, setValues] = useState(initialRef.current)\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: T[K]) => {\n setValues((prev) => ({ ...prev, [key]: value }))\n if (clearErrorOnChange) {\n setErrors((prev) => {\n if (!prev[key]) return prev\n const next = { ...prev }\n delete next[key]\n return next\n })\n }\n },\n [clearErrorOnChange],\n )\n\n // Validate against the LATEST values via a ref, so handleSubmit stays stable\n // and never reads a stale snapshot.\n const valuesRef = useRef(values)\n valuesRef.current = values\n const validateRef = useRef(validate)\n validateRef.current = validate\n\n const handleSubmit = useCallback(\n async (e?: { preventDefault?: () => void }) => {\n e?.preventDefault?.()\n setErrorMessage(null)\n\n const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}\n setErrors(errs)\n if (Object.keys(errs).length > 0) return\n\n if (requireTurnstile && !turnstileToken) {\n setErrorMessage(errorFallback)\n return\n }\n\n setIsSubmitting(true)\n try {\n const result = await submitAction(valuesRef.current, turnstileToken ?? undefined)\n if (result.success) {\n setIsSuccess(true)\n setTurnstileToken(null)\n } else {\n setErrorMessage(result.message || errorFallback)\n }\n } catch (err) {\n setErrorMessage(err instanceof Error ? err.message : errorFallback)\n } finally {\n setIsSubmitting(false)\n }\n },\n [requireTurnstile, turnstileToken, submitAction, errorFallback],\n )\n\n const reset = useCallback(() => {\n setValues(initialRef.current)\n setErrors({})\n setIsSuccess(false)\n setErrorMessage(null)\n setTurnstileToken(null)\n }, [])\n\n return useMemo(\n () => ({\n values,\n errors,\n isSubmitting,\n isSuccess,\n errorMessage,\n turnstileToken,\n setField,\n setValues,\n setErrors,\n setTurnstileToken,\n handleSubmit,\n reset,\n }),\n [\n values,\n errors,\n isSubmitting,\n isSuccess,\n errorMessage,\n turnstileToken,\n setField,\n handleSubmit,\n reset,\n ],\n )\n}\n"],"names":["useState","useCallback","useRef","useMemo","useForm","options","initialValues","submitAction","validate","requireTurnstile","errorFallback","clearErrorOnChange","initialRef","values","setValues","current","errors","setErrors","isSubmitting","setIsSubmitting","isSuccess","setIsSuccess","errorMessage","setErrorMessage","turnstileToken","setTurnstileToken","setField","key","value","prev","next","valuesRef","validateRef","handleSubmit","e","preventDefault","errs","Object","keys","length","result","undefined","success","message","err","Error","reset"],"mappings":"AAAA;AAEA,SAASA,QAAQ,EAAEC,WAAW,EAAEC,MAAM,EAAEC,OAAO,QAAQ,QAAO;AAqC9D;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,SAASC,QAA2CC,OAA0B;IACnF,MAAM,EACJC,aAAa,EACbC,YAAY,EACZC,QAAQ,EACRC,mBAAmB,KAAK,EACxBC,gBAAgB,yCAAyC,EACzDC,qBAAqB,IAAI,EAC1B,GAAGN;IAEJ,8EAA8E;IAC9E,qCAAqC;IACrC,MAAMO,aAAaV,OAAOI;IAE1B,MAAM,CAACO,QAAQC,UAAU,GAAGd,SAAYY,WAAWG,OAAO;IAC1D,MAAM,CAACC,QAAQC,UAAU,GAAGjB,SAAwB,CAAC;IACrD,MAAM,CAACkB,cAAcC,gBAAgB,GAAGnB,SAAS;IACjD,MAAM,CAACoB,WAAWC,aAAa,GAAGrB,SAAS;IAC3C,MAAM,CAACsB,cAAcC,gBAAgB,GAAGvB,SAAwB;IAChE,MAAM,CAACwB,gBAAgBC,kBAAkB,GAAGzB,SAAwB;IAEpE,MAAM0B,WAAWzB,YACf,CAAoB0B,KAAQC;QAC1Bd,UAAU,CAACe,OAAU,CAAA;gBAAE,GAAGA,IAAI;gBAAE,CAACF,IAAI,EAAEC;YAAM,CAAA;QAC7C,IAAIjB,oBAAoB;YACtBM,UAAU,CAACY;gBACT,IAAI,CAACA,IAAI,CAACF,IAAI,EAAE,OAAOE;gBACvB,MAAMC,OAAO;oBAAE,GAAGD,IAAI;gBAAC;gBACvB,OAAOC,IAAI,CAACH,IAAI;gBAChB,OAAOG;YACT;QACF;IACF,GACA;QAACnB;KAAmB;IAGtB,6EAA6E;IAC7E,oCAAoC;IACpC,MAAMoB,YAAY7B,OAAOW;IACzBkB,UAAUhB,OAAO,GAAGF;IACpB,MAAMmB,cAAc9B,OAAOM;IAC3BwB,YAAYjB,OAAO,GAAGP;IAEtB,MAAMyB,eAAehC,YACnB,OAAOiC;QACLA,GAAGC;QACHZ,gBAAgB;QAEhB,MAAMa,OAAOJ,YAAYjB,OAAO,GAAGiB,YAAYjB,OAAO,CAACgB,UAAUhB,OAAO,IAAI,CAAC;QAC7EE,UAAUmB;QACV,IAAIC,OAAOC,IAAI,CAACF,MAAMG,MAAM,GAAG,GAAG;QAElC,IAAI9B,oBAAoB,CAACe,gBAAgB;YACvCD,gBAAgBb;YAChB;QACF;QAEAS,gBAAgB;QAChB,IAAI;YACF,MAAMqB,SAAS,MAAMjC,aAAawB,UAAUhB,OAAO,EAAES,kBAAkBiB;YACvE,IAAID,OAAOE,OAAO,EAAE;gBAClBrB,aAAa;gBACbI,kBAAkB;YACpB,OAAO;gBACLF,gBAAgBiB,OAAOG,OAAO,IAAIjC;YACpC;QACF,EAAE,OAAOkC,KAAK;YACZrB,gBAAgBqB,eAAeC,QAAQD,IAAID,OAAO,GAAGjC;QACvD,SAAU;YACRS,gBAAgB;QAClB;IACF,GACA;QAACV;QAAkBe;QAAgBjB;QAAcG;KAAc;IAGjE,MAAMoC,QAAQ7C,YAAY;QACxBa,UAAUF,WAAWG,OAAO;QAC5BE,UAAU,CAAC;QACXI,aAAa;QACbE,gBAAgB;QAChBE,kBAAkB;IACpB,GAAG,EAAE;IAEL,OAAOtB,QACL,IAAO,CAAA;YACLU;YACAG;YACAE;YACAE;YACAE;YACAE;YACAE;YACAZ;YACAG;YACAQ;YACAQ;YACAa;QACF,CAAA,GACA;QACEjC;QACAG;QACAE;QACAE;QACAE;QACAE;QACAE;QACAO;QACAa;KACD;AAEL"} \ No newline at end of file diff --git a/dist/modules/forms/validators.d.ts b/dist/modules/forms/validators.d.ts new file mode 100644 index 0000000..d99e0db --- /dev/null +++ b/dist/modules/forms/validators.d.ts @@ -0,0 +1,43 @@ +import type { Validator } from './useForm.js'; +/** + * Composable validation rules + a builder that turns a per-field schema into a + * `Validator`. These are the bits that actually repeat across projects + * (required / email / min-length / checkbox-must-be-true); the field SET and + * the MARKUP stay in the project. + * + * Pure functions, no 'use client' — usable both in the client `useForm` hook + * and server-side (e.g. re-validating inside a server action). + * + * const validate = buildValidator({ + * email: [required(), email()], + * message: [required(), minLength(10)], + * consent: [checked()], + * }) + * + * Dynamic / builder-driven forms build the schema at runtime: + * + * const schema = Object.fromEntries( + * fields.map((f) => [f.name, f.required ? [required()] : []]), + * ) + * const validate = buildValidator(schema) + */ +/** A rule returns `true` when the value is OK, or an error message string. */ +export type Rule = (value: unknown, values: Record) => true | string; +/** Standalone e-mail check, handy outside the rule system too. */ +export declare const isEmail: (v: unknown) => boolean; +/** Non-empty string, non-null, and (for checkboxes) not `false`. */ +export declare const required: (msg?: string) => Rule; +export declare const email: (msg?: string) => Rule; +export declare const minLength: (n: number, msg?: string) => Rule; +export declare const maxLength: (n: number, msg?: string) => Rule; +/** Checkbox must be ticked (true). */ +export declare const checked: (msg?: string) => Rule; +/** Value must match a regex (ignored when empty — pair with `required` to force). */ +export declare const pattern: (re: RegExp, msg?: string) => Rule; +/** Escape hatch: any predicate → rule. */ +export declare const custom: (test: (value: unknown, values: Record) => boolean, msg: string) => Rule; +/** + * Compose a `Validator` from per-field rule lists. First failing rule for a + * field wins. Fields with no rules (or an empty list) are skipped. + */ +export declare function buildValidator>(schema: Partial>): Validator; diff --git a/dist/modules/forms/validators.js b/dist/modules/forms/validators.js new file mode 100644 index 0000000..5f9df6d --- /dev/null +++ b/dist/modules/forms/validators.js @@ -0,0 +1,37 @@ +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +/** Standalone e-mail check, handy outside the rule system too. */ export const isEmail = (v)=>typeof v === 'string' && EMAIL_RE.test(v.trim()); +/** Non-empty string, non-null, and (for checkboxes) not `false`. */ export const required = (msg = 'required')=>(v)=>{ + if (v == null) return msg; + if (typeof v === 'string' && !v.trim()) return msg; + if (v === false) return msg; + return true; + }; +export const email = (msg = 'invalid email')=>(v)=>isEmail(v) ? true : msg; +export const minLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length >= n ? true : msg ?? `min ${n} chars`; +export const maxLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length <= n ? true : msg ?? `max ${n} chars`; +/** Checkbox must be ticked (true). */ export const checked = (msg = 'required')=>(v)=>v === true ? true : msg; +/** Value must match a regex (ignored when empty — pair with `required` to force). */ export const pattern = (re, msg = 'invalid format')=>(v)=>typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg; +/** Escape hatch: any predicate → rule. */ export const custom = (test, msg)=>(v, values)=>test(v, values) ? true : msg; +/** + * Compose a `Validator` from per-field rule lists. First failing rule for a + * field wins. Fields with no rules (or an empty list) are skipped. + */ export function buildValidator(schema) { + return (values)=>{ + const errs = {}; + const all = values; + for(const key in schema){ + const rules = schema[key]; + if (!rules || rules.length === 0) continue; + for (const rule of rules){ + const res = rule(all[key], all); + if (res !== true) { + errs[key] = res; + break; + } + } + } + return errs; + }; +} + +//# sourceMappingURL=validators.js.map \ No newline at end of file diff --git a/dist/modules/forms/validators.js.map b/dist/modules/forms/validators.js.map new file mode 100644 index 0000000..42eddac --- /dev/null +++ b/dist/modules/forms/validators.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/forms/validators.ts"],"sourcesContent":["import type { FormErrors, Validator } from './useForm.js'\n\n/**\n * Composable validation rules + a builder that turns a per-field schema into a\n * `Validator`. These are the bits that actually repeat across projects\n * (required / email / min-length / checkbox-must-be-true); the field SET and\n * the MARKUP stay in the project.\n *\n * Pure functions, no 'use client' — usable both in the client `useForm` hook\n * and server-side (e.g. re-validating inside a server action).\n *\n * const validate = buildValidator({\n * email: [required(), email()],\n * message: [required(), minLength(10)],\n * consent: [checked()],\n * })\n *\n * Dynamic / builder-driven forms build the schema at runtime:\n *\n * const schema = Object.fromEntries(\n * fields.map((f) => [f.name, f.required ? [required()] : []]),\n * )\n * const validate = buildValidator(schema)\n */\n\n/** A rule returns `true` when the value is OK, or an error message string. */\nexport type Rule = (value: unknown, values: Record) => true | string\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** Standalone e-mail check, handy outside the rule system too. */\nexport const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_RE.test(v.trim())\n\n/** Non-empty string, non-null, and (for checkboxes) not `false`. */\nexport const required =\n (msg = 'required'): Rule =>\n (v) => {\n if (v == null) return msg\n if (typeof v === 'string' && !v.trim()) return msg\n if (v === false) return msg\n return true\n }\n\nexport const email =\n (msg = 'invalid email'): Rule =>\n (v) =>\n isEmail(v) ? true : msg\n\nexport const minLength =\n (n: number, msg?: string): Rule =>\n (v) =>\n typeof v === 'string' && v.trim().length >= n ? true : (msg ?? `min ${n} chars`)\n\nexport const maxLength =\n (n: number, msg?: string): Rule =>\n (v) =>\n typeof v === 'string' && v.trim().length <= n ? true : (msg ?? `max ${n} chars`)\n\n/** Checkbox must be ticked (true). */\nexport const checked =\n (msg = 'required'): Rule =>\n (v) =>\n v === true ? true : msg\n\n/** Value must match a regex (ignored when empty — pair with `required` to force). */\nexport const pattern =\n (re: RegExp, msg = 'invalid format'): Rule =>\n (v) =>\n typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg\n\n/** Escape hatch: any predicate → rule. */\nexport const custom =\n (test: (value: unknown, values: Record) => boolean, msg: string): Rule =>\n (v, values) =>\n test(v, values) ? true : msg\n\n/**\n * Compose a `Validator` from per-field rule lists. First failing rule for a\n * field wins. Fields with no rules (or an empty list) are skipped.\n */\nexport function buildValidator>(\n schema: Partial>,\n): Validator {\n return (values) => {\n const errs: FormErrors = {}\n const all = values as Record\n for (const key in schema) {\n const rules = schema[key as keyof T]\n if (!rules || rules.length === 0) continue\n for (const rule of rules) {\n const res = rule(all[key], all)\n if (res !== true) {\n errs[key as keyof T] = res\n break\n }\n }\n }\n return errs\n }\n}\n"],"names":["EMAIL_RE","isEmail","v","test","trim","required","msg","email","minLength","n","length","maxLength","checked","pattern","re","custom","values","buildValidator","schema","errs","all","key","rules","rule","res"],"mappings":"AA4BA,MAAMA,WAAW;AAEjB,gEAAgE,GAChE,OAAO,MAAMC,UAAU,CAACC,IAAwB,OAAOA,MAAM,YAAYF,SAASG,IAAI,CAACD,EAAEE,IAAI,IAAG;AAEhG,kEAAkE,GAClE,OAAO,MAAMC,WACX,CAACC,MAAM,UAAU,GACjB,CAACJ;QACC,IAAIA,KAAK,MAAM,OAAOI;QACtB,IAAI,OAAOJ,MAAM,YAAY,CAACA,EAAEE,IAAI,IAAI,OAAOE;QAC/C,IAAIJ,MAAM,OAAO,OAAOI;QACxB,OAAO;IACT,EAAC;AAEH,OAAO,MAAMC,QACX,CAACD,MAAM,eAAe,GACtB,CAACJ,IACCD,QAAQC,KAAK,OAAOI,IAAG;AAE3B,OAAO,MAAME,YACX,CAACC,GAAWH,MACZ,CAACJ,IACC,OAAOA,MAAM,YAAYA,EAAEE,IAAI,GAAGM,MAAM,IAAID,IAAI,OAAQH,OAAO,CAAC,IAAI,EAAEG,EAAE,MAAM,CAAC,CAAC;AAEpF,OAAO,MAAME,YACX,CAACF,GAAWH,MACZ,CAACJ,IACC,OAAOA,MAAM,YAAYA,EAAEE,IAAI,GAAGM,MAAM,IAAID,IAAI,OAAQH,OAAO,CAAC,IAAI,EAAEG,EAAE,MAAM,CAAC,CAAC;AAEpF,oCAAoC,GACpC,OAAO,MAAMG,UACX,CAACN,MAAM,UAAU,GACjB,CAACJ,IACCA,MAAM,OAAO,OAAOI,IAAG;AAE3B,mFAAmF,GACnF,OAAO,MAAMO,UACX,CAACC,IAAYR,MAAM,gBAAgB,GACnC,CAACJ,IACC,OAAOA,MAAM,YAAYA,EAAEE,IAAI,OAAO,MAAMU,GAAGX,IAAI,CAACD,EAAEE,IAAI,MAAM,OAAOE,IAAG;AAE9E,wCAAwC,GACxC,OAAO,MAAMS,SACX,CAACZ,MAAoEG,MACrE,CAACJ,GAAGc,SACFb,KAAKD,GAAGc,UAAU,OAAOV,IAAG;AAEhC;;;CAGC,GACD,OAAO,SAASW,eACdC,MAAwC;IAExC,OAAO,CAACF;QACN,MAAMG,OAAsB,CAAC;QAC7B,MAAMC,MAAMJ;QACZ,IAAK,MAAMK,OAAOH,OAAQ;YACxB,MAAMI,QAAQJ,MAAM,CAACG,IAAe;YACpC,IAAI,CAACC,SAASA,MAAMZ,MAAM,KAAK,GAAG;YAClC,KAAK,MAAMa,QAAQD,MAAO;gBACxB,MAAME,MAAMD,KAAKH,GAAG,CAACC,IAAI,EAAED;gBAC3B,IAAII,QAAQ,MAAM;oBAChBL,IAAI,CAACE,IAAe,GAAGG;oBACvB;gBACF;YACF;QACF;QACA,OAAOL;IACT;AACF"} \ No newline at end of file diff --git a/src/exports/client.ts b/src/exports/client.ts index 2f9ac0a..afef735 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -30,6 +30,20 @@ export type { ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js' +export { useForm } from '../modules/forms/useForm.js' +export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js' +export { + buildValidator, + checked, + custom, + email, + isEmail, + maxLength, + minLength, + pattern, + required, +} from '../modules/forms/validators.js' +export type { Rule } from '../modules/forms/validators.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 29a2d91..75d8778 100644 --- a/src/index.ts +++ b/src/index.ts @@ -67,6 +67,22 @@ export type { FormsFieldsOverride, FormsOption, } from './modules/forms/types.js' +export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js' +// Validation rules are pure — exported server-side too, for re-validating a +// submission inside a server action. (useForm/useContactForm are client-only → +// '@intecion/ipal-kit/client'.) +export { + buildValidator, + checked, + custom, + email, + isEmail, + maxLength, + minLength, + pattern, + required, +} from './modules/forms/validators.js' +export type { Rule } from './modules/forms/validators.js' export { createContentHelpers } from './modules/frontend/index.js' export { buildPreventDeleteSystemPage, @@ -110,8 +126,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 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 31f8326..20b291f 100644 --- a/src/modules/forms/index.ts +++ b/src/modules/forms/index.ts @@ -8,5 +8,21 @@ 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' +// Generic form engine (any field set) + the standard contact-form preset. +export { useForm } from './useForm.js' +export type { FormErrors, FormSubmitAction, Validator } from './useForm.js' export { validateSubmission } from './validateSubmission.js' export type { FormValidationResult } from './validateSubmission.js' +// Composable validation rules (pure — safe on server or client). +export { + buildValidator, + checked, + custom, + email, + isEmail, + maxLength, + minLength, + pattern, + required, +} from './validators.js' +export type { Rule } from './validators.js' diff --git a/src/modules/forms/useContactForm.ts b/src/modules/forms/useContactForm.ts index dec75ee..43117ff 100644 --- a/src/modules/forms/useContactForm.ts +++ b/src/modules/forms/useContactForm.ts @@ -1,10 +1,15 @@ 'use client' -import { useCallback, useState } from 'react' +import { useMemo } from 'react' -import type { SubmitFormResult } from './submitForm.js' +import { type FormSubmitAction, useForm } from './useForm.js' +import { buildValidator, checked, email, minLength, required } from './validators.js' -/** Field values the form tracks. Projects add/remove keys freely. */ +/** + * Field values of the STANDARD contact form. This is a preset shape — projects + * that need a different field set (or dynamic builder fields) should use + * `useForm` directly instead, where the shape is fully open. + */ export type ContactFormValues = { consent: boolean email: string @@ -14,22 +19,15 @@ export type ContactFormValues = { 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> +export type ContactFormErrors = Partial> +export type SubmitAction = FormSubmitAction type UseContactFormOptions = { - /** Generic error message shown when the action throws. */ + /** Generic error message shown when the action fails/throws. */ errorFallback?: string initialTopic?: string + /** Override the per-field error message (shown via `errors.`). */ + messages?: Partial> /** Minimum message length. Default 10. */ minMessageLength?: number /** Whether consent is required (project passes true when consentText shown). */ @@ -41,35 +39,22 @@ type UseContactFormOptions = { 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. + * Zero-config preset over `useForm` for the everyday contact form: standard + * fields (name/email/phone/topic/message/consent) and standard rules, wired + * for you. Markup and styling stay 100% in the project — this only removes the + * duplicated logic. * * 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 && } + * + * Need custom or dynamic fields? Drop the preset and call `useForm` + validators. */ export function useContactForm(options: UseContactFormOptions) { const { - errorFallback = 'Something went wrong. Please try again.', + errorFallback, initialTopic = '', + messages, minMessageLength = 10, requireConsent = false, requireTopic = false, @@ -77,76 +62,30 @@ export function useContactForm(options: UseContactFormOptions) { 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 = useMemo( + () => + buildValidator({ + name: [required(messages?.name)], + email: [required(messages?.email), email(messages?.email)], + ...(requireTopic ? { topic: [required(messages?.topic)] } : {}), + message: [required(messages?.message), minLength(minMessageLength, messages?.message)], + ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}), + }), + [requireTopic, requireConsent, minMessageLength, messages], ) - 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) - } + return useForm({ + errorFallback, + initialValues: { + name: '', + consent: false, + email: '', + message: '', + phone: '', + topic: initialTopic, }, - [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, - } + requireTurnstile, + submitAction, + validate, + }) } diff --git a/src/modules/forms/useForm.ts b/src/modules/forms/useForm.ts new file mode 100644 index 0000000..e8559a2 --- /dev/null +++ b/src/modules/forms/useForm.ts @@ -0,0 +1,172 @@ +'use client' + +import { useState, useCallback, useRef, useMemo } from 'react' + +/** + * Error map: a field key → its error message. A field is "in error" iff it has + * a key here, so `errors.email` is both the truthy flag (for a red border) AND + * the message (to display). Empty object = valid. + */ +export type FormErrors = Partial> + +/** + * The project's server action that calls submitForm (server-only, holds the + * Turnstile secret). This hook is a client hook, so it can't call submitForm + * directly — the project injects its action. The result only needs `success` + * plus an optional `message`; richer shapes (SubmitFormResult) satisfy it. + */ +export type FormSubmitAction = ( + values: T, + turnstileToken?: string, +) => Promise<{ success: boolean; message?: string }> + +/** Turns the current values into an error map. Empty map = valid. */ +export type Validator = (values: T) => FormErrors + +type UseFormOptions> = { + /** Defines the field set AND the reset state. Any shape you like. */ + initialValues: T + submitAction: FormSubmitAction + /** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */ + validate?: Validator + /** Require a Turnstile token before submit (when the widget is shown). */ + requireTurnstile?: boolean + /** Generic error message shown when the action fails/throws with no message. */ + errorFallback?: string + /** Clear a field's error as soon as the user edits it. Default true. */ + clearErrorOnChange?: boolean +} + +/** + * Fully generic form engine: state, validation, Turnstile token, submit, + * success/error — WITHOUT any markup. The project owns 100% of the look AND + * the field set: there is no baked-in shape here. Replaces the identical + * ~150 lines of form plumbing copied into every project. + * + * The field set comes from `initialValues`; the rules come from `validate` + * (so dynamic/builder-driven forms just build both at runtime). For the + * everyday contact form use the `useContactForm` preset instead — it wires + * the standard fields and rules for you. + * + * const f = useForm({ + * initialValues: { email: '', message: '' }, + * submitAction, // your server action + * validate: buildValidator({ email: [required(), email()], message: [required()] }), + * requireTurnstile: Boolean(siteKey), + * }) + * f.setField('email', e.target.value)} + * className={f.errors.email ? 'border-red-500' : '…'} /> + *
…
+ */ +export function useForm>(options: UseFormOptions) { + const { + initialValues, + submitAction, + validate, + requireTurnstile = false, + errorFallback = 'Something went wrong. Please try again.', + clearErrorOnChange = true, + } = options + + // Freeze the initial snapshot so `reset` is stable even though callers pass a + // fresh object literal every render. + const initialRef = useRef(initialValues) + + const [values, setValues] = useState(initialRef.current) + 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: T[K]) => { + setValues((prev) => ({ ...prev, [key]: value })) + if (clearErrorOnChange) { + setErrors((prev) => { + if (!prev[key]) return prev + const next = { ...prev } + delete next[key] + return next + }) + } + }, + [clearErrorOnChange], + ) + + // Validate against the LATEST values via a ref, so handleSubmit stays stable + // and never reads a stale snapshot. + const valuesRef = useRef(values) + valuesRef.current = values + const validateRef = useRef(validate) + validateRef.current = validate + + const handleSubmit = useCallback( + async (e?: { preventDefault?: () => void }) => { + e?.preventDefault?.() + setErrorMessage(null) + + const errs = validateRef.current ? validateRef.current(valuesRef.current) : {} + setErrors(errs) + if (Object.keys(errs).length > 0) return + + if (requireTurnstile && !turnstileToken) { + setErrorMessage(errorFallback) + return + } + + setIsSubmitting(true) + try { + const result = await submitAction(valuesRef.current, turnstileToken ?? undefined) + if (result.success) { + setIsSuccess(true) + setTurnstileToken(null) + } else { + setErrorMessage(result.message || errorFallback) + } + } catch (err) { + setErrorMessage(err instanceof Error ? err.message : errorFallback) + } finally { + setIsSubmitting(false) + } + }, + [requireTurnstile, turnstileToken, submitAction, errorFallback], + ) + + const reset = useCallback(() => { + setValues(initialRef.current) + setErrors({}) + setIsSuccess(false) + setErrorMessage(null) + setTurnstileToken(null) + }, []) + + return useMemo( + () => ({ + values, + errors, + isSubmitting, + isSuccess, + errorMessage, + turnstileToken, + setField, + setValues, + setErrors, + setTurnstileToken, + handleSubmit, + reset, + }), + [ + values, + errors, + isSubmitting, + isSuccess, + errorMessage, + turnstileToken, + setField, + handleSubmit, + reset, + ], + ) +} diff --git a/src/modules/forms/validators.ts b/src/modules/forms/validators.ts new file mode 100644 index 0000000..115b2a8 --- /dev/null +++ b/src/modules/forms/validators.ts @@ -0,0 +1,100 @@ +import type { FormErrors, Validator } from './useForm.js' + +/** + * Composable validation rules + a builder that turns a per-field schema into a + * `Validator`. These are the bits that actually repeat across projects + * (required / email / min-length / checkbox-must-be-true); the field SET and + * the MARKUP stay in the project. + * + * Pure functions, no 'use client' — usable both in the client `useForm` hook + * and server-side (e.g. re-validating inside a server action). + * + * const validate = buildValidator({ + * email: [required(), email()], + * message: [required(), minLength(10)], + * consent: [checked()], + * }) + * + * Dynamic / builder-driven forms build the schema at runtime: + * + * const schema = Object.fromEntries( + * fields.map((f) => [f.name, f.required ? [required()] : []]), + * ) + * const validate = buildValidator(schema) + */ + +/** A rule returns `true` when the value is OK, or an error message string. */ +export type Rule = (value: unknown, values: Record) => true | string + +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ + +/** Standalone e-mail check, handy outside the rule system too. */ +export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_RE.test(v.trim()) + +/** Non-empty string, non-null, and (for checkboxes) not `false`. */ +export const required = + (msg = 'required'): Rule => + (v) => { + if (v == null) return msg + if (typeof v === 'string' && !v.trim()) return msg + if (v === false) return msg + return true + } + +export const email = + (msg = 'invalid email'): Rule => + (v) => + isEmail(v) ? true : msg + +export const minLength = + (n: number, msg?: string): Rule => + (v) => + typeof v === 'string' && v.trim().length >= n ? true : (msg ?? `min ${n} chars`) + +export const maxLength = + (n: number, msg?: string): Rule => + (v) => + typeof v === 'string' && v.trim().length <= n ? true : (msg ?? `max ${n} chars`) + +/** Checkbox must be ticked (true). */ +export const checked = + (msg = 'required'): Rule => + (v) => + v === true ? true : msg + +/** Value must match a regex (ignored when empty — pair with `required` to force). */ +export const pattern = + (re: RegExp, msg = 'invalid format'): Rule => + (v) => + typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg + +/** Escape hatch: any predicate → rule. */ +export const custom = + (test: (value: unknown, values: Record) => boolean, msg: string): Rule => + (v, values) => + test(v, values) ? true : msg + +/** + * Compose a `Validator` from per-field rule lists. First failing rule for a + * field wins. Fields with no rules (or an empty list) are skipped. + */ +export function buildValidator>( + schema: Partial>, +): Validator { + return (values) => { + const errs: FormErrors = {} + const all = values as Record + for (const key in schema) { + const rules = schema[key as keyof T] + if (!rules || rules.length === 0) continue + for (const rule of rules) { + const res = rule(all[key], all) + if (res !== true) { + errs[key as keyof T] = res + break + } + } + } + return errs + } +}