Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52977e67fc | ||
|
|
b25f221a50 | ||
|
|
f9d3d9ae97 | ||
|
|
962b9cb640 | ||
|
|
9b9bbc1a9f | ||
|
|
abf2e7d40f | ||
|
|
d500d9412f | ||
|
|
d034ddf990 |
Vendored
+6
@@ -12,6 +12,12 @@ export { Analytics } from '../modules/analytics/client.js';
|
||||
*/
|
||||
export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
|
||||
export type { CookieBannerClassNames } from '../modules/consent/client.js';
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||
export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js';
|
||||
export { 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';
|
||||
|
||||
Vendored
+3
@@ -10,6 +10,9 @@ export { Analytics } from '../modules/analytics/client.js';
|
||||
* components. Kept separate from the main entry so server bundles don't pull in
|
||||
* client-only code.
|
||||
*/ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||
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';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
|
||||
{"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"}
|
||||
Vendored
+6
-1
@@ -17,13 +17,17 @@ 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 { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js';
|
||||
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js';
|
||||
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath, } from './modules/i18n/index.js';
|
||||
export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
|
||||
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
|
||||
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
|
||||
export { resolveLocalized } from './modules/i18n/index.js';
|
||||
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
|
||||
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage, } from './modules/notifications/index.js';
|
||||
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js';
|
||||
@@ -41,6 +45,7 @@ export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/i
|
||||
export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta, } from './modules/seo/index.js';
|
||||
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler, } from './modules/seo/index.js';
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField, } from './modules/seo/index.js';
|
||||
export { buildNoindexField } from './modules/seo/index.js';
|
||||
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd, } from './modules/seo/index.js';
|
||||
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd, } from './modules/seo/index.js';
|
||||
export { buildArticleJsonLd } from './modules/seo/index.js';
|
||||
|
||||
Vendored
+7
-1
@@ -10,11 +10,16 @@ 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 { buildCrossLocaleFieldSync, 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';
|
||||
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
|
||||
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
|
||||
export { resolveLocalized } from './modules/i18n/index.js';
|
||||
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
|
||||
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js';
|
||||
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js';
|
||||
@@ -25,6 +30,7 @@ export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/
|
||||
export { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta } from './modules/seo/index.js';
|
||||
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js';
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js';
|
||||
export { buildNoindexField } from './modules/seo/index.js';
|
||||
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js';
|
||||
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
|
||||
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js';
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+6
@@ -4,5 +4,11 @@ export type { RateLimitArgs } from './rateLimit.js';
|
||||
export { submitForm } from './submitForm.js';
|
||||
export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js';
|
||||
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js';
|
||||
export { useContactForm } from './useContactForm.js';
|
||||
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js';
|
||||
export { 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';
|
||||
|
||||
Vendored
+5
@@ -3,6 +3,11 @@
|
||||
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
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,kBAAkB,QAAQ,0BAAyB"}
|
||||
{"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"}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
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;
|
||||
message: string;
|
||||
name: string;
|
||||
phone: string;
|
||||
topic: string;
|
||||
};
|
||||
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>;
|
||||
export type SubmitAction = FormSubmitAction<ContactFormValues>;
|
||||
type UseContactFormOptions = {
|
||||
/** Generic error message shown when the action fails/throws. */
|
||||
errorFallback?: string;
|
||||
initialTopic?: string;
|
||||
/** Override the per-field error message (shown via `errors.<field>`). */
|
||||
messages?: Partial<Record<keyof ContactFormValues, string>>;
|
||||
/** Minimum message length. Default 10. */
|
||||
minMessageLength?: number;
|
||||
/** Whether consent is required (project passes true when consentText shown). */
|
||||
requireConsent?: boolean;
|
||||
/** Whether a topic must be chosen (project passes this when topics exist). */
|
||||
requireTopic?: boolean;
|
||||
/** Require a Turnstile token before submit (when the widget is shown). */
|
||||
requireTurnstile?: boolean;
|
||||
submitAction: SubmitAction;
|
||||
};
|
||||
/**
|
||||
* 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) })
|
||||
*
|
||||
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||
*/
|
||||
export declare function useContactForm(options: UseContactFormOptions): {
|
||||
values: ContactFormValues;
|
||||
errors: Partial<Record<keyof ContactFormValues, string>>;
|
||||
isSubmitting: boolean;
|
||||
isSuccess: boolean;
|
||||
errorMessage: string | null;
|
||||
turnstileToken: string | null;
|
||||
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
|
||||
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
|
||||
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
|
||||
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
||||
handleSubmit: (e?: {
|
||||
preventDefault?: (() => void) | undefined;
|
||||
} | undefined) => Promise<void>;
|
||||
reset: () => void;
|
||||
};
|
||||
export {};
|
||||
Vendored
+61
@@ -0,0 +1,61 @@
|
||||
'use client';
|
||||
import { useMemo } from 'react';
|
||||
import { useForm } from './useForm.js';
|
||||
import { buildValidator, checked, email, minLength, required } from './validators.js';
|
||||
/**
|
||||
* 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) })
|
||||
*
|
||||
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||
*/ export function useContactForm(options) {
|
||||
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,
|
||||
messages
|
||||
]);
|
||||
return useForm({
|
||||
errorFallback,
|
||||
initialValues: {
|
||||
name: '',
|
||||
consent: false,
|
||||
email: '',
|
||||
message: '',
|
||||
phone: '',
|
||||
topic: initialTopic
|
||||
},
|
||||
requireTurnstile,
|
||||
submitAction,
|
||||
validate
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=useContactForm.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"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<Record<keyof ContactFormValues, string>>\nexport type SubmitAction = FormSubmitAction<ContactFormValues>\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.<field>`). */\n messages?: Partial<Record<keyof ContactFormValues, 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\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<ContactFormValues>({\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<ContactFormValues>({\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"}
|
||||
Vendored
+70
@@ -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<T> = Partial<Record<keyof T, string>>;
|
||||
/**
|
||||
* 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<T> = (values: T, turnstileToken?: string) => Promise<{
|
||||
success: boolean;
|
||||
message?: string;
|
||||
}>;
|
||||
/** Turns the current values into an error map. Empty map = valid. */
|
||||
export type Validator<T> = (values: T) => FormErrors<T>;
|
||||
type UseFormOptions<T extends Record<string, unknown>> = {
|
||||
/** Defines the field set AND the reset state. Any shape you like. */
|
||||
initialValues: T;
|
||||
submitAction: FormSubmitAction<T>;
|
||||
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
|
||||
validate?: Validator<T>;
|
||||
/** 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),
|
||||
* })
|
||||
* <input value={f.values.email}
|
||||
* onChange={(e) => f.setField('email', e.target.value)}
|
||||
* className={f.errors.email ? 'border-red-500' : '…'} />
|
||||
* <form onSubmit={f.handleSubmit}>…</form>
|
||||
*/
|
||||
export declare function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>): {
|
||||
values: T;
|
||||
errors: Partial<Record<keyof T, string>>;
|
||||
isSubmitting: boolean;
|
||||
isSuccess: boolean;
|
||||
errorMessage: string | null;
|
||||
turnstileToken: string | null;
|
||||
setField: <K extends keyof T>(key: K, value: T[K]) => void;
|
||||
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
|
||||
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
|
||||
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
||||
handleSubmit: (e?: {
|
||||
preventDefault?: () => void;
|
||||
}) => Promise<void>;
|
||||
reset: () => void;
|
||||
};
|
||||
export {};
|
||||
Vendored
+122
@@ -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),
|
||||
* })
|
||||
* <input value={f.values.email}
|
||||
* onChange={(e) => f.setField('email', e.target.value)}
|
||||
* className={f.errors.email ? 'border-red-500' : '…'} />
|
||||
* <form onSubmit={f.handleSubmit}>…</form>
|
||||
*/ 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
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
import type { Validator } from './useForm.js';
|
||||
/**
|
||||
* Composable validation rules + a builder that turns a per-field schema into a
|
||||
* `Validator<T>`. 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<MyValues>({
|
||||
* 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<string, unknown>) => 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<string, unknown>) => boolean, msg: string) => Rule;
|
||||
/**
|
||||
* Compose a `Validator<T>` 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<T extends Record<string, unknown>>(schema: Partial<Record<keyof T, Rule[]>>): Validator<T>;
|
||||
Vendored
+37
@@ -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<T>` 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
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,63 @@
|
||||
import type { CollectionAfterChangeHook } from 'payload';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
type BuildCrossLocaleFieldSyncArgs = {
|
||||
/**
|
||||
* The localized `blocks`/`array` field whose rows hold the shared fields.
|
||||
* Default 'layout'.
|
||||
*/
|
||||
arrayField?: string;
|
||||
/**
|
||||
* Slug of the collection this hook is attached to — needed to re-read and
|
||||
* update the other locales. (A hook can't discover its own collection.)
|
||||
*/
|
||||
collection: string;
|
||||
config: I18nConfig;
|
||||
/**
|
||||
* Fields WITHIN each row that are conceptually language-independent (a shared
|
||||
* media reference, an icon, a color) and should be propagated from the edited
|
||||
* locale to every other locale — e.g. ['image'] or ['image', 'backgroundImage'].
|
||||
*
|
||||
* Only fields with a value in the source are copied: clearing a field in one
|
||||
* language does NOT wipe it in the others (conservative, matches the hand-
|
||||
* rolled hooks this replaces). Text and other truly-localized fields are never
|
||||
* touched.
|
||||
*/
|
||||
fields: string[];
|
||||
/**
|
||||
* Flag name set on `req` to break the update→afterChange→update loop.
|
||||
* Default '_ipalSyncingCrossLocale'. Override only if two syncs run on one
|
||||
* collection and must not share a guard.
|
||||
*/
|
||||
guardFlag?: string;
|
||||
};
|
||||
/**
|
||||
* Propagates language-independent fields (images, icons…) that live INSIDE a
|
||||
* localized `blocks`/`array` field from the just-edited locale to every other
|
||||
* configured locale.
|
||||
*
|
||||
* Why this exists: Payload localizes an array/blocks field as a whole, so there
|
||||
* is no way to mark a single sub-field (the image) as non-localized — each
|
||||
* locale keeps its own copy of every row, image included. Without this, an
|
||||
* editor who picks images in Polish has to re-pick the SAME images in English,
|
||||
* German, … This hook does that copy automatically.
|
||||
*
|
||||
* A0-safe: the locale list comes from `config`, never a hard-coded array — add
|
||||
* a language in the panel and it's covered with no code change. (The hand-rolled
|
||||
* versions this replaces carried a literal `['pl','en',...]` that silently
|
||||
* dropped any locale not listed.)
|
||||
*
|
||||
* Row matching: by Payload row `id` when the same id exists in both locales
|
||||
* (robust to reordering and to several blocks of the same type); otherwise it
|
||||
* falls back to the positional index, but only when the block types at that
|
||||
* index match — so it never writes an image into a block of a different type.
|
||||
*
|
||||
* // collections/Pages.ts
|
||||
* import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
|
||||
* hooks: {
|
||||
* afterChange: [
|
||||
* buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
|
||||
* ],
|
||||
* }
|
||||
*/
|
||||
export declare function buildCrossLocaleFieldSync(args: BuildCrossLocaleFieldSyncArgs): CollectionAfterChangeHook;
|
||||
export {};
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
import { getLocaleCodes } from '../i18n/index.js';
|
||||
/** Relationship/upload values arrive as an id or a populated object — normalize to the id. */ function toId(value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value === 'string' || typeof value === 'number') {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'object' && 'id' in value) {
|
||||
const id = value.id;
|
||||
return typeof id === 'string' || typeof id === 'number' ? id : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Propagates language-independent fields (images, icons…) that live INSIDE a
|
||||
* localized `blocks`/`array` field from the just-edited locale to every other
|
||||
* configured locale.
|
||||
*
|
||||
* Why this exists: Payload localizes an array/blocks field as a whole, so there
|
||||
* is no way to mark a single sub-field (the image) as non-localized — each
|
||||
* locale keeps its own copy of every row, image included. Without this, an
|
||||
* editor who picks images in Polish has to re-pick the SAME images in English,
|
||||
* German, … This hook does that copy automatically.
|
||||
*
|
||||
* A0-safe: the locale list comes from `config`, never a hard-coded array — add
|
||||
* a language in the panel and it's covered with no code change. (The hand-rolled
|
||||
* versions this replaces carried a literal `['pl','en',...]` that silently
|
||||
* dropped any locale not listed.)
|
||||
*
|
||||
* Row matching: by Payload row `id` when the same id exists in both locales
|
||||
* (robust to reordering and to several blocks of the same type); otherwise it
|
||||
* falls back to the positional index, but only when the block types at that
|
||||
* index match — so it never writes an image into a block of a different type.
|
||||
*
|
||||
* // collections/Pages.ts
|
||||
* import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
|
||||
* hooks: {
|
||||
* afterChange: [
|
||||
* buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
|
||||
* ],
|
||||
* }
|
||||
*/ export function buildCrossLocaleFieldSync(args) {
|
||||
const { arrayField = 'layout', collection, config, fields, guardFlag = '_ipalSyncingCrossLocale' } = args;
|
||||
return async ({ doc, req })=>{
|
||||
const reqAny = req;
|
||||
// Re-entry guard: our own payload.update() below re-fires afterChange.
|
||||
if (reqAny[guardFlag] || !doc?.id) {
|
||||
return doc;
|
||||
}
|
||||
const sourceRows = doc[arrayField];
|
||||
if (!Array.isArray(sourceRows) || sourceRows.length === 0) {
|
||||
return doc;
|
||||
}
|
||||
// Source locale = the locale being written. Fall back to the configured
|
||||
// default rather than a hard-coded 'pl' when req.locale is absent.
|
||||
const sourceLocale = typeof req.locale === 'string' ? req.locale : config.defaultLocale;
|
||||
const otherLocales = getLocaleCodes(config).filter((l)=>l !== sourceLocale);
|
||||
if (otherLocales.length === 0) {
|
||||
return doc;
|
||||
} // single-locale site: nothing to sync
|
||||
const payload = req.payload;
|
||||
reqAny[guardFlag] = true;
|
||||
try {
|
||||
for (const locale of otherLocales){
|
||||
let targetDoc;
|
||||
try {
|
||||
targetDoc = await payload.findByID({
|
||||
id: doc.id,
|
||||
collection: collection,
|
||||
depth: 0,
|
||||
locale: locale
|
||||
});
|
||||
} catch {
|
||||
continue; // locale not yet created for this doc — nothing to sync into
|
||||
}
|
||||
const targetRows = targetDoc[arrayField];
|
||||
if (!Array.isArray(targetRows) || targetRows.length === 0) {
|
||||
continue;
|
||||
}
|
||||
// id → row index, for robust matching across locales.
|
||||
const byId = new Map();
|
||||
targetRows.forEach((row, i)=>{
|
||||
if (row?.id != null) {
|
||||
byId.set(row.id, i);
|
||||
}
|
||||
});
|
||||
let changed = false;
|
||||
sourceRows.forEach((sourceRow, idx)=>{
|
||||
if (!sourceRow) {
|
||||
return;
|
||||
}
|
||||
// Match by id first; else positional index, but only if block types agree.
|
||||
let targetRow;
|
||||
if (sourceRow.id != null && byId.has(sourceRow.id)) {
|
||||
targetRow = targetRows[byId.get(sourceRow.id)];
|
||||
} else {
|
||||
const candidate = targetRows[idx];
|
||||
if (candidate && candidate.blockType === sourceRow.blockType) {
|
||||
targetRow = candidate;
|
||||
}
|
||||
}
|
||||
if (!targetRow) {
|
||||
return;
|
||||
}
|
||||
for (const field of fields){
|
||||
const sourceId = toId(sourceRow[field]);
|
||||
if (sourceId == null) {
|
||||
continue;
|
||||
} // don't propagate a cleared field
|
||||
if (toId(targetRow[field]) !== sourceId) {
|
||||
targetRow[field] = sourceId;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
if (changed) {
|
||||
await payload.update({
|
||||
id: doc.id,
|
||||
collection: collection,
|
||||
data: {
|
||||
[arrayField]: targetRows
|
||||
},
|
||||
locale: locale,
|
||||
req
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
payload.logger?.error?.({
|
||||
err,
|
||||
msg: `[ipal] cross-locale ${arrayField} sync failed`
|
||||
});
|
||||
} finally{
|
||||
reqAny[guardFlag] = false;
|
||||
}
|
||||
return doc;
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=buildCrossLocaleFieldSync.js.map
|
||||
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -1,5 +1,6 @@
|
||||
export { normalizeFilenameHook } from '../media/index.js';
|
||||
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js';
|
||||
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js';
|
||||
export { buildRevalidateHook } from './buildRevalidateHook.js';
|
||||
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js';
|
||||
export { setPublishedAtHook } from './setPublishedAt.js';
|
||||
|
||||
Vendored
+1
@@ -2,6 +2,7 @@
|
||||
// żeby był jeden katalog "wszystkie hooki pluginu"). Źródło prawdy to ich moduły.
|
||||
export { normalizeFilenameHook } from '../media/index.js';
|
||||
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js';
|
||||
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js';
|
||||
export { buildRevalidateHook } from './buildRevalidateHook.js';
|
||||
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js';
|
||||
export { setPublishedAtHook } from './setPublishedAt.js';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/hooks/index.ts"],"sourcesContent":["// Re-eksport hooków domenowych (mieszkają w swoich modułach, tu dla przeglądu —\n// żeby był jeden katalog \"wszystkie hooki pluginu\"). Źródło prawdy to ich moduły.\nexport { normalizeFilenameHook } from '../media/index.js'\nexport { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'\nexport { buildRevalidateHook } from './buildRevalidateHook.js'\nexport { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'\nexport { setPublishedAtHook } from './setPublishedAt.js'\n\nexport { trackSlugHistoryHook } from './trackSlugHistory.js'\nexport { buildValidateUniqueRole } from './validateUniqueRole.js'\n"],"names":["normalizeFilenameHook","buildAutoFillMetaHook","validateFaviconField","buildRevalidateHook","buildPreventDeleteSystemPage","setPublishedAtHook","trackSlugHistoryHook","buildValidateUniqueRole"],"mappings":"AAAA,gFAAgF;AAChF,kFAAkF;AAClF,SAASA,qBAAqB,QAAQ,oBAAmB;AACzD,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,kBAAiB;AAC7E,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,4BAA4B,QAAQ,+BAA8B;AAC3E,SAASC,kBAAkB,QAAQ,sBAAqB;AAExD,SAASC,oBAAoB,QAAQ,wBAAuB;AAC5D,SAASC,uBAAuB,QAAQ,0BAAyB"}
|
||||
{"version":3,"sources":["../../../src/modules/hooks/index.ts"],"sourcesContent":["// Re-eksport hooków domenowych (mieszkają w swoich modułach, tu dla przeglądu —\n// żeby był jeden katalog \"wszystkie hooki pluginu\"). Źródło prawdy to ich moduły.\nexport { normalizeFilenameHook } from '../media/index.js'\nexport { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'\nexport { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js'\nexport { buildRevalidateHook } from './buildRevalidateHook.js'\nexport { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'\nexport { setPublishedAtHook } from './setPublishedAt.js'\n\nexport { trackSlugHistoryHook } from './trackSlugHistory.js'\nexport { buildValidateUniqueRole } from './validateUniqueRole.js'\n"],"names":["normalizeFilenameHook","buildAutoFillMetaHook","validateFaviconField","buildCrossLocaleFieldSync","buildRevalidateHook","buildPreventDeleteSystemPage","setPublishedAtHook","trackSlugHistoryHook","buildValidateUniqueRole"],"mappings":"AAAA,gFAAgF;AAChF,kFAAkF;AAClF,SAASA,qBAAqB,QAAQ,oBAAmB;AACzD,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,kBAAiB;AAC7E,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,4BAA4B,QAAQ,+BAA8B;AAC3E,SAASC,kBAAkB,QAAQ,sBAAqB;AAExD,SAASC,oBAAoB,QAAQ,wBAAuB;AAC5D,SAASC,uBAAuB,QAAQ,0BAAyB"}
|
||||
Vendored
+1
@@ -12,5 +12,6 @@ export { buildLocalizationConfig } from './localizationConfig.js';
|
||||
export { buildLocalizedPath, switchLocalePath } from './localizedPath.js';
|
||||
export type { LocalizedSlugs } from './localizedPath.js';
|
||||
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js';
|
||||
export { resolveLocalized } from './resolveLocalized.js';
|
||||
export type { I18nConfig, LocaleDefinition } from './types.js';
|
||||
export { validateI18nConfig } from './validation.js';
|
||||
|
||||
Vendored
+1
@@ -8,6 +8,7 @@ export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMidd
|
||||
export { buildLocalizationConfig } from './localizationConfig.js';
|
||||
export { buildLocalizedPath, switchLocalePath } from './localizedPath.js';
|
||||
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js';
|
||||
export { resolveLocalized } from './resolveLocalized.js';
|
||||
export { validateI18nConfig } from './validation.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n} from './AlternateLinksContext.js'\nexport type { AlternateLinks } from './AlternateLinksContext.js'\nexport { AlternateLinksUpdater } from './AlternateLinksUpdater.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { LanguageSwitcher } from './LanguageSwitcher.js'\nexport type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","LanguageSwitcher","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","validateI18nConfig"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,QACf,6BAA4B;AAEnC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAE/F,SAASC,kBAAkB,QAAQ,kBAAiB"}
|
||||
{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n} from './AlternateLinksContext.js'\nexport type { AlternateLinks } from './AlternateLinksContext.js'\nexport { AlternateLinksUpdater } from './AlternateLinksUpdater.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { LanguageSwitcher } from './LanguageSwitcher.js'\nexport type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport { resolveLocalized } from './resolveLocalized.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","LanguageSwitcher","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","resolveLocalized","validateI18nConfig"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,QACf,6BAA4B;AAEnC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAC/F,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,kBAAkB,QAAQ,kBAAiB"}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Resolves a possibly-localized value to a string for the given locale.
|
||||
* Payload returns a localized field as a plain string (current locale) OR, with
|
||||
* locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles
|
||||
* both, with a safe fallback to the first available value — replacing the
|
||||
* hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,
|
||||
* rich text, form topics, …).
|
||||
*
|
||||
* import { resolveLocalized } from '@intecion/ipal-kit'
|
||||
* const name = resolveLocalized(item.label, locale) // '' if nothing
|
||||
* const city = resolveLocalized(company.city, locale, '—') // custom fallback
|
||||
*/
|
||||
export declare function resolveLocalized(value: unknown, locale: string, fallback?: string): string;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Resolves a possibly-localized value to a string for the given locale.
|
||||
* Payload returns a localized field as a plain string (current locale) OR, with
|
||||
* locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles
|
||||
* both, with a safe fallback to the first available value — replacing the
|
||||
* hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,
|
||||
* rich text, form topics, …).
|
||||
*
|
||||
* import { resolveLocalized } from '@intecion/ipal-kit'
|
||||
* const name = resolveLocalized(item.label, locale) // '' if nothing
|
||||
* const city = resolveLocalized(company.city, locale, '—') // custom fallback
|
||||
*/ export function resolveLocalized(value, locale, fallback = '') {
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
const map = value;
|
||||
const forLocale = map[locale];
|
||||
if (typeof forLocale === 'string') {
|
||||
return forLocale;
|
||||
}
|
||||
const first = Object.values(map).find((v)=>typeof v === 'string');
|
||||
return first ?? fallback;
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=resolveLocalized.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/i18n/resolveLocalized.ts"],"sourcesContent":["/**\n * Resolves a possibly-localized value to a string for the given locale.\n * Payload returns a localized field as a plain string (current locale) OR, with\n * locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles\n * both, with a safe fallback to the first available value — replacing the\n * hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,\n * rich text, form topics, …).\n *\n * import { resolveLocalized } from '@intecion/ipal-kit'\n * const name = resolveLocalized(item.label, locale) // '' if nothing\n * const city = resolveLocalized(company.city, locale, '—') // custom fallback\n */\nexport function resolveLocalized(value: unknown, locale: string, fallback = ''): string {\n if (value == null) {return fallback}\n if (typeof value === 'string') {return value}\n if (typeof value === 'object') {\n const map = value as Record<string, unknown>\n const forLocale = map[locale]\n if (typeof forLocale === 'string') {return forLocale}\n const first = Object.values(map).find((v) => typeof v === 'string')\n return (first) ?? fallback\n }\n return String(value)\n}\n"],"names":["resolveLocalized","value","locale","fallback","map","forLocale","first","Object","values","find","v","String"],"mappings":"AAAA;;;;;;;;;;;CAWC,GACD,OAAO,SAASA,iBAAiBC,KAAc,EAAEC,MAAc,EAAEC,WAAW,EAAE;IAC5E,IAAIF,SAAS,MAAM;QAAC,OAAOE;IAAQ;IACnC,IAAI,OAAOF,UAAU,UAAU;QAAC,OAAOA;IAAK;IAC5C,IAAI,OAAOA,UAAU,UAAU;QAC7B,MAAMG,MAAMH;QACZ,MAAMI,YAAYD,GAAG,CAACF,OAAO;QAC7B,IAAI,OAAOG,cAAc,UAAU;YAAC,OAAOA;QAAS;QACpD,MAAMC,QAAQC,OAAOC,MAAM,CAACJ,KAAKK,IAAI,CAAC,CAACC,IAAM,OAAOA,MAAM;QAC1D,OAAO,AAACJ,SAAUH;IACpB;IACA,OAAOQ,OAAOV;AAChB"}
|
||||
Vendored
+9
@@ -24,6 +24,15 @@ type Manifest = {
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* import { i18nConfig } from '@/i18n.config'
|
||||
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
||||
*
|
||||
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
|
||||
* `next build` with no reachable database (the usual Coolify/Docker case) gets
|
||||
* a minimal valid manifest instead of a crash — same contract as
|
||||
* generateStaticParams and the sitemap handler. Projects should still mark the
|
||||
* route dynamic so Next doesn't prerender it at build time:
|
||||
*
|
||||
* // app/manifest.ts
|
||||
* export const dynamic = 'force-dynamic'
|
||||
*/
|
||||
export declare function createManifestHandler(opts: {
|
||||
config: I18nConfig;
|
||||
|
||||
Vendored
+32
-11
@@ -9,22 +9,43 @@ import { getDefaultLocale } from '../i18n/index.js';
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* import { i18nConfig } from '@/i18n.config'
|
||||
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
||||
*
|
||||
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
|
||||
* `next build` with no reachable database (the usual Coolify/Docker case) gets
|
||||
* a minimal valid manifest instead of a crash — same contract as
|
||||
* generateStaticParams and the sitemap handler. Projects should still mark the
|
||||
* route dynamic so Next doesn't prerender it at build time:
|
||||
*
|
||||
* // app/manifest.ts
|
||||
* export const dynamic = 'force-dynamic'
|
||||
*/ export function createManifestHandler(opts) {
|
||||
return async ()=>{
|
||||
const defaultLocale = getDefaultLocale(opts.config);
|
||||
const payload = await opts.getCachedPayload();
|
||||
const settings = await payload.findGlobal({
|
||||
slug: opts.settingsSlug ?? 'site-settings',
|
||||
depth: 1,
|
||||
locale: defaultLocale
|
||||
}).catch(()=>null);
|
||||
const start_url = `/${defaultLocale}`;
|
||||
// Minimal, always-valid manifest. Used both when SiteSettings is empty and
|
||||
// when the database is unreachable during a build.
|
||||
const fallback = {
|
||||
display: 'standalone',
|
||||
icons: [],
|
||||
start_url
|
||||
};
|
||||
let settings;
|
||||
try {
|
||||
// getCachedPayload() ITSELF throws when the DB can't be reached (e.g.
|
||||
// `getaddrinfo ENOTFOUND` during `docker build`), BEFORE findGlobal runs
|
||||
// — so the whole thing, not just the query, must sit inside try/catch.
|
||||
const payload = await opts.getCachedPayload();
|
||||
settings = await payload.findGlobal({
|
||||
slug: opts.settingsSlug ?? 'site-settings',
|
||||
depth: 1,
|
||||
locale: defaultLocale
|
||||
}).catch(()=>null);
|
||||
} catch (err) {
|
||||
console.warn('[ipal] createManifestHandler: database not reachable during build (Docker/CI) — returning minimal manifest; it fills in at runtime:', err);
|
||||
return fallback;
|
||||
}
|
||||
if (!settings) {
|
||||
return {
|
||||
display: 'standalone',
|
||||
icons: [],
|
||||
start_url
|
||||
};
|
||||
return fallback;
|
||||
}
|
||||
const iconSource = settings.favicon ?? settings.logo;
|
||||
const icons = [];
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+34
@@ -0,0 +1,34 @@
|
||||
import type { CheckboxField, Field } from 'payload';
|
||||
type BuildNoindexFieldArgs = {
|
||||
/** Help text under the checkbox. */
|
||||
description?: string;
|
||||
/** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */
|
||||
label?: string;
|
||||
/**
|
||||
* Dotted path, inside the document, that the SEO read path (metadata +
|
||||
* sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.
|
||||
* The checkbox value is mirrored here on every save, so editors toggle one
|
||||
* friendly switch and the machinery reads a stable location.
|
||||
*/
|
||||
metaPath?: string;
|
||||
/** Field name for the editor-facing checkbox. Default 'noindex'. */
|
||||
name?: string;
|
||||
/** Extend/override the generated checkbox (position, access, etc.). */
|
||||
overrides?: Partial<CheckboxField>;
|
||||
};
|
||||
/**
|
||||
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
|
||||
* sitemap and metadata generators actually read). Replaces the hand-rolled
|
||||
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
|
||||
* glue copied into every project — no `any`, one source of truth for editors,
|
||||
* one stable read location for the engine.
|
||||
*
|
||||
* Idempotent and order-independent: if either the checkbox OR an existing
|
||||
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
|
||||
*
|
||||
* // collections/Pages.ts
|
||||
* import { buildNoindexField } from '@intecion/ipal-kit'
|
||||
* fields: [ /* … *\/ buildNoindexField() ],
|
||||
*/
|
||||
export declare function buildNoindexField(args?: BuildNoindexFieldArgs): Field;
|
||||
export {};
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */ function readPath(obj, path) {
|
||||
let cur = obj;
|
||||
for (const key of path){
|
||||
if (cur == null || typeof cur !== 'object') {
|
||||
return undefined;
|
||||
}
|
||||
cur = cur[key];
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
/** Write a dotted path, creating intermediate objects as needed. */ function writePath(obj, path, value) {
|
||||
let cur = obj;
|
||||
for(let i = 0; i < path.length - 1; i++){
|
||||
const key = path[i];
|
||||
const next = cur[key];
|
||||
if (next == null || typeof next !== 'object') {
|
||||
cur[key] = {};
|
||||
}
|
||||
cur = cur[key];
|
||||
}
|
||||
cur[path[path.length - 1]] = value;
|
||||
}
|
||||
/**
|
||||
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
|
||||
* sitemap and metadata generators actually read). Replaces the hand-rolled
|
||||
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
|
||||
* glue copied into every project — no `any`, one source of truth for editors,
|
||||
* one stable read location for the engine.
|
||||
*
|
||||
* Idempotent and order-independent: if either the checkbox OR an existing
|
||||
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
|
||||
*
|
||||
* // collections/Pages.ts
|
||||
* import { buildNoindexField } from '@intecion/ipal-kit'
|
||||
* fields: [ /* … *\/ buildNoindexField() ],
|
||||
*/ export function buildNoindexField(args = {}) {
|
||||
const { name = 'noindex', description = 'Zaznacz, aby wykluczyć tę podstronę z indeksowania (robots: noindex, follow) i z sitemap.xml.', label = 'Wyklucz z indeksowania (noindex)', metaPath = 'meta.noindex', overrides = {} } = args;
|
||||
const segments = metaPath.split('.');
|
||||
const mirror = ({ data, value })=>{
|
||||
const shouldNoindex = Boolean(value ?? readPath(data, segments));
|
||||
if (data && typeof data === 'object') {
|
||||
writePath(data, segments, shouldNoindex);
|
||||
}
|
||||
return shouldNoindex;
|
||||
};
|
||||
const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides;
|
||||
return {
|
||||
name,
|
||||
type: 'checkbox',
|
||||
admin: {
|
||||
description,
|
||||
position: 'sidebar',
|
||||
...adminOverrides
|
||||
},
|
||||
defaultValue: false,
|
||||
hooks: {
|
||||
...hooksOverrides,
|
||||
// mirror runs first, then any project-supplied beforeChange hooks.
|
||||
beforeChange: [
|
||||
mirror,
|
||||
...hooksOverrides?.beforeChange ?? []
|
||||
]
|
||||
},
|
||||
label,
|
||||
...restOverrides
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=buildNoindexField.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -9,6 +9,7 @@ export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
|
||||
export { createManifestHandler } from './buildManifest.js';
|
||||
export { buildMetadata } from './buildMetadata.js';
|
||||
export type { PageMetadata } from './buildMetadata.js';
|
||||
export { buildNoindexField } from './buildNoindexField.js';
|
||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
||||
export { buildRobots } from './buildRobots.js';
|
||||
export type { RobotsRules } from './buildRobots.js';
|
||||
|
||||
Vendored
+1
@@ -7,6 +7,7 @@ export { buildLlmsTxt } from './buildLlmsTxt.js';
|
||||
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js';
|
||||
export { createManifestHandler } from './buildManifest.js';
|
||||
export { buildMetadata } from './buildMetadata.js';
|
||||
export { buildNoindexField } from './buildNoindexField.js';
|
||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
||||
export { buildRobots } from './buildRobots.js';
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
|
||||
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.6.1",
|
||||
"version": "1.6.5",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -24,6 +24,26 @@ export {
|
||||
} from '../modules/consent/client.js'
|
||||
|
||||
export type { CookieBannerClassNames } from '../modules/consent/client.js'
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js'
|
||||
export type {
|
||||
ContactFormErrors,
|
||||
ContactFormValues,
|
||||
SubmitAction,
|
||||
} from '../modules/forms/useContactForm.js'
|
||||
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 {
|
||||
|
||||
@@ -67,8 +67,25 @@ 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 {
|
||||
buildCrossLocaleFieldSync,
|
||||
buildPreventDeleteSystemPage,
|
||||
buildRevalidateHook,
|
||||
buildValidateUniqueRole,
|
||||
@@ -91,6 +108,7 @@ export {
|
||||
export type { LocaleMiddlewareResult } from './modules/i18n/index.js'
|
||||
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'
|
||||
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
|
||||
export { resolveLocalized } from './modules/i18n/index.js'
|
||||
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
|
||||
export {
|
||||
getNotificationTexts,
|
||||
@@ -134,6 +152,7 @@ export {
|
||||
buildOrganizationJsonLd,
|
||||
validateFaviconField,
|
||||
} from './modules/seo/index.js'
|
||||
export { buildNoindexField } from './modules/seo/index.js'
|
||||
export {
|
||||
buildBreadcrumbJsonLd,
|
||||
buildSiteNavigationJsonLd,
|
||||
|
||||
@@ -6,5 +6,23 @@ export type { RateLimitArgs } from './rateLimit.js'
|
||||
export { submitForm } from './submitForm.js'
|
||||
export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'
|
||||
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'
|
||||
export { useContactForm } from './useContactForm.js'
|
||||
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'
|
||||
// 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'
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
|
||||
import { type FormSubmitAction, useForm } from './useForm.js'
|
||||
import { buildValidator, checked, email, minLength, required } from './validators.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
|
||||
message: string
|
||||
name: string
|
||||
phone: string
|
||||
topic: string
|
||||
}
|
||||
|
||||
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>
|
||||
export type SubmitAction = FormSubmitAction<ContactFormValues>
|
||||
|
||||
type UseContactFormOptions = {
|
||||
/** Generic error message shown when the action fails/throws. */
|
||||
errorFallback?: string
|
||||
initialTopic?: string
|
||||
/** Override the per-field error message (shown via `errors.<field>`). */
|
||||
messages?: Partial<Record<keyof ContactFormValues, string>>
|
||||
/** Minimum message length. Default 10. */
|
||||
minMessageLength?: number
|
||||
/** Whether consent is required (project passes true when consentText shown). */
|
||||
requireConsent?: boolean
|
||||
/** Whether a topic must be chosen (project passes this when topics exist). */
|
||||
requireTopic?: boolean
|
||||
/** Require a Turnstile token before submit (when the widget is shown). */
|
||||
requireTurnstile?: boolean
|
||||
submitAction: SubmitAction
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) })
|
||||
*
|
||||
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||
*/
|
||||
export function useContactForm(options: UseContactFormOptions) {
|
||||
const {
|
||||
errorFallback,
|
||||
initialTopic = '',
|
||||
messages,
|
||||
minMessageLength = 10,
|
||||
requireConsent = false,
|
||||
requireTopic = false,
|
||||
requireTurnstile = false,
|
||||
submitAction,
|
||||
} = options
|
||||
|
||||
const validate = useMemo(
|
||||
() =>
|
||||
buildValidator<ContactFormValues>({
|
||||
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],
|
||||
)
|
||||
|
||||
return useForm<ContactFormValues>({
|
||||
errorFallback,
|
||||
initialValues: {
|
||||
name: '',
|
||||
consent: false,
|
||||
email: '',
|
||||
message: '',
|
||||
phone: '',
|
||||
topic: initialTopic,
|
||||
},
|
||||
requireTurnstile,
|
||||
submitAction,
|
||||
validate,
|
||||
})
|
||||
}
|
||||
@@ -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<T> = Partial<Record<keyof T, string>>
|
||||
|
||||
/**
|
||||
* 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<T> = (
|
||||
values: T,
|
||||
turnstileToken?: string,
|
||||
) => Promise<{ success: boolean; message?: string }>
|
||||
|
||||
/** Turns the current values into an error map. Empty map = valid. */
|
||||
export type Validator<T> = (values: T) => FormErrors<T>
|
||||
|
||||
type UseFormOptions<T extends Record<string, unknown>> = {
|
||||
/** Defines the field set AND the reset state. Any shape you like. */
|
||||
initialValues: T
|
||||
submitAction: FormSubmitAction<T>
|
||||
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
|
||||
validate?: Validator<T>
|
||||
/** 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),
|
||||
* })
|
||||
* <input value={f.values.email}
|
||||
* onChange={(e) => f.setField('email', e.target.value)}
|
||||
* className={f.errors.email ? 'border-red-500' : '…'} />
|
||||
* <form onSubmit={f.handleSubmit}>…</form>
|
||||
*/
|
||||
export function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>) {
|
||||
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<T>(initialRef.current)
|
||||
const [errors, setErrors] = useState<FormErrors<T>>({})
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [isSuccess, setIsSuccess] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
const [turnstileToken, setTurnstileToken] = useState<string | null>(null)
|
||||
|
||||
const setField = useCallback(
|
||||
<K extends keyof T>(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,
|
||||
],
|
||||
)
|
||||
}
|
||||
@@ -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<T>`. 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<MyValues>({
|
||||
* 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<string, unknown>) => 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<string, unknown>) => boolean, msg: string): Rule =>
|
||||
(v, values) =>
|
||||
test(v, values) ? true : msg
|
||||
|
||||
/**
|
||||
* Compose a `Validator<T>` 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<T extends Record<string, unknown>>(
|
||||
schema: Partial<Record<keyof T, Rule[]>>,
|
||||
): Validator<T> {
|
||||
return (values) => {
|
||||
const errs: FormErrors<T> = {}
|
||||
const all = values as Record<string, unknown>
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import type { BasePayload, CollectionAfterChangeHook } from 'payload'
|
||||
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { getLocaleCodes } from '../i18n/index.js'
|
||||
|
||||
type Row = { blockType?: string; id?: number | string } & Record<string, unknown>
|
||||
|
||||
type BuildCrossLocaleFieldSyncArgs = {
|
||||
/**
|
||||
* The localized `blocks`/`array` field whose rows hold the shared fields.
|
||||
* Default 'layout'.
|
||||
*/
|
||||
arrayField?: string
|
||||
/**
|
||||
* Slug of the collection this hook is attached to — needed to re-read and
|
||||
* update the other locales. (A hook can't discover its own collection.)
|
||||
*/
|
||||
collection: string
|
||||
config: I18nConfig
|
||||
/**
|
||||
* Fields WITHIN each row that are conceptually language-independent (a shared
|
||||
* media reference, an icon, a color) and should be propagated from the edited
|
||||
* locale to every other locale — e.g. ['image'] or ['image', 'backgroundImage'].
|
||||
*
|
||||
* Only fields with a value in the source are copied: clearing a field in one
|
||||
* language does NOT wipe it in the others (conservative, matches the hand-
|
||||
* rolled hooks this replaces). Text and other truly-localized fields are never
|
||||
* touched.
|
||||
*/
|
||||
fields: string[]
|
||||
/**
|
||||
* Flag name set on `req` to break the update→afterChange→update loop.
|
||||
* Default '_ipalSyncingCrossLocale'. Override only if two syncs run on one
|
||||
* collection and must not share a guard.
|
||||
*/
|
||||
guardFlag?: string
|
||||
}
|
||||
|
||||
/** Relationship/upload values arrive as an id or a populated object — normalize to the id. */
|
||||
function toId(value: unknown): null | number | string {
|
||||
if (value == null) {return null}
|
||||
if (typeof value === 'string' || typeof value === 'number') {return value}
|
||||
if (typeof value === 'object' && 'id' in (value as Record<string, unknown>)) {
|
||||
const id = (value as Record<string, unknown>).id
|
||||
return typeof id === 'string' || typeof id === 'number' ? id : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Propagates language-independent fields (images, icons…) that live INSIDE a
|
||||
* localized `blocks`/`array` field from the just-edited locale to every other
|
||||
* configured locale.
|
||||
*
|
||||
* Why this exists: Payload localizes an array/blocks field as a whole, so there
|
||||
* is no way to mark a single sub-field (the image) as non-localized — each
|
||||
* locale keeps its own copy of every row, image included. Without this, an
|
||||
* editor who picks images in Polish has to re-pick the SAME images in English,
|
||||
* German, … This hook does that copy automatically.
|
||||
*
|
||||
* A0-safe: the locale list comes from `config`, never a hard-coded array — add
|
||||
* a language in the panel and it's covered with no code change. (The hand-rolled
|
||||
* versions this replaces carried a literal `['pl','en',...]` that silently
|
||||
* dropped any locale not listed.)
|
||||
*
|
||||
* Row matching: by Payload row `id` when the same id exists in both locales
|
||||
* (robust to reordering and to several blocks of the same type); otherwise it
|
||||
* falls back to the positional index, but only when the block types at that
|
||||
* index match — so it never writes an image into a block of a different type.
|
||||
*
|
||||
* // collections/Pages.ts
|
||||
* import { buildCrossLocaleFieldSync } from '@intecion/ipal-kit'
|
||||
* hooks: {
|
||||
* afterChange: [
|
||||
* buildCrossLocaleFieldSync({ config: i18nConfig, collection: 'pages', fields: ['image'] }),
|
||||
* ],
|
||||
* }
|
||||
*/
|
||||
export function buildCrossLocaleFieldSync(
|
||||
args: BuildCrossLocaleFieldSyncArgs,
|
||||
): CollectionAfterChangeHook {
|
||||
const {
|
||||
arrayField = 'layout',
|
||||
collection,
|
||||
config,
|
||||
fields,
|
||||
guardFlag = '_ipalSyncingCrossLocale',
|
||||
} = args
|
||||
|
||||
return async ({ doc, req }) => {
|
||||
const reqAny = req as unknown as Record<string, unknown>
|
||||
// Re-entry guard: our own payload.update() below re-fires afterChange.
|
||||
if (reqAny[guardFlag] || !doc?.id) {return doc}
|
||||
|
||||
const sourceRows = (doc as Record<string, unknown>)[arrayField]
|
||||
if (!Array.isArray(sourceRows) || sourceRows.length === 0) {return doc}
|
||||
|
||||
// Source locale = the locale being written. Fall back to the configured
|
||||
// default rather than a hard-coded 'pl' when req.locale is absent.
|
||||
const sourceLocale = typeof req.locale === 'string' ? req.locale : config.defaultLocale
|
||||
const otherLocales = getLocaleCodes(config).filter((l) => l !== sourceLocale)
|
||||
if (otherLocales.length === 0) {return doc} // single-locale site: nothing to sync
|
||||
|
||||
const payload = req.payload
|
||||
|
||||
reqAny[guardFlag] = true
|
||||
try {
|
||||
for (const locale of otherLocales) {
|
||||
let targetDoc: Record<string, unknown>
|
||||
try {
|
||||
targetDoc = (await payload.findByID({
|
||||
id: doc.id as never,
|
||||
collection: collection as never,
|
||||
depth: 0,
|
||||
locale: locale as never,
|
||||
})) as Record<string, unknown>
|
||||
} catch {
|
||||
continue // locale not yet created for this doc — nothing to sync into
|
||||
}
|
||||
|
||||
const targetRows = targetDoc[arrayField]
|
||||
if (!Array.isArray(targetRows) || targetRows.length === 0) {continue}
|
||||
|
||||
// id → row index, for robust matching across locales.
|
||||
const byId = new Map<number | string, number>()
|
||||
;(targetRows as Row[]).forEach((row, i) => {
|
||||
if (row?.id != null) {byId.set(row.id, i)}
|
||||
})
|
||||
|
||||
let changed = false
|
||||
|
||||
;(sourceRows as Row[]).forEach((sourceRow, idx) => {
|
||||
if (!sourceRow) {return}
|
||||
|
||||
// Match by id first; else positional index, but only if block types agree.
|
||||
let targetRow: Row | undefined
|
||||
if (sourceRow.id != null && byId.has(sourceRow.id)) {
|
||||
targetRow = (targetRows as Row[])[byId.get(sourceRow.id)!]
|
||||
} else {
|
||||
const candidate = (targetRows as Row[])[idx]
|
||||
if (candidate && candidate.blockType === sourceRow.blockType) {targetRow = candidate}
|
||||
}
|
||||
if (!targetRow) {return}
|
||||
|
||||
for (const field of fields) {
|
||||
const sourceId = toId(sourceRow[field])
|
||||
if (sourceId == null) {continue} // don't propagate a cleared field
|
||||
if (toId(targetRow[field]) !== sourceId) {
|
||||
targetRow[field] = sourceId
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (changed) {
|
||||
await payload.update({
|
||||
id: doc.id as never,
|
||||
collection: collection as never,
|
||||
data: { [arrayField]: targetRows } as never,
|
||||
locale: locale as never,
|
||||
req,
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
payload.logger?.error?.({ err, msg: `[ipal] cross-locale ${arrayField} sync failed` })
|
||||
} finally {
|
||||
reqAny[guardFlag] = false
|
||||
}
|
||||
|
||||
return doc
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
// żeby był jeden katalog "wszystkie hooki pluginu"). Źródło prawdy to ich moduły.
|
||||
export { normalizeFilenameHook } from '../media/index.js'
|
||||
export { buildAutoFillMetaHook, validateFaviconField } from '../seo/index.js'
|
||||
export { buildCrossLocaleFieldSync } from './buildCrossLocaleFieldSync.js'
|
||||
export { buildRevalidateHook } from './buildRevalidateHook.js'
|
||||
export { buildPreventDeleteSystemPage } from './preventDeleteSystemPage.js'
|
||||
export { setPublishedAtHook } from './setPublishedAt.js'
|
||||
|
||||
@@ -16,5 +16,6 @@ export { buildLocalizationConfig } from './localizationConfig.js'
|
||||
export { buildLocalizedPath, switchLocalePath } from './localizedPath.js'
|
||||
export type { LocalizedSlugs } from './localizedPath.js'
|
||||
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'
|
||||
export { resolveLocalized } from './resolveLocalized.js'
|
||||
export type { I18nConfig, LocaleDefinition } from './types.js'
|
||||
export { validateI18nConfig } from './validation.js'
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Resolves a possibly-localized value to a string for the given locale.
|
||||
* Payload returns a localized field as a plain string (current locale) OR, with
|
||||
* locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles
|
||||
* both, with a safe fallback to the first available value — replacing the
|
||||
* hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,
|
||||
* rich text, form topics, …).
|
||||
*
|
||||
* import { resolveLocalized } from '@intecion/ipal-kit'
|
||||
* const name = resolveLocalized(item.label, locale) // '' if nothing
|
||||
* const city = resolveLocalized(company.city, locale, '—') // custom fallback
|
||||
*/
|
||||
export function resolveLocalized(value: unknown, locale: string, fallback = ''): string {
|
||||
if (value == null) {return fallback}
|
||||
if (typeof value === 'string') {return value}
|
||||
if (typeof value === 'object') {
|
||||
const map = value as Record<string, unknown>
|
||||
const forLocale = map[locale]
|
||||
if (typeof forLocale === 'string') {return forLocale}
|
||||
const first = Object.values(map).find((v) => typeof v === 'string')
|
||||
return (first) ?? fallback
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
@@ -39,6 +39,15 @@ type SettingsShape = {
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* import { i18nConfig } from '@/i18n.config'
|
||||
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
|
||||
*
|
||||
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
|
||||
* `next build` with no reachable database (the usual Coolify/Docker case) gets
|
||||
* a minimal valid manifest instead of a crash — same contract as
|
||||
* generateStaticParams and the sitemap handler. Projects should still mark the
|
||||
* route dynamic so Next doesn't prerender it at build time:
|
||||
*
|
||||
* // app/manifest.ts
|
||||
* export const dynamic = 'force-dynamic'
|
||||
*/
|
||||
export function createManifestHandler(opts: {
|
||||
config: I18nConfig
|
||||
@@ -47,18 +56,35 @@ export function createManifestHandler(opts: {
|
||||
}): () => Promise<Manifest> {
|
||||
return async () => {
|
||||
const defaultLocale = getDefaultLocale(opts.config)
|
||||
const payload = await opts.getCachedPayload()
|
||||
const settings = (await payload
|
||||
.findGlobal({
|
||||
slug: (opts.settingsSlug ?? 'site-settings') as never,
|
||||
depth: 1,
|
||||
locale: defaultLocale as never,
|
||||
})
|
||||
.catch(() => null)) as null | SettingsShape
|
||||
|
||||
const start_url = `/${defaultLocale}`
|
||||
|
||||
// Minimal, always-valid manifest. Used both when SiteSettings is empty and
|
||||
// when the database is unreachable during a build.
|
||||
const fallback: Manifest = { display: 'standalone', icons: [], start_url }
|
||||
|
||||
let settings: null | SettingsShape
|
||||
try {
|
||||
// getCachedPayload() ITSELF throws when the DB can't be reached (e.g.
|
||||
// `getaddrinfo ENOTFOUND` during `docker build`), BEFORE findGlobal runs
|
||||
// — so the whole thing, not just the query, must sit inside try/catch.
|
||||
const payload = await opts.getCachedPayload()
|
||||
settings = (await payload
|
||||
.findGlobal({
|
||||
slug: (opts.settingsSlug ?? 'site-settings') as never,
|
||||
depth: 1,
|
||||
locale: defaultLocale as never,
|
||||
})
|
||||
.catch(() => null)) as null | SettingsShape
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
'[ipal] createManifestHandler: database not reachable during build (Docker/CI) — returning minimal manifest; it fills in at runtime:',
|
||||
err,
|
||||
)
|
||||
return fallback
|
||||
}
|
||||
|
||||
if (!settings) {
|
||||
return { display: 'standalone', icons: [], start_url }
|
||||
return fallback
|
||||
}
|
||||
|
||||
const iconSource = settings.favicon ?? settings.logo
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { CheckboxField, Field, FieldHook } from 'payload'
|
||||
|
||||
type BuildNoindexFieldArgs = {
|
||||
/** Help text under the checkbox. */
|
||||
description?: string
|
||||
/** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */
|
||||
label?: string
|
||||
/**
|
||||
* Dotted path, inside the document, that the SEO read path (metadata +
|
||||
* sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.
|
||||
* The checkbox value is mirrored here on every save, so editors toggle one
|
||||
* friendly switch and the machinery reads a stable location.
|
||||
*/
|
||||
metaPath?: string
|
||||
/** Field name for the editor-facing checkbox. Default 'noindex'. */
|
||||
name?: string
|
||||
/** Extend/override the generated checkbox (position, access, etc.). */
|
||||
overrides?: Partial<CheckboxField>
|
||||
}
|
||||
|
||||
/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */
|
||||
function readPath(obj: null | Record<string, unknown> | undefined, path: string[]): unknown {
|
||||
let cur: unknown = obj
|
||||
for (const key of path) {
|
||||
if (cur == null || typeof cur !== 'object') {return undefined}
|
||||
cur = (cur as Record<string, unknown>)[key]
|
||||
}
|
||||
return cur
|
||||
}
|
||||
|
||||
/** Write a dotted path, creating intermediate objects as needed. */
|
||||
function writePath(obj: Record<string, unknown>, path: string[], value: unknown): void {
|
||||
let cur: Record<string, unknown> = obj
|
||||
for (let i = 0; i < path.length - 1; i++) {
|
||||
const key = path[i]
|
||||
const next = cur[key]
|
||||
if (next == null || typeof next !== 'object') {cur[key] = {}}
|
||||
cur = cur[key] as Record<string, unknown>
|
||||
}
|
||||
cur[path[path.length - 1]] = value
|
||||
}
|
||||
|
||||
/**
|
||||
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
|
||||
* sitemap and metadata generators actually read). Replaces the hand-rolled
|
||||
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
|
||||
* glue copied into every project — no `any`, one source of truth for editors,
|
||||
* one stable read location for the engine.
|
||||
*
|
||||
* Idempotent and order-independent: if either the checkbox OR an existing
|
||||
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
|
||||
*
|
||||
* // collections/Pages.ts
|
||||
* import { buildNoindexField } from '@intecion/ipal-kit'
|
||||
* fields: [ /* … *\/ buildNoindexField() ],
|
||||
*/
|
||||
export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
|
||||
const {
|
||||
name = 'noindex',
|
||||
description = 'Zaznacz, aby wykluczyć tę podstronę z indeksowania (robots: noindex, follow) i z sitemap.xml.',
|
||||
label = 'Wyklucz z indeksowania (noindex)',
|
||||
metaPath = 'meta.noindex',
|
||||
overrides = {},
|
||||
} = args
|
||||
|
||||
const segments = metaPath.split('.')
|
||||
|
||||
const mirror: FieldHook = ({ data, value }) => {
|
||||
const shouldNoindex = Boolean(value ?? readPath(data as Record<string, unknown>, segments))
|
||||
if (data && typeof data === 'object') {
|
||||
writePath(data as Record<string, unknown>, segments, shouldNoindex)
|
||||
}
|
||||
return shouldNoindex
|
||||
}
|
||||
|
||||
const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides
|
||||
|
||||
return {
|
||||
name,
|
||||
type: 'checkbox',
|
||||
admin: {
|
||||
description,
|
||||
position: 'sidebar',
|
||||
...adminOverrides,
|
||||
},
|
||||
defaultValue: false,
|
||||
hooks: {
|
||||
...hooksOverrides,
|
||||
// mirror runs first, then any project-supplied beforeChange hooks.
|
||||
beforeChange: [mirror, ...(hooksOverrides?.beforeChange ?? [])],
|
||||
},
|
||||
label,
|
||||
...restOverrides,
|
||||
} as CheckboxField
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'
|
||||
export { createManifestHandler } from './buildManifest.js'
|
||||
export { buildMetadata } from './buildMetadata.js'
|
||||
export type { PageMetadata } from './buildMetadata.js'
|
||||
export { buildNoindexField } from './buildNoindexField.js'
|
||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
|
||||
export { buildRobots } from './buildRobots.js'
|
||||
export type { RobotsRules } from './buildRobots.js'
|
||||
|
||||
Reference in New Issue
Block a user