@vtex/faststore 0.0.6 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/dist/catalog.json +161 -20
- package/dist/cli/UnreachableCaseError-Crd168Vu.js +10 -0
- package/dist/cli/UnreachableCaseError-Crd168Vu.js.map +1 -0
- package/dist/cli/cacheControl-CEojH_TM.js +158 -0
- package/dist/cli/cacheControl-CEojH_TM.js.map +1 -0
- package/dist/cli/cachePolicy-m2vASMRW.js +26 -0
- package/dist/cli/cachePolicy-m2vASMRW.js.map +1 -0
- package/dist/cli/computeCoreSchemaHash-DPJZj-qJ.js +10 -0
- package/dist/cli/computeCoreSchemaHash-DPJZj-qJ.js.map +1 -0
- package/dist/cli/default-BCQHcwbL.js +253 -0
- package/dist/cli/default-BCQHcwbL.js.map +1 -0
- package/dist/cli/disableSuggestions-yO9UqiWn.js +21 -0
- package/dist/cli/disableSuggestions-yO9UqiWn.js.map +1 -0
- package/dist/cli/dist-C1JhdHfo.js +2001 -0
- package/dist/cli/dist-C1JhdHfo.js.map +1 -0
- package/dist/cli/graphql-DG9thCDG.js +14589 -0
- package/dist/cli/graphql-DG9thCDG.js.map +1 -0
- package/dist/cli/index.d.ts +350 -0
- package/dist/cli/index.js +35047 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/index.min-BsIHDfFK.js +613 -0
- package/dist/cli/index.min-BsIHDfFK.js.map +1 -0
- package/dist/cli/inlineTrace-uLgOJ3TH.js +52 -0
- package/dist/cli/inlineTrace-uLgOJ3TH.js.map +1 -0
- package/dist/cli/internalPlugin-DnuwN4_4.js +11 -0
- package/dist/cli/internalPlugin-DnuwN4_4.js.map +1 -0
- package/dist/cli/packageVersion-DQAnIEil.js +6 -0
- package/dist/cli/packageVersion-DQAnIEil.js.map +1 -0
- package/dist/cli/rolldown-runtime-BMI-E3GI.js +44 -0
- package/dist/cli/schemaIsSubgraph-DoGh3OYj.js +17 -0
- package/dist/cli/schemaIsSubgraph-DoGh3OYj.js.map +1 -0
- package/dist/cli/schemaReporting-K-me-3-v.js +199 -0
- package/dist/cli/schemaReporting-K-me-3-v.js.map +1 -0
- package/dist/cli/server-runtime.js +49859 -0
- package/dist/cli/server-runtime.js.map +1 -0
- package/dist/cli/traceTreeBuilder-BIcV2U7b.js +9118 -0
- package/dist/cli/traceTreeBuilder-BIcV2U7b.js.map +1 -0
- package/dist/cli/usageReporting-Bpl8vSZX.js +10201 -0
- package/dist/cli/usageReporting-Bpl8vSZX.js.map +1 -0
- package/dist/cli/v4-CBhFvC49.js +42 -0
- package/dist/cli/v4-CBhFvC49.js.map +1 -0
- package/dist/components.d.ts +5 -3
- package/dist/components.js +5 -3
- package/dist/content-types.json +93 -0
- package/dist/core/dist/define-component.d.ts +37 -0
- package/dist/core/dist/index.d.ts +2 -2
- package/dist/docs/account-entry-point.md +1 -1
- package/dist/docs/account-menu-identity.md +160 -0
- package/dist/docs/account-menu.md +106 -23
- package/dist/docs/avatar.md +103 -0
- package/dist/docs/my-account-profile.md +1 -1
- package/dist/docs/product-shelf.md +20 -13
- package/dist/index.d.ts +2 -2
- package/dist/internal/client.js +1 -1
- package/dist/internal/content.d.ts +2 -2
- package/dist/internal/server.d.ts +4 -1
- package/dist/internal/server.js +4 -1
- package/dist/matter/account-access-gate/account-access-gate.js.map +1 -1
- package/dist/matter/account-entry-point/account-entry-point.js +1 -1
- package/dist/matter/account-entry-point/account-entry-point.js.map +1 -1
- package/dist/matter/account-menu/account-menu.d.ts +70 -0
- package/dist/matter/account-menu/account-menu.js +201 -9
- package/dist/matter/account-menu/account-menu.js.map +1 -1
- package/dist/matter/account-menu/sign-out-failure.js +50 -0
- package/dist/matter/account-menu/sign-out-failure.js.map +1 -0
- package/dist/matter/account-menu-identity/account-menu-identity.d.ts +21 -0
- package/dist/matter/account-menu-identity/account-menu-identity.js +88 -0
- package/dist/matter/account-menu-identity/account-menu-identity.js.map +1 -0
- package/dist/matter/card-entry/card-entry.js +1 -0
- package/dist/matter/card-entry/card-entry.js.map +1 -1
- package/dist/matter/cart/cart.js +1 -1
- package/dist/matter/client-preferences/client-preferences-fieldset.js +2 -2
- package/dist/matter/client-profile-form/client-profile-fieldset.js +2 -2
- package/dist/matter/identity-summary/identity-summary.js +2 -1
- package/dist/matter/identity-summary/identity-summary.js.map +1 -1
- package/dist/matter/my-account-profile/my-account-profile.d.ts +3 -0
- package/dist/matter/my-account-profile/my-account-profile.js +2 -1
- package/dist/matter/my-account-profile/my-account-profile.js.map +1 -1
- package/dist/matter/payment/payment-controller.js +1 -0
- package/dist/matter/payment/payment-controller.js.map +1 -1
- package/dist/matter/payment/payment.js +1 -0
- package/dist/matter/payment/payment.js.map +1 -1
- package/dist/matter/product-shelf/product-shelf.d.ts +61 -31
- package/dist/matter/product-shelf/product-shelf.js +157 -57
- package/dist/matter/product-shelf/product-shelf.js.map +1 -1
- package/dist/matter/saved-cards/saved-cards.js +1 -0
- package/dist/matter/saved-cards/saved-cards.js.map +1 -1
- package/dist/matter/shipping-address/shipping-address.js +2 -2
- package/dist/particles/avatar/avatar.d.ts +17 -0
- package/dist/particles/avatar/avatar.js +65 -0
- package/dist/particles/avatar/avatar.js.map +1 -0
- package/dist/schema.graphql +65 -26
- package/dist/sdk/analytics/use-analytics-actions.js +2 -1
- package/dist/sdk/analytics/use-analytics-actions.js.map +1 -1
- package/dist/sdk/cart/use-cart-actions.js +9 -8
- package/dist/sdk/cart/use-cart-actions.js.map +1 -1
- package/dist/sdk/cart/use-cart-validate-on-open.js +2 -1
- package/dist/sdk/cart/use-cart-validate-on-open.js.map +1 -1
- package/dist/sdk/content/create-content-runtime.d.ts +22 -1
- package/dist/sdk/content/create-content-runtime.js +89 -1
- package/dist/sdk/content/create-content-runtime.js.map +1 -1
- package/dist/sdk/data/empty-content-value.js +16 -0
- package/dist/sdk/data/empty-content-value.js.map +1 -0
- package/dist/sdk/data/hot-data-provider.js +2 -1
- package/dist/sdk/data/hot-data-provider.js.map +1 -1
- package/dist/sdk/data/index.js +2 -2
- package/dist/sdk/data/reactive-list-item-data-provider.js +2 -2
- package/dist/sdk/data/variables-from-content.d.ts +43 -0
- package/dist/sdk/data/variables-from-content.js +57 -0
- package/dist/sdk/data/variables-from-content.js.map +1 -0
- package/dist/sdk/generated/gql.js +2 -1
- package/dist/sdk/generated/gql.js.map +1 -1
- package/dist/sdk/generated/graphql.js +85 -1
- package/dist/sdk/generated/graphql.js.map +1 -1
- package/dist/sdk/identity/use-identity-actions.js +5 -4
- package/dist/sdk/identity/use-identity-actions.js.map +1 -1
- package/dist/sdk/payment/use-payment-actions.js +1 -1
- package/dist/sdk/payment/use-place-order.js +1 -1
- package/dist/sdk/region/use-region-actions.js +2 -1
- package/dist/sdk/region/use-region-actions.js.map +1 -1
- package/dist/sdk/session/read-server-session.d.ts +21 -0
- package/dist/sdk/session/read-server-session.js +61 -0
- package/dist/sdk/session/read-server-session.js.map +1 -0
- package/dist/sdk/session/use-session-actions.js +5 -4
- package/dist/sdk/session/use-session-actions.js.map +1 -1
- package/dist/sdk/session/use-session-revalidation.js +2 -1
- package/dist/sdk/session/use-session-revalidation.js.map +1 -1
- package/dist/sdk/shipping/use-shipping-actions.js +3 -2
- package/dist/sdk/shipping/use-shipping-actions.js.map +1 -1
- package/dist/utils/safe-href.d.ts +11 -0
- package/package.json +13 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity-summary.js","names":[],"sources":["../../../src/matter/identity-summary/identity-summary.tsx"],"sourcesContent":["'use client';\n\nimport { defineComponent } from '@vtex/fs-core';\nimport { createContext, type ReactNode, useContext, useState } from 'react';\nimport { Badge } from '../../particles/badge/badge.js';\nimport { applyPhoneMask, type PhoneCountry } from '../../particles/phone-field/phone-field.js';\nimport { useActionsOverride } from '../../sdk/actions/actions-override-context.js';\nimport type { ComponentActions } from '../../sdk/actions/types.js';\nimport { useDataOverride } from '../../sdk/data/data-override-context.js';\nimport type { SessionUserError } from '../../sdk/session/auth-operations.js';\nimport { type SessionState, useSession } from '../session/session.js';\n\n// ---------------------------------------------------------------------------\n// GraphQL Fragment — colocated self-contained data root (ADR-0011).\n// Reads only `clientProfile` (the fields this read-only summary displays). The\n// edit surface is a separately-composed FormRoot over `ClientProfileFieldset`, which owns its own\n// fragment and identity actions.\n//\n// Single top-level entity → the compiler delivers `$data` UNWRAPPED, i.e. the\n// `ClientProfile` value directly, not `{ clientProfile: ... }` (ADR-0015 arity-1).\n// ---------------------------------------------------------------------------\n\nconst fragment = /* GraphQL */ `\n fragment IdentitySummaryData on Query {\n clientProfile {\n __typename\n id\n email\n firstName\n lastName\n phone\n document\n }\n }\n`;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * The `$data` slice forwarded by the reactive runtime — the unwrapped `ClientProfile` entity.\n * The fragment selects a single top-level field, so the compiler hands the entity value directly\n * (not a `{ clientProfile: ... }` wrapper); ADR-0015.\n */\nexport type IdentitySummaryData = {\n email?: string | null;\n firstName?: string | null;\n lastName?: string | null;\n phone?: string | null;\n document?: string | null;\n} | null;\n\n// ---------------------------------------------------------------------------\n// Context — data + session state + sign-out, provided by IdentitySummaryRoot.\n// The summary/form swap is owned by `IdentityEditController`, which moves only on its own buttons\n// (ADR-0006) — this matter owns only the identity data and the sign-out action, never a bespoke toggle.\n// ---------------------------------------------------------------------------\n\ntype IdentitySummaryContextValue = {\n state: SessionState;\n firstName: string;\n lastName: string;\n email: string;\n phone: string;\n document: string;\n handleSignOut: () => void;\n signOutPending: boolean;\n signOutError: string | null;\n};\n\nconst IDENTITY_SUMMARY_CONTEXT_UNSET = Symbol('IdentitySummaryContextUnset');\n\nconst IdentitySummaryContext = createContext<IdentitySummaryContextValue | typeof IDENTITY_SUMMARY_CONTEXT_UNSET>(\n IDENTITY_SUMMARY_CONTEXT_UNSET,\n);\n\nfunction useIdentitySummaryContext(): IdentitySummaryContextValue {\n const ctx = useContext(IdentitySummaryContext);\n if (ctx === IDENTITY_SUMMARY_CONTEXT_UNSET) {\n throw new Error('IdentitySummary components must be used inside IdentitySummaryRoot.');\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport type IdentitySummaryRootProps = {\n /** Error message shown when the sign-out mutation returns user errors. */\n signOutErrorMessage?: string;\n className?: string;\n children?: ReactNode;\n /** `IdentitySummaryData` slice forwarded by the reactive runtime. */\n $data?: IdentitySummaryData;\n /** Compiler-injected action surface; carries `session.logout`. */\n $actions?: ComponentActions;\n};\n\nexport type IdentitySummarySelectedSummaryProps = {\n /** Phone display country; selects the mask applied to the stored E.164 value. */\n country?: PhoneCountry;\n /** Badge label in the `identified` session state. */\n identifiedBadgeLabel?: string;\n /** Badge label in the `loggedIn` session state. */\n loggedInBadgeLabel?: string;\n className?: string;\n /** Compose custom read-only content; falls back to the default badge + details when omitted. */\n children?: ReactNode;\n};\n\nexport type IdentitySummaryBadgeProps = {\n /** Badge label in the `identified` session state. */\n identifiedLabel?: string;\n /** Badge label in the `loggedIn` session state. */\n loggedInLabel?: string;\n className?: string;\n};\n\nexport type IdentitySummaryFieldProps = {\n className?: string;\n};\n\nexport type IdentitySummaryPhoneProps = {\n /** Phone display country; selects the mask applied to the stored E.164 value. */\n country?: PhoneCountry;\n className?: string;\n};\n\nexport type IdentitySummarySignOutButtonProps = {\n label?: string;\n className?: string;\n children?: ReactNode;\n};\n\nexport type IdentitySummaryErrorProps = {\n className?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Definitions\n// ---------------------------------------------------------------------------\n\nexport const IdentitySummaryRootDefinition = defineComponent<IdentitySummaryRootProps>({\n name: 'IdentitySummaryRoot',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryRoot,\n fragment,\n fetchStrategy: 'reactive',\n requiresContext: 'session',\n providesContext: 'identity-summary',\n actions: { session: ['logout'] },\n editor: { label: 'Identity Summary Root', category: 'identity' },\n schema: {\n signOutErrorMessage: {\n type: 'string',\n default: 'Unable to sign out. Please try again.',\n label: 'Sign-out error message',\n },\n },\n guideline:\n 'Read-only identity summary data root: reads the shopper profile, provides it plus a sign-out action to descendants, and self-gates (renders nothing in the anonymous state). Must be inside SessionRoot. Wrap the parts in an IdentityEditController for the summary/form swap: an IdentitySummaryView holding these parts, an IdentityEditForm holding a FormRoot over ClientProfileFieldset. See identity-summary.md.',\n});\n\nexport const IdentitySummarySelectedSummaryDefinition = defineComponent<IdentitySummarySelectedSummaryProps>({\n name: 'IdentitySummarySelectedSummary',\n importPath: '@vtex/faststore/components',\n component: IdentitySummarySelectedSummary,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Selected Summary', category: 'identity' },\n schema: {},\n guideline:\n 'Default composition of the identity summary: badge, name, e-mail, phone, document, in that order. It is a shortcut, not the only way — to change the order, drop a field, or interleave anything else, compose IdentitySummaryBadge / Name / Email / Phone / Document directly instead. It offers nothing to the schema: its country and badge-label props configure the default composition only, and are withheld from the schema because a page that set one here and then composed children would watch it vanish. A composed summary configures the leaf instead — the phone mask country on IdentitySummaryPhone, the labels on IdentitySummaryBadge. Must be a descendant of IdentitySummaryRoot.',\n});\n\nexport const IdentitySummaryBadgeDefinition = defineComponent<IdentitySummaryBadgeProps>({\n name: 'IdentitySummaryBadge',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryBadge,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Badge', category: 'identity' },\n schema: {\n identifiedLabel: { type: 'string', default: 'Guest', label: 'Identified badge label' },\n loggedInLabel: { type: 'string', default: 'Signed in', label: 'Logged-in badge label' },\n },\n guideline:\n 'Session-state badge for the identity summary. Place it wherever the summary should carry it; order is composition, not a prop. Must be a descendant of IdentitySummaryRoot.',\n});\n\nexport const IdentitySummaryNameDefinition = defineComponent<IdentitySummaryFieldProps>({\n name: 'IdentitySummaryName',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryName,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Name', category: 'identity' },\n schema: {},\n guideline:\n \"The shopper's full name, or nothing when the profile has neither first nor last name. Place it in whatever order the summary should read. Must be a descendant of IdentitySummaryRoot.\",\n});\n\nexport const IdentitySummaryEmailDefinition = defineComponent<IdentitySummaryFieldProps>({\n name: 'IdentitySummaryEmail',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryEmail,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Email', category: 'identity' },\n schema: {},\n guideline: \"The shopper's e-mail, or nothing when absent. Must be a descendant of IdentitySummaryRoot.\",\n});\n\nexport const IdentitySummaryPhoneDefinition = defineComponent<IdentitySummaryPhoneProps>({\n name: 'IdentitySummaryPhone',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryPhone,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Phone', category: 'identity' },\n schema: {\n country: { type: 'string', label: 'Phone country (US or BR)' },\n },\n guideline:\n \"The shopper's phone, or nothing when absent. Masked for `country` when one is set; rendered as stored otherwise, since each mask truncates to its own country's length. Must be a descendant of IdentitySummaryRoot.\",\n});\n\nexport const IdentitySummaryDocumentDefinition = defineComponent<IdentitySummaryFieldProps>({\n name: 'IdentitySummaryDocument',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryDocument,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Document', category: 'identity' },\n schema: {},\n guideline: \"The shopper's tax document, or nothing when absent. Must be a descendant of IdentitySummaryRoot.\",\n});\n\nexport const IdentitySummarySignOutButtonDefinition = defineComponent<IdentitySummarySignOutButtonProps>({\n name: 'IdentitySummarySignOutButton',\n importPath: '@vtex/faststore/components',\n component: IdentitySummarySignOutButton,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Sign Out Button', category: 'action' },\n schema: {\n label: { type: 'string', default: 'Sign out', label: 'Button label' },\n },\n guideline:\n 'Dispatches $actions.session.logout (async/pessimistic): carries data-fs-identity-summary-pending while in flight and disables itself. Compose an Icon + text as children, or rely on `label`. Must be a descendant of IdentitySummaryRoot.',\n});\n\nexport const IdentitySummaryErrorDefinition = defineComponent<IdentitySummaryErrorProps>({\n name: 'IdentitySummaryError',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryError,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Error', category: 'content' },\n schema: {},\n guideline:\n 'Renders the inline sign-out error (role=\"alert\") when the logout mutation returns a user error, else nothing. Must be a descendant of IdentitySummaryRoot.',\n});\n\n// ---------------------------------------------------------------------------\n// Root\n// ---------------------------------------------------------------------------\n\n/**\n * Data root for the identity summary. Reads the shopper profile from its colocated fragment,\n * enforces the SessionRoot ancestor via `useSession()`, and self-gates to null in the anonymous\n * state. Owns the sign-out mutation state (pending/error) and broadcasts everything the read-only\n * parts and the sign-out button need through `IdentitySummaryContext`.\n */\nexport function IdentitySummaryRoot({\n signOutErrorMessage = 'Unable to sign out. Please try again.',\n className,\n children,\n $data: $dataProp,\n $actions: $actionsProp,\n}: Readonly<IdentitySummaryRootProps>) {\n const $data = useDataOverride($dataProp);\n const $actions = useActionsOverride($actionsProp);\n // Enforces the SessionRoot ancestor: useSession() throws when rendered outside one.\n const { state } = useSession();\n\n const [signOutPending, setSignOutPending] = useState(false);\n const [signOutError, setSignOutError] = useState<string | null>(null);\n\n async function handleSignOut() {\n setSignOutPending(true);\n setSignOutError(null);\n try {\n const errors: readonly SessionUserError[] = (await $actions?.session?.logout?.()) ?? [];\n if (errors.length > 0) setSignOutError(errors[0]?.message ?? signOutErrorMessage);\n } catch (error) {\n // A logout that throws rather than resolving userErrors would otherwise leave the shopper still\n // signed in with nothing on screen, and escape as an unhandled rejection.\n console.error('[IdentitySummary] logout failed:', error instanceof Error ? error.name : 'UnknownError');\n setSignOutError(signOutErrorMessage);\n } finally {\n setSignOutPending(false);\n }\n }\n\n // Self-gate: nothing to show for an anonymous or unresolved session.\n if (state === 'anonymous') return null;\n\n const contextValue: IdentitySummaryContextValue = {\n state,\n firstName: $data?.firstName ?? '',\n lastName: $data?.lastName ?? '',\n email: $data?.email ?? '',\n phone: $data?.phone ?? '',\n document: $data?.document ?? '',\n handleSignOut,\n signOutPending,\n signOutError,\n };\n\n return (\n <IdentitySummaryContext.Provider value={contextValue}>\n <div\n className={className}\n data-fs-identity-summary=\"\"\n {...(signOutPending ? { 'data-fs-identity-summary-pending': '' } : {})}\n >\n {children}\n </div>\n </IdentitySummaryContext.Provider>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Read-only summary\n// ---------------------------------------------------------------------------\n\n/**\n * Read-only identity display: a session-state badge plus name, email, phone, and document.\n *\n * The props below configure the default composition only — composing children replaces it wholesale,\n * and a leaf placed there takes its own props (`IdentitySummaryPhone` its `country`,\n * `IdentitySummaryBadge` its labels). They are deliberately absent from the schema, so a page cannot\n * set one here and watch it disappear behind composed children.\n */\nexport function IdentitySummarySelectedSummary({\n country,\n identifiedBadgeLabel = 'Guest',\n loggedInBadgeLabel = 'Signed in',\n className,\n children,\n}: IdentitySummarySelectedSummaryProps) {\n return (\n <div className={className} data-fs-identity-summary-summary=\"\">\n {children ?? (\n <>\n <IdentitySummaryBadge identifiedLabel={identifiedBadgeLabel} loggedInLabel={loggedInBadgeLabel} />\n <IdentitySummaryName />\n <IdentitySummaryEmail />\n <IdentitySummaryPhone country={country} />\n <IdentitySummaryDocument />\n </>\n )}\n </div>\n );\n}\n\n/** Session-state badge. Renders `identifiedLabel` for a guest and `loggedInLabel` once authenticated. */\nexport function IdentitySummaryBadge({\n identifiedLabel = 'Guest',\n loggedInLabel = 'Signed in',\n className,\n}: IdentitySummaryBadgeProps) {\n const { state } = useIdentitySummaryContext();\n return (\n <Badge className={className} data-fs-identity-summary-badge=\"\" data-fs-identity-summary-state={state}>\n {state === 'loggedIn' ? loggedInLabel : identifiedLabel}\n </Badge>\n );\n}\n\n/** The shopper's full name. Renders nothing when the profile carries neither name. */\nexport function IdentitySummaryName({ className }: IdentitySummaryFieldProps) {\n const { firstName, lastName } = useIdentitySummaryContext();\n const fullName = [firstName, lastName].filter(Boolean).join(' ');\n if (!fullName) return null;\n return (\n <p className={className} data-fs-identity-summary-name=\"\">\n {fullName}\n </p>\n );\n}\n\n/** The shopper's e-mail. Renders nothing when absent. */\nexport function IdentitySummaryEmail({ className }: IdentitySummaryFieldProps) {\n const { email } = useIdentitySummaryContext();\n if (!email) return null;\n return (\n <p className={className} data-fs-identity-summary-email=\"\">\n {email}\n </p>\n );\n}\n\n/** E.164 prefixes for the countries the masks understand. */\nconst COUNTRY_PREFIX: Record<PhoneCountry, string> = { BR: '+55', US: '+1' };\n\n/**\n * The shopper's phone, masked for `country`. Renders nothing when absent, and renders the stored value\n * as-is whenever the mask does not apply to it — no country given, or a stored E.164 number belonging to\n * a different one. Each mask truncates to its own country's length, so applying the wrong one prints a\n * number that is not the shopper's, with nothing to signal that digits were dropped.\n */\nexport function IdentitySummaryPhone({ country, className }: IdentitySummaryPhoneProps) {\n const { phone } = useIdentitySummaryContext();\n if (!phone) return null;\n const maskApplies = country !== undefined && (!phone.startsWith('+') || phone.startsWith(COUNTRY_PREFIX[country]));\n return (\n <p className={className} data-fs-identity-summary-phone=\"\">\n {maskApplies && country ? applyPhoneMask(phone, country) : phone}\n </p>\n );\n}\n\n/** The shopper's tax document. Renders nothing when absent. */\nexport function IdentitySummaryDocument({ className }: IdentitySummaryFieldProps) {\n const { document } = useIdentitySummaryContext();\n if (!document) return null;\n return (\n <p className={className} data-fs-identity-summary-document=\"\">\n {document}\n </p>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Sign-out button + error (domain-coupled; the summary/form swap is IdentityEditController's)\n// ---------------------------------------------------------------------------\n\n/** Dispatches the sign-out mutation (async/pessimistic). */\nexport function IdentitySummarySignOutButton({\n label = 'Sign out',\n className,\n children,\n}: IdentitySummarySignOutButtonProps) {\n const { handleSignOut, signOutPending } = useIdentitySummaryContext();\n return (\n <button\n type=\"button\"\n data-fs-identity-summary-sign-out=\"\"\n className={className}\n disabled={signOutPending}\n {...(signOutPending ? { 'data-fs-identity-summary-pending': '' } : {})}\n onClick={handleSignOut}\n >\n {children ?? label}\n </button>\n );\n}\n\n/** Renders the inline sign-out user error, or nothing when there is none. */\nexport function IdentitySummaryError({ className }: IdentitySummaryErrorProps) {\n const { signOutError } = useIdentitySummaryContext();\n if (!signOutError) return null;\n return (\n <div role=\"alert\" className={className} data-fs-identity-summary-error=\"\">\n {signOutError}\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Namespace Export\n// ---------------------------------------------------------------------------\n\nexport const IdentitySummary = {\n Badge: IdentitySummaryBadge,\n BadgeDefinition: IdentitySummaryBadgeDefinition,\n Name: IdentitySummaryName,\n NameDefinition: IdentitySummaryNameDefinition,\n Email: IdentitySummaryEmail,\n EmailDefinition: IdentitySummaryEmailDefinition,\n Phone: IdentitySummaryPhone,\n PhoneDefinition: IdentitySummaryPhoneDefinition,\n Document: IdentitySummaryDocument,\n DocumentDefinition: IdentitySummaryDocumentDefinition,\n Root: IdentitySummaryRoot,\n RootDefinition: IdentitySummaryRootDefinition,\n SelectedSummary: IdentitySummarySelectedSummary,\n SelectedSummaryDefinition: IdentitySummarySelectedSummaryDefinition,\n SignOutButton: IdentitySummarySignOutButton,\n SignOutButtonDefinition: IdentitySummarySignOutButtonDefinition,\n Error: IdentitySummaryError,\n ErrorDefinition: IdentitySummaryErrorDefinition,\n};\n"],"mappings":";;;;;;;;;;;AAsBA,MAAM,WAAyB;;;;;;;;;;;;;AAiD/B,MAAM,iCAAiC,OAAO,6BAA6B;AAE3E,MAAM,yBAAyB,cAC7B,8BACF;AAEA,SAAS,4BAAyD;CAChE,MAAM,MAAM,WAAW,sBAAsB;CAC7C,IAAI,QAAQ,gCACV,MAAM,IAAI,MAAM,qEAAqE;CAEvF,OAAO;AACT;AA6DA,MAAa,gCAAgC,gBAA0C;CACrF,MAAM;CACN,YAAY;CACZ,WAAW;CACX;CACA,eAAe;CACf,iBAAiB;CACjB,iBAAiB;CACjB,SAAS,EAAE,SAAS,CAAC,QAAQ,EAAE;CAC/B,QAAQ;EAAE,OAAO;EAAyB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1
|
+
{"version":3,"file":"identity-summary.js","names":[],"sources":["../../../src/matter/identity-summary/identity-summary.tsx"],"sourcesContent":["'use client';\n\nimport { defineComponent } from '@vtex/fs-core';\nimport { createContext, type ReactNode, useContext, useState } from 'react';\nimport { Badge } from '../../particles/badge/badge.js';\nimport { applyPhoneMask, type PhoneCountry } from '../../particles/phone-field/phone-field.js';\nimport { useActionsOverride } from '../../sdk/actions/actions-override-context.js';\nimport type { ComponentActions } from '../../sdk/actions/types.js';\nimport { useDataOverride } from '../../sdk/data/data-override-context.js';\nimport type { SessionUserError } from '../../sdk/session/auth-operations.js';\nimport { loggableErrorName } from '../../utils/loggable-error-name.js';\nimport { type SessionState, useSession } from '../session/session.js';\n\n// ---------------------------------------------------------------------------\n// GraphQL Fragment — colocated self-contained data root (ADR-0011).\n// Reads only `clientProfile` (the fields this read-only summary displays). The\n// edit surface is a separately-composed FormRoot over `ClientProfileFieldset`, which owns its own\n// fragment and identity actions.\n//\n// Single top-level entity → the compiler delivers `$data` UNWRAPPED, i.e. the\n// `ClientProfile` value directly, not `{ clientProfile: ... }` (ADR-0015 arity-1).\n// ---------------------------------------------------------------------------\n\nconst fragment = /* GraphQL */ `\n fragment IdentitySummaryData on Query {\n clientProfile {\n __typename\n id\n email\n firstName\n lastName\n phone\n document\n }\n }\n`;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * The `$data` slice forwarded by the reactive runtime — the unwrapped `ClientProfile` entity.\n * The fragment selects a single top-level field, so the compiler hands the entity value directly\n * (not a `{ clientProfile: ... }` wrapper); ADR-0015.\n */\nexport type IdentitySummaryData = {\n email?: string | null;\n firstName?: string | null;\n lastName?: string | null;\n phone?: string | null;\n document?: string | null;\n} | null;\n\n// ---------------------------------------------------------------------------\n// Context — data + session state + sign-out, provided by IdentitySummaryRoot.\n// The summary/form swap is owned by `IdentityEditController`, which moves only on its own buttons\n// (ADR-0006) — this matter owns only the identity data and the sign-out action, never a bespoke toggle.\n// ---------------------------------------------------------------------------\n\ntype IdentitySummaryContextValue = {\n state: SessionState;\n firstName: string;\n lastName: string;\n email: string;\n phone: string;\n document: string;\n handleSignOut: () => void;\n signOutPending: boolean;\n signOutError: string | null;\n};\n\nconst IDENTITY_SUMMARY_CONTEXT_UNSET = Symbol('IdentitySummaryContextUnset');\n\nconst IdentitySummaryContext = createContext<IdentitySummaryContextValue | typeof IDENTITY_SUMMARY_CONTEXT_UNSET>(\n IDENTITY_SUMMARY_CONTEXT_UNSET,\n);\n\nfunction useIdentitySummaryContext(): IdentitySummaryContextValue {\n const ctx = useContext(IdentitySummaryContext);\n if (ctx === IDENTITY_SUMMARY_CONTEXT_UNSET) {\n throw new Error('IdentitySummary components must be used inside IdentitySummaryRoot.');\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport type IdentitySummaryRootProps = {\n /** Error message shown when the sign-out mutation returns user errors. */\n signOutErrorMessage?: string;\n className?: string;\n children?: ReactNode;\n /** `IdentitySummaryData` slice forwarded by the reactive runtime. */\n $data?: IdentitySummaryData;\n /** Compiler-injected action surface; carries `session.logout`. */\n $actions?: ComponentActions;\n};\n\nexport type IdentitySummarySelectedSummaryProps = {\n /** Phone display country; selects the mask applied to the stored E.164 value. */\n country?: PhoneCountry;\n /** Badge label in the `identified` session state. */\n identifiedBadgeLabel?: string;\n /** Badge label in the `loggedIn` session state. */\n loggedInBadgeLabel?: string;\n className?: string;\n /** Compose custom read-only content; falls back to the default badge + details when omitted. */\n children?: ReactNode;\n};\n\nexport type IdentitySummaryBadgeProps = {\n /** Badge label in the `identified` session state. */\n identifiedLabel?: string;\n /** Badge label in the `loggedIn` session state. */\n loggedInLabel?: string;\n className?: string;\n};\n\nexport type IdentitySummaryFieldProps = {\n className?: string;\n};\n\nexport type IdentitySummaryPhoneProps = {\n /** Phone display country; selects the mask applied to the stored E.164 value. */\n country?: PhoneCountry;\n className?: string;\n};\n\nexport type IdentitySummarySignOutButtonProps = {\n label?: string;\n className?: string;\n children?: ReactNode;\n};\n\nexport type IdentitySummaryErrorProps = {\n className?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Definitions\n// ---------------------------------------------------------------------------\n\nexport const IdentitySummaryRootDefinition = defineComponent<IdentitySummaryRootProps>({\n name: 'IdentitySummaryRoot',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryRoot,\n fragment,\n fetchStrategy: 'reactive',\n requiresContext: 'session',\n providesContext: 'identity-summary',\n actions: { session: ['logout'] },\n editor: { label: 'Identity Summary Root', category: 'identity' },\n schema: {\n signOutErrorMessage: {\n type: 'string',\n default: 'Unable to sign out. Please try again.',\n label: 'Sign-out error message',\n },\n },\n guideline:\n 'Read-only identity summary data root: reads the shopper profile, provides it plus a sign-out action to descendants, and self-gates (renders nothing in the anonymous state). Must be inside SessionRoot. Wrap the parts in an IdentityEditController for the summary/form swap: an IdentitySummaryView holding these parts, an IdentityEditForm holding a FormRoot over ClientProfileFieldset. See identity-summary.md.',\n});\n\nexport const IdentitySummarySelectedSummaryDefinition = defineComponent<IdentitySummarySelectedSummaryProps>({\n name: 'IdentitySummarySelectedSummary',\n importPath: '@vtex/faststore/components',\n component: IdentitySummarySelectedSummary,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Selected Summary', category: 'identity' },\n schema: {},\n guideline:\n 'Default composition of the identity summary: badge, name, e-mail, phone, document, in that order. It is a shortcut, not the only way — to change the order, drop a field, or interleave anything else, compose IdentitySummaryBadge / Name / Email / Phone / Document directly instead. It offers nothing to the schema: its country and badge-label props configure the default composition only, and are withheld from the schema because a page that set one here and then composed children would watch it vanish. A composed summary configures the leaf instead — the phone mask country on IdentitySummaryPhone, the labels on IdentitySummaryBadge. Must be a descendant of IdentitySummaryRoot.',\n});\n\nexport const IdentitySummaryBadgeDefinition = defineComponent<IdentitySummaryBadgeProps>({\n name: 'IdentitySummaryBadge',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryBadge,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Badge', category: 'identity' },\n schema: {\n identifiedLabel: { type: 'string', default: 'Guest', label: 'Identified badge label' },\n loggedInLabel: { type: 'string', default: 'Signed in', label: 'Logged-in badge label' },\n },\n guideline:\n 'Session-state badge for the identity summary. Place it wherever the summary should carry it; order is composition, not a prop. Must be a descendant of IdentitySummaryRoot.',\n});\n\nexport const IdentitySummaryNameDefinition = defineComponent<IdentitySummaryFieldProps>({\n name: 'IdentitySummaryName',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryName,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Name', category: 'identity' },\n schema: {},\n guideline:\n \"The shopper's full name, or nothing when the profile has neither first nor last name. Place it in whatever order the summary should read. Must be a descendant of IdentitySummaryRoot.\",\n});\n\nexport const IdentitySummaryEmailDefinition = defineComponent<IdentitySummaryFieldProps>({\n name: 'IdentitySummaryEmail',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryEmail,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Email', category: 'identity' },\n schema: {},\n guideline: \"The shopper's e-mail, or nothing when absent. Must be a descendant of IdentitySummaryRoot.\",\n});\n\nexport const IdentitySummaryPhoneDefinition = defineComponent<IdentitySummaryPhoneProps>({\n name: 'IdentitySummaryPhone',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryPhone,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Phone', category: 'identity' },\n schema: {\n country: { type: 'string', label: 'Phone country (US or BR)' },\n },\n guideline:\n \"The shopper's phone, or nothing when absent. Masked for `country` when one is set; rendered as stored otherwise, since each mask truncates to its own country's length. Must be a descendant of IdentitySummaryRoot.\",\n});\n\nexport const IdentitySummaryDocumentDefinition = defineComponent<IdentitySummaryFieldProps>({\n name: 'IdentitySummaryDocument',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryDocument,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Document', category: 'identity' },\n schema: {},\n guideline: \"The shopper's tax document, or nothing when absent. Must be a descendant of IdentitySummaryRoot.\",\n});\n\nexport const IdentitySummarySignOutButtonDefinition = defineComponent<IdentitySummarySignOutButtonProps>({\n name: 'IdentitySummarySignOutButton',\n importPath: '@vtex/faststore/components',\n component: IdentitySummarySignOutButton,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Sign Out Button', category: 'action' },\n schema: {\n label: { type: 'string', default: 'Sign out', label: 'Button label' },\n },\n guideline:\n 'Dispatches $actions.session.logout (async/pessimistic): carries data-fs-identity-summary-pending while in flight and disables itself. Compose an Icon + text as children, or rely on `label`. Must be a descendant of IdentitySummaryRoot.',\n});\n\nexport const IdentitySummaryErrorDefinition = defineComponent<IdentitySummaryErrorProps>({\n name: 'IdentitySummaryError',\n importPath: '@vtex/faststore/components',\n component: IdentitySummaryError,\n requiresContext: 'identity-summary',\n editor: { label: 'Identity Summary Error', category: 'content' },\n schema: {},\n guideline:\n 'Renders the inline sign-out error (role=\"alert\") when the logout mutation returns a user error, else nothing. Must be a descendant of IdentitySummaryRoot.',\n});\n\n// ---------------------------------------------------------------------------\n// Root\n// ---------------------------------------------------------------------------\n\n/**\n * Data root for the identity summary. Reads the shopper profile from its colocated fragment,\n * enforces the SessionRoot ancestor via `useSession()`, and self-gates to null in the anonymous\n * state. Owns the sign-out mutation state (pending/error) and broadcasts everything the read-only\n * parts and the sign-out button need through `IdentitySummaryContext`.\n */\nexport function IdentitySummaryRoot({\n signOutErrorMessage = 'Unable to sign out. Please try again.',\n className,\n children,\n $data: $dataProp,\n $actions: $actionsProp,\n}: Readonly<IdentitySummaryRootProps>) {\n const $data = useDataOverride($dataProp);\n const $actions = useActionsOverride($actionsProp);\n // Enforces the SessionRoot ancestor: useSession() throws when rendered outside one.\n const { state } = useSession();\n\n const [signOutPending, setSignOutPending] = useState(false);\n const [signOutError, setSignOutError] = useState<string | null>(null);\n\n async function handleSignOut() {\n setSignOutPending(true);\n setSignOutError(null);\n try {\n const errors: readonly SessionUserError[] = (await $actions?.session?.logout?.()) ?? [];\n if (errors.length > 0) setSignOutError(errors[0]?.message ?? signOutErrorMessage);\n } catch (error) {\n // A logout that throws rather than resolving userErrors would otherwise leave the shopper still\n // signed in with nothing on screen, and escape as an unhandled rejection.\n console.error('[IdentitySummary] logout failed:', loggableErrorName(error));\n setSignOutError(signOutErrorMessage);\n } finally {\n setSignOutPending(false);\n }\n }\n\n // Self-gate: nothing to show for an anonymous or unresolved session.\n if (state === 'anonymous') return null;\n\n const contextValue: IdentitySummaryContextValue = {\n state,\n firstName: $data?.firstName ?? '',\n lastName: $data?.lastName ?? '',\n email: $data?.email ?? '',\n phone: $data?.phone ?? '',\n document: $data?.document ?? '',\n handleSignOut,\n signOutPending,\n signOutError,\n };\n\n return (\n <IdentitySummaryContext.Provider value={contextValue}>\n <div\n className={className}\n data-fs-identity-summary=\"\"\n {...(signOutPending ? { 'data-fs-identity-summary-pending': '' } : {})}\n >\n {children}\n </div>\n </IdentitySummaryContext.Provider>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Read-only summary\n// ---------------------------------------------------------------------------\n\n/**\n * Read-only identity display: a session-state badge plus name, email, phone, and document.\n *\n * The props below configure the default composition only — composing children replaces it wholesale,\n * and a leaf placed there takes its own props (`IdentitySummaryPhone` its `country`,\n * `IdentitySummaryBadge` its labels). They are deliberately absent from the schema, so a page cannot\n * set one here and watch it disappear behind composed children.\n */\nexport function IdentitySummarySelectedSummary({\n country,\n identifiedBadgeLabel = 'Guest',\n loggedInBadgeLabel = 'Signed in',\n className,\n children,\n}: IdentitySummarySelectedSummaryProps) {\n return (\n <div className={className} data-fs-identity-summary-summary=\"\">\n {children ?? (\n <>\n <IdentitySummaryBadge identifiedLabel={identifiedBadgeLabel} loggedInLabel={loggedInBadgeLabel} />\n <IdentitySummaryName />\n <IdentitySummaryEmail />\n <IdentitySummaryPhone country={country} />\n <IdentitySummaryDocument />\n </>\n )}\n </div>\n );\n}\n\n/** Session-state badge. Renders `identifiedLabel` for a guest and `loggedInLabel` once authenticated. */\nexport function IdentitySummaryBadge({\n identifiedLabel = 'Guest',\n loggedInLabel = 'Signed in',\n className,\n}: IdentitySummaryBadgeProps) {\n const { state } = useIdentitySummaryContext();\n return (\n <Badge className={className} data-fs-identity-summary-badge=\"\" data-fs-identity-summary-state={state}>\n {state === 'loggedIn' ? loggedInLabel : identifiedLabel}\n </Badge>\n );\n}\n\n/** The shopper's full name. Renders nothing when the profile carries neither name. */\nexport function IdentitySummaryName({ className }: IdentitySummaryFieldProps) {\n const { firstName, lastName } = useIdentitySummaryContext();\n const fullName = [firstName, lastName].filter(Boolean).join(' ');\n if (!fullName) return null;\n return (\n <p className={className} data-fs-identity-summary-name=\"\">\n {fullName}\n </p>\n );\n}\n\n/** The shopper's e-mail. Renders nothing when absent. */\nexport function IdentitySummaryEmail({ className }: IdentitySummaryFieldProps) {\n const { email } = useIdentitySummaryContext();\n if (!email) return null;\n return (\n <p className={className} data-fs-identity-summary-email=\"\">\n {email}\n </p>\n );\n}\n\n/** E.164 prefixes for the countries the masks understand. */\nconst COUNTRY_PREFIX: Record<PhoneCountry, string> = { BR: '+55', US: '+1' };\n\n/**\n * The shopper's phone, masked for `country`. Renders nothing when absent, and renders the stored value\n * as-is whenever the mask does not apply to it — no country given, or a stored E.164 number belonging to\n * a different one. Each mask truncates to its own country's length, so applying the wrong one prints a\n * number that is not the shopper's, with nothing to signal that digits were dropped.\n */\nexport function IdentitySummaryPhone({ country, className }: IdentitySummaryPhoneProps) {\n const { phone } = useIdentitySummaryContext();\n if (!phone) return null;\n const maskApplies = country !== undefined && (!phone.startsWith('+') || phone.startsWith(COUNTRY_PREFIX[country]));\n return (\n <p className={className} data-fs-identity-summary-phone=\"\">\n {maskApplies && country ? applyPhoneMask(phone, country) : phone}\n </p>\n );\n}\n\n/** The shopper's tax document. Renders nothing when absent. */\nexport function IdentitySummaryDocument({ className }: IdentitySummaryFieldProps) {\n const { document } = useIdentitySummaryContext();\n if (!document) return null;\n return (\n <p className={className} data-fs-identity-summary-document=\"\">\n {document}\n </p>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Sign-out button + error (domain-coupled; the summary/form swap is IdentityEditController's)\n// ---------------------------------------------------------------------------\n\n/** Dispatches the sign-out mutation (async/pessimistic). */\nexport function IdentitySummarySignOutButton({\n label = 'Sign out',\n className,\n children,\n}: IdentitySummarySignOutButtonProps) {\n const { handleSignOut, signOutPending } = useIdentitySummaryContext();\n return (\n <button\n type=\"button\"\n data-fs-identity-summary-sign-out=\"\"\n className={className}\n disabled={signOutPending}\n {...(signOutPending ? { 'data-fs-identity-summary-pending': '' } : {})}\n onClick={handleSignOut}\n >\n {children ?? label}\n </button>\n );\n}\n\n/** Renders the inline sign-out user error, or nothing when there is none. */\nexport function IdentitySummaryError({ className }: IdentitySummaryErrorProps) {\n const { signOutError } = useIdentitySummaryContext();\n if (!signOutError) return null;\n return (\n <div role=\"alert\" className={className} data-fs-identity-summary-error=\"\">\n {signOutError}\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Namespace Export\n// ---------------------------------------------------------------------------\n\nexport const IdentitySummary = {\n Badge: IdentitySummaryBadge,\n BadgeDefinition: IdentitySummaryBadgeDefinition,\n Name: IdentitySummaryName,\n NameDefinition: IdentitySummaryNameDefinition,\n Email: IdentitySummaryEmail,\n EmailDefinition: IdentitySummaryEmailDefinition,\n Phone: IdentitySummaryPhone,\n PhoneDefinition: IdentitySummaryPhoneDefinition,\n Document: IdentitySummaryDocument,\n DocumentDefinition: IdentitySummaryDocumentDefinition,\n Root: IdentitySummaryRoot,\n RootDefinition: IdentitySummaryRootDefinition,\n SelectedSummary: IdentitySummarySelectedSummary,\n SelectedSummaryDefinition: IdentitySummarySelectedSummaryDefinition,\n SignOutButton: IdentitySummarySignOutButton,\n SignOutButtonDefinition: IdentitySummarySignOutButtonDefinition,\n Error: IdentitySummaryError,\n ErrorDefinition: IdentitySummaryErrorDefinition,\n};\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAM,WAAyB;;;;;;;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AI,CAAC,cAAc,OAAO;CAC1B,OACE,oBAAC,OAAD;EAAK,MAAK;EAAmB;EAAW,kCAA+B;EACpE,UAAA;CACE,CAAA;AAET;AAMA,MAAa,kBAAkB;CAC7B,OAAO;CACP,iBAAiB;CACjB,MAAM;CACN,gBAAgB;CAChB,OAAO;CACP,iBAAiB;CACjB,OAAO;CACP,iBAAiB;CACjB,UAAU;CACV,oBAAoB;CACpB,MAAM;CACN,gBAAgB;CAChB,iBAAiB;CACjB,2BAA2B;CAC3B,eAAe;CACf,yBAAyB;CACzB,OAAO;CACP,iBAAiB;AACnB"}
|
|
@@ -10,6 +10,9 @@ import { ComponentPropsWithRef, ReactNode } from "react";
|
|
|
10
10
|
* CustomerProfile` from the root-field selection for the reactive path (rfc-data-layer.md §"Entity
|
|
11
11
|
* fragments and schema introspection"), and `ReactiveDataProvider` publishes that entity data
|
|
12
12
|
* directly — the same convention `SessionRoot` reads `$data.loggedIn` under, not `$data.session`.
|
|
13
|
+
*
|
|
14
|
+
* `null` whenever `customerProfile` is: an anonymous session, or a signed-in read that failed. The
|
|
15
|
+
* Root treats it as unresolved data, so the first renders nothing and the second keeps the skeleton.
|
|
13
16
|
*/
|
|
14
17
|
export type MyAccountProfileData = {
|
|
15
18
|
id?: string | null;
|
|
@@ -5,6 +5,7 @@ import { Field } from "../../particles/field/field.js";
|
|
|
5
5
|
import { useActionsOverride } from "../../sdk/actions/actions-override-context.js";
|
|
6
6
|
import { useDataOverride } from "../../sdk/data/data-override-context.js";
|
|
7
7
|
import { useSession } from "../session/session.js";
|
|
8
|
+
import { loggableErrorName } from "../../utils/loggable-error-name.js";
|
|
8
9
|
import { Select } from "../../particles/select/select.js";
|
|
9
10
|
import { DocumentField, isSupportedDocumentType, isValidDocument, maskDocumentValue } from "../../particles/document-field/document-field.js";
|
|
10
11
|
import { Input } from "../../particles/input/input.js";
|
|
@@ -266,7 +267,7 @@ function MyAccountProfileRoot({ $data: $dataProp, $actions: $actionsProp, docume
|
|
|
266
267
|
type: "success"
|
|
267
268
|
});
|
|
268
269
|
} catch (error) {
|
|
269
|
-
console.error("[MyAccountProfileRoot] customerProfileUpdate failed", error
|
|
270
|
+
console.error("[MyAccountProfileRoot] customerProfileUpdate failed", loggableErrorName(error));
|
|
270
271
|
toast.add({
|
|
271
272
|
title: saveFailedMessage,
|
|
272
273
|
type: "error"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"my-account-profile.js","names":[],"sources":["../../../src/matter/my-account-profile/my-account-profile.tsx"],"sourcesContent":["'use client';\n\nimport { defineComponent } from '@vtex/fs-core';\nimport {\n type ChangeEvent,\n type ComponentPropsWithRef,\n createContext,\n type ReactNode,\n type SyntheticEvent,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport {\n DocumentField,\n isSupportedDocumentType,\n isValidDocument,\n maskDocumentValue,\n} from '../../particles/document-field/document-field.js';\nimport { Field } from '../../particles/field/field.js';\nimport { Input } from '../../particles/input/input.js';\nimport {\n applyPhoneMask,\n type PhoneCountry,\n PhoneField,\n toE164,\n validatePhoneNumber,\n} from '../../particles/phone-field/phone-field.js';\nimport { Select } from '../../particles/select/select.js';\nimport { useToast } from '../../particles/toast/toast.js';\nimport { useActionsOverride } from '../../sdk/actions/actions-override-context.js';\nimport type { ComponentActions } from '../../sdk/actions/types.js';\nimport { useDataOverride } from '../../sdk/data/data-override-context.js';\nimport type { CustomerProfileUserError } from '../../sdk/identity/operations.js';\nimport { useSession } from '../session/session.js';\n\n/**\n * The `my-account-profile` compound (see my-account-profile.md; spec archived at the specs-archive tag) — the data root\n * plus form mechanics for the shopper's persistent account profile. `Root` owns the saved profile,\n * the draft, the view↔edit toggle, and the single batched Save; it publishes a context whose\n * registration API is the seam every field Control attaches to.\n *\n * Unlike `ClientProfileFormRoot`, the Root does not enumerate the field set: a Control registers\n * its key plus an optional validator and normalizer, and the Root derives which fields to validate,\n * which to send, and which to focus from the live registry only. A field absent from the\n * composition is absent from the payload by construction (Decision 1).\n */\n\n// ---------------------------------------------------------------------------\n// GraphQL fragment — raw literal, outside codegen (Decision 8)\n// ---------------------------------------------------------------------------\n\nconst fragment = /* GraphQL */ `\n fragment MyAccountProfileData on Query {\n customerProfile {\n __typename\n id\n firstName\n lastName\n email\n homePhone\n mobilePhone\n document\n documentType\n birthDate\n gender\n }\n }\n`;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * The `$data` slice forwarded by the reactive runtime — the `customerProfile` entity itself, not the\n * `Query` shape the fragment above is authored against. The compiler derives an entity fragment `on\n * CustomerProfile` from the root-field selection for the reactive path (rfc-data-layer.md §\"Entity\n * fragments and schema introspection\"), and `ReactiveDataProvider` publishes that entity data\n * directly — the same convention `SessionRoot` reads `$data.loggedIn` under, not `$data.session`.\n */\nexport type MyAccountProfileData = {\n id?: string | null;\n firstName?: string | null;\n lastName?: string | null;\n email?: string | null;\n homePhone?: string | null;\n mobilePhone?: string | null;\n document?: string | null;\n documentType?: string | null;\n birthDate?: string | null;\n gender?: string | null;\n} | null;\n\n/**\n * The shopper-editable keys. `email` is absent (login identifier) and `documentType` is absent\n * (read for the tax-ID control's active type; not writable in V0).\n */\nexport type MyAccountProfileFieldKey =\n | 'firstName'\n | 'lastName'\n | 'homePhone'\n | 'mobilePhone'\n | 'document'\n | 'birthDate'\n | 'gender';\n\nconst FIELD_KEYS: readonly MyAccountProfileFieldKey[] = [\n 'firstName',\n 'lastName',\n 'homePhone',\n 'mobilePhone',\n 'document',\n 'birthDate',\n 'gender',\n];\n\nexport type MyAccountProfileMode = 'view' | 'edit';\n\n/** Every editable key, always a string — a `null` upstream value is seeded as `''`. */\nexport type MyAccountProfileValues = Readonly<Record<MyAccountProfileFieldKey, string>>;\n\n/**\n * What a Control hands the Root. `validate` returns a message when the value is unacceptable and\n * `null` when it is fine — requiredness is expressed as a validator that rejects `''`. `normalize`\n * is applied on Save, to dirty values only.\n */\nexport type MyAccountProfileFieldRegistration = Readonly<{\n key: MyAccountProfileFieldKey;\n validate?: (value: string) => string | null;\n normalize?: (value: string) => string;\n}>;\n\nexport type MyAccountProfileFieldErrors = Readonly<Partial<Record<MyAccountProfileFieldKey, string>>>;\n\nexport type MyAccountProfileContextValue = Readonly<{\n mode: MyAccountProfileMode;\n savedValues: MyAccountProfileValues;\n draft: MyAccountProfileValues;\n fieldErrors: MyAccountProfileFieldErrors;\n email: string;\n activeDocumentType: string | undefined;\n pending: boolean;\n registerField: (registration: MyAccountProfileFieldRegistration) => () => void;\n setField: (key: MyAccountProfileFieldKey, value: string) => void;\n edit: () => void;\n cancel: () => void;\n}>;\n\nexport type MyAccountProfileRootProps = Readonly<{\n /** Store-configured tax-ID type fallback, used when the saved `documentType` is not registered. */\n documentType?: string;\n saveFailedMessage?: string;\n savedMessage?: string;\n className?: string;\n children?: ReactNode;\n $data?: MyAccountProfileData;\n /** Compiler-injected action surface; carries `identity.customerProfileUpdate`. */\n $actions?: ComponentActions;\n}>;\n\nexport type MyAccountProfileEditButtonProps = Readonly<{ label?: string; className?: string; children?: ReactNode }>;\nexport type MyAccountProfileSaveButtonProps = Readonly<{ label?: string; className?: string; children?: ReactNode }>;\nexport type MyAccountProfileCancelButtonProps = Readonly<{\n label?: string;\n className?: string;\n children?: ReactNode;\n}>;\nexport type MyAccountProfileEmailProps = Readonly<{ className?: string }>;\n\nconst DEFAULT_SAVE_FAILED_MESSAGE = 'Unable to save your profile. Please try again.';\nconst DEFAULT_SAVED_MESSAGE = 'Your profile has been saved.';\n\nfunction buildSavedValues($data: MyAccountProfileData | undefined): MyAccountProfileValues {\n return {\n firstName: $data?.firstName ?? '',\n lastName: $data?.lastName ?? '',\n homePhone: $data?.homePhone ?? '',\n mobilePhone: $data?.mobilePhone ?? '',\n document: $data?.document ?? '',\n birthDate: $data?.birthDate ?? '',\n gender: $data?.gender ?? '',\n };\n}\n\n/**\n * Native `<input type=\"date\">` values and the profile's stored `birthDate` are both `yyyy-mm-dd`.\n * `toNativeDate` stays defensive against a `yyyy-mm-ddTHH:mm:ss...` upstream value slipping through\n * unnormalized — the resolver already strips the time component, this is a second line of defense —\n * since the native input rejects anything but the date-only form outright.\n */\nfunction toNativeDate(stored: string): string {\n const [datePart] = stored.split('T');\n return datePart ?? '';\n}\nfunction toStoredDate(native: string): string {\n return native;\n}\n\nconst DEFAULT_GENDER_OPTIONS: readonly MyAccountProfileGenderOption[] = [\n { value: 'female', label: 'Female' },\n { value: 'male', label: 'Male' },\n { value: 'other', label: 'Other' },\n { value: 'prefer_not_to_say', label: 'Prefer not to say' },\n];\n\n// ---------------------------------------------------------------------------\n// Context — Root publishes the draft + registration API to its Controls\n// ---------------------------------------------------------------------------\n\nconst MY_ACCOUNT_PROFILE_UNSET = Symbol('MyAccountProfileContextUnset');\n\nconst MyAccountProfileContext = createContext<MyAccountProfileContextValue | typeof MY_ACCOUNT_PROFILE_UNSET>(\n MY_ACCOUNT_PROFILE_UNSET,\n);\n\n/** Throws when used outside `MyAccountProfileRoot`, per ADR-0009. */\nexport function useMyAccountProfile(): MyAccountProfileContextValue {\n const ctx = useContext(MyAccountProfileContext);\n if (ctx === MY_ACCOUNT_PROFILE_UNSET) {\n throw new Error('MyAccountProfile components must be used inside MyAccountProfileRoot.');\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Root\n// ---------------------------------------------------------------------------\n\nexport const MyAccountProfileRootDefinition = defineComponent<MyAccountProfileRootProps>({\n name: 'MyAccountProfileRoot',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileRoot,\n fragment,\n fetchStrategy: 'reactive',\n requiresContext: 'session',\n providesContext: 'my-account-profile',\n actions: { identity: ['customerProfileUpdate'] },\n skeleton: MyAccountProfileSkeleton,\n editor: { label: 'My Account Profile Root', category: 'identity' },\n schema: {\n documentType: { type: 'string', label: 'Default document type (e.g. CPF)' },\n saveFailedMessage: {\n type: 'string',\n default: 'Unable to save your profile. Please try again.',\n label: 'Save failure message',\n },\n savedMessage: {\n type: 'string',\n default: 'Your profile has been saved.',\n label: 'Save success message',\n },\n },\n guideline:\n 'Data root + form mechanics for the persistent My Account profile: owns the saved profile, the draft, the view/edit toggle, and the single batched Save (dispatches only dirty, registered fields; an empty string erases, an omitted field is untouched). Self-gates on the authenticated (loggedIn) session; requires a SessionRoot ancestor and a mounted ToastProvider ancestor — Save success/failure surface as a toast, not an inline part. Field Controls register their key plus an optional validator and normalizer through useMyAccountProfile() — the field set is a merchant composition decision, never enumerated here. Compose EditButton (view state), SaveButton/CancelButton (edit state), and Email as children in any order. See my-account-profile.md.',\n});\n\nexport function MyAccountProfileRoot({\n $data: $dataProp,\n $actions: $actionsProp,\n documentType: documentTypeProp,\n saveFailedMessage = DEFAULT_SAVE_FAILED_MESSAGE,\n savedMessage = DEFAULT_SAVED_MESSAGE,\n className,\n children,\n}: MyAccountProfileRootProps) {\n // Enforces the SessionRoot ancestor: useSession() throws when rendered outside one.\n const { state } = useSession();\n // Enforces the ToastProvider ancestor: useToast() throws when rendered outside one (Decision 10).\n const toast = useToast();\n const $data = useDataOverride($dataProp);\n const $actions = useActionsOverride($actionsProp);\n const resolved = $data != null;\n\n const savedValues = useMemo(() => buildSavedValues($data), [$data]);\n const savedEmail = $data?.email ?? '';\n const savedDocumentType = $data?.documentType?.toUpperCase();\n const activeDocumentType =\n savedDocumentType && isSupportedDocumentType(savedDocumentType) ? savedDocumentType : documentTypeProp;\n\n const [mode, setMode] = useState<MyAccountProfileMode>('view');\n const [draft, setDraft] = useState<MyAccountProfileValues>(savedValues);\n const [fieldErrors, setFieldErrors] = useState<MyAccountProfileFieldErrors>({});\n const [pending, setPending] = useState(false);\n const [registry, setRegistry] = useState<ReadonlyMap<MyAccountProfileFieldKey, MyAccountProfileFieldRegistration>>(\n () => new Map(),\n );\n\n const formRef = useRef<HTMLFormElement>(null);\n\n // Re-seed pristine fields when the saved profile changes underneath an open edit; a field the\n // shopper has touched (draft no longer equals the previous saved value) is never clobbered. Runs\n // during render (previous-saved in state, not a ref) so the re-seed lands in the same commit.\n const [prevSaved, setPrevSaved] = useState(savedValues);\n const changedKeys = FIELD_KEYS.filter((key) => prevSaved[key] !== savedValues[key]);\n if (changedKeys.length > 0) {\n setPrevSaved(savedValues);\n setDraft((prevDraft) => {\n let next = prevDraft;\n for (const key of changedKeys) {\n if (prevDraft[key] !== prevSaved[key]) continue;\n if (next === prevDraft) next = { ...prevDraft };\n (next as Record<MyAccountProfileFieldKey, string>)[key] = savedValues[key];\n }\n return next;\n });\n }\n\n const registerField = useCallback((registration: MyAccountProfileFieldRegistration) => {\n setRegistry((prev) => {\n const next = new Map(prev);\n next.set(registration.key, registration);\n return next;\n });\n return () => {\n setRegistry((prev) => {\n if (!prev.has(registration.key)) return prev;\n const next = new Map(prev);\n next.delete(registration.key);\n return next;\n });\n };\n }, []);\n\n const setField = useCallback((key: MyAccountProfileFieldKey, value: string) => {\n setDraft((prev) => ({ ...prev, [key]: value }));\n setFieldErrors((prev) => {\n if (!prev[key]) return prev;\n const next = { ...prev };\n delete next[key];\n return next;\n });\n }, []);\n\n // Opening an edit always starts from the latest truth, so a value the server normalized (e.g. a\n // reformatted phone) on a previous save is what the shopper sees, not their own stale keystrokes.\n const edit = useCallback(() => {\n setDraft(savedValues);\n setFieldErrors({});\n setMode('edit');\n }, [savedValues]);\n\n const cancel = useCallback(() => {\n setDraft(savedValues);\n setFieldErrors({});\n setMode('view');\n }, [savedValues]);\n\n function focusFirstInvalid(errors: MyAccountProfileFieldErrors) {\n const wrappers = formRef.current?.querySelectorAll<HTMLElement>('[data-fs-my-account-profile-field]');\n if (!wrappers) return;\n for (const wrapper of wrappers) {\n const key = wrapper.dataset.fsMyAccountProfileField as MyAccountProfileFieldKey | undefined;\n if (key && errors[key]) {\n const target = wrapper.querySelector<HTMLElement>('input, select, textarea') ?? wrapper;\n target.focus();\n return;\n }\n }\n }\n\n async function handleSubmit(event: SyntheticEvent<HTMLFormElement>) {\n event.preventDefault();\n if (pending) return;\n\n const dirtyKeys = Array.from(registry.keys()).filter((key) => draft[key] !== savedValues[key]);\n if (dirtyKeys.length === 0) {\n setFieldErrors({});\n setMode('view');\n toast.add({ title: savedMessage, type: 'success' });\n return;\n }\n\n // Validate only the fields the shopper actually changed (Decision 9, product-confirmed): a\n // stale invalid value the shopper never touched must not block an unrelated field's save.\n const errors: Record<string, string> = {};\n for (const key of dirtyKeys) {\n const registration = registry.get(key);\n const message = registration?.validate?.(draft[key]);\n if (message) errors[key] = message;\n }\n if (Object.keys(errors).length > 0) {\n setFieldErrors(errors as MyAccountProfileFieldErrors);\n focusFirstInvalid(errors as MyAccountProfileFieldErrors);\n return;\n }\n setFieldErrors({});\n\n const identity = $actions?.identity;\n if (!identity?.customerProfileUpdate) {\n // A composition/platform gap (the provider chain never delivered customerProfileUpdate) is\n // otherwise indistinguishable from a dead button — surface it the same way a rejected write\n // would, rather than returning silently.\n toast.add({ title: saveFailedMessage, type: 'error' });\n return;\n }\n\n const payload: Partial<Record<MyAccountProfileFieldKey, string>> = {};\n for (const key of dirtyKeys) {\n const registration = registry.get(key);\n const rawValue = draft[key];\n payload[key] = registration?.normalize ? registration.normalize(rawValue) : rawValue;\n }\n\n setPending(true);\n try {\n const userErrors: readonly CustomerProfileUserError[] = await identity.customerProfileUpdate(payload);\n if (userErrors.length > 0) {\n toast.add({ title: userErrors[0]?.message ?? saveFailedMessage, type: 'error' });\n return;\n }\n setMode('view');\n toast.add({ title: savedMessage, type: 'success' });\n } catch (error) {\n // Log only the error name — the message can echo a submitted profile value (PII).\n console.error(\n '[MyAccountProfileRoot] customerProfileUpdate failed',\n error instanceof Error ? error.name : 'UnknownError',\n );\n toast.add({ title: saveFailedMessage, type: 'error' });\n } finally {\n setPending(false);\n }\n }\n\n const contextValue = useMemo<MyAccountProfileContextValue>(\n () => ({\n mode,\n savedValues,\n draft,\n fieldErrors,\n email: savedEmail,\n activeDocumentType,\n pending,\n registerField,\n setField,\n edit,\n cancel,\n }),\n [\n mode,\n savedValues,\n draft,\n fieldErrors,\n savedEmail,\n activeDocumentType,\n pending,\n registerField,\n setField,\n edit,\n cancel,\n ],\n );\n\n // Self-gate: an anonymous or identified-but-not-authenticated session never reaches the DOM,\n // even if the topology's SessionGuard is missing (US-5).\n if (state !== 'loggedIn') return null;\n\n // Empty is a post-resolution state — the skeleton renders while $data is unresolved, never an\n // empty summary.\n if (!resolved) return <MyAccountProfileSkeleton className={className} />;\n\n return (\n <MyAccountProfileContext value={contextValue}>\n <form\n ref={formRef}\n onSubmit={handleSubmit}\n className={className}\n data-fs-my-account-profile=\"\"\n data-fs-my-account-profile-mode={mode}\n {...(pending ? { 'data-fs-my-account-profile-pending': '' } : {})}\n >\n {children}\n </form>\n </MyAccountProfileContext>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Frame parts\n// ---------------------------------------------------------------------------\n\nexport const MyAccountProfileEditButtonDefinition = defineComponent<MyAccountProfileEditButtonProps>({\n name: 'MyAccountProfileEditButton',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileEditButton,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Edit Button', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Edit', label: 'Button label' },\n },\n guideline:\n 'Switches MyAccountProfileRoot from the view state to the edit state. Renders only in the view state. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileEditButton({ label = 'Edit', className, children }: MyAccountProfileEditButtonProps) {\n const { mode, edit } = useMyAccountProfile();\n if (mode !== 'view') return null;\n return (\n <button type=\"button\" onClick={edit} className={className} data-fs-my-account-profile-edit=\"\">\n {children ?? label}\n </button>\n );\n}\n\nexport const MyAccountProfileSaveButtonDefinition = defineComponent<MyAccountProfileSaveButtonProps>({\n name: 'MyAccountProfileSaveButton',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileSaveButton,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Save Button', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Save', label: 'Button label' },\n },\n guideline:\n \"Submits MyAccountProfileRoot's batched Save. Renders only in the edit state; disabled while the write is pending. Must be a descendant of MyAccountProfileRoot.\",\n});\n\nexport function MyAccountProfileSaveButton({ label = 'Save', className, children }: MyAccountProfileSaveButtonProps) {\n const { mode, pending } = useMyAccountProfile();\n if (mode !== 'edit') return null;\n return (\n <button type=\"submit\" disabled={pending} className={className} data-fs-my-account-profile-save=\"\">\n {children ?? label}\n </button>\n );\n}\n\nexport const MyAccountProfileCancelButtonDefinition = defineComponent<MyAccountProfileCancelButtonProps>({\n name: 'MyAccountProfileCancelButton',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileCancelButton,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Cancel Button', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Cancel', label: 'Button label' },\n },\n guideline:\n 'Reverts every field to its last saved value and returns MyAccountProfileRoot to the view state, without persisting. Renders only in the edit state; disabled while the write is pending. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileCancelButton({\n label = 'Cancel',\n className,\n children,\n}: MyAccountProfileCancelButtonProps) {\n const { mode, pending, cancel } = useMyAccountProfile();\n if (mode !== 'edit') return null;\n return (\n <button\n type=\"button\"\n disabled={pending}\n onClick={cancel}\n className={className}\n data-fs-my-account-profile-cancel=\"\"\n >\n {children ?? label}\n </button>\n );\n}\n\nexport const MyAccountProfileEmailDefinition = defineComponent<MyAccountProfileEmailProps>({\n name: 'MyAccountProfileEmail',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileEmail,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Email', category: 'identity' },\n schema: {},\n guideline:\n \"The shopper's read-only login identifier, or nothing when absent. Never editable — no edit-state rendering exists for it. Must be a descendant of MyAccountProfileRoot.\",\n});\n\nexport function MyAccountProfileEmail({ className }: MyAccountProfileEmailProps) {\n const { email } = useMyAccountProfile();\n if (!email) return null;\n return (\n <p className={className} data-fs-my-account-profile-email=\"\">\n {email}\n </p>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Skeleton — no context: it is rendered directly by the Root before any Provider exists\n// (mirrors ProductShelfSkeleton / PricingSkeleton; see spec deviation note).\n// ---------------------------------------------------------------------------\n\nexport const MyAccountProfileSkeletonDefinition = defineComponent<ComponentPropsWithRef<'div'>>({\n name: 'MyAccountProfileSkeleton',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileSkeleton,\n editor: { label: 'My Account Profile Skeleton', category: 'identity' },\n schema: {},\n guideline:\n 'Loading placeholder rendered by MyAccountProfileRoot while $data is unresolved. Declares no context requirement — it renders before the Root has anything to provide.',\n});\n\nexport function MyAccountProfileSkeleton({ className, ...props }: ComponentPropsWithRef<'div'>) {\n return (\n <div {...props} className={className} data-fs-my-account-profile-skeleton=\"\" aria-hidden=\"true\">\n <span data-fs-my-account-profile-skeleton-line=\"\" />\n <span data-fs-my-account-profile-skeleton-line=\"\" />\n <span data-fs-my-account-profile-skeleton-line=\"\" />\n </div>\n );\n}\n\nMyAccountProfileRoot.Skeleton = MyAccountProfileSkeleton;\n\n// ---------------------------------------------------------------------------\n// Field Controls\n//\n// Each Control is a thin binding over an existing presentational particle: it registers with the\n// Root's registration seam in an effect, reads its value off `mode` (savedValues in view, draft in\n// edit), writes through `setField`, and wraps its input in an element carrying\n// `data-fs-my-account-profile-field` — the Root's DOM-order focus seam. None persists on its own.\n// ---------------------------------------------------------------------------\n\nexport type MyAccountProfileFirstNameControlProps = Readonly<{\n label?: string;\n requiredMessage?: string;\n className?: string;\n}>;\n\nexport const MyAccountProfileFirstNameControlDefinition = defineComponent<MyAccountProfileFirstNameControlProps>({\n name: 'MyAccountProfileFirstNameControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileFirstNameControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile First Name Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'First name', label: 'Label' },\n requiredMessage: { type: 'string', default: 'First name is required.', label: 'Required message' },\n },\n guideline:\n 'Draft-bound, required first-name field. Blocks Save with an inline message and focus when left empty. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileFirstNameControl({\n label = 'First name',\n requiredMessage = 'First name is required.',\n className,\n}: MyAccountProfileFirstNameControlProps) {\n const { mode, draft, savedValues, fieldErrors, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({ key: 'firstName', validate: (value) => (value.trim() ? null : requiredMessage) });\n }, [requiredMessage, registerField]);\n\n const error = fieldErrors.firstName;\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-first-name=\"\" data-fs-my-account-profile-field=\"firstName\">\n {savedValues.firstName}\n </p>\n );\n }\n\n return (\n <Field.Root\n className={className}\n invalid={!!error}\n disabled={pending}\n data-fs-my-account-profile-first-name=\"\"\n data-fs-my-account-profile-field=\"firstName\"\n >\n <Field.Label>{label}</Field.Label>\n <Field.Control\n value={draft.firstName}\n onChange={(event) => setField('firstName', event.target.value)}\n disabled={pending}\n />\n {error ? <Field.Error match>{error}</Field.Error> : null}\n </Field.Root>\n );\n}\n\nexport type MyAccountProfileLastNameControlProps = Readonly<{\n label?: string;\n requiredMessage?: string;\n className?: string;\n}>;\n\nexport const MyAccountProfileLastNameControlDefinition = defineComponent<MyAccountProfileLastNameControlProps>({\n name: 'MyAccountProfileLastNameControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileLastNameControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Last Name Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Last name', label: 'Label' },\n requiredMessage: { type: 'string', default: 'Last name is required.', label: 'Required message' },\n },\n guideline:\n 'Draft-bound, required last-name field. Blocks Save with an inline message and focus when left empty. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileLastNameControl({\n label = 'Last name',\n requiredMessage = 'Last name is required.',\n className,\n}: MyAccountProfileLastNameControlProps) {\n const { mode, draft, savedValues, fieldErrors, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({ key: 'lastName', validate: (value) => (value.trim() ? null : requiredMessage) });\n }, [requiredMessage, registerField]);\n\n const error = fieldErrors.lastName;\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-last-name=\"\" data-fs-my-account-profile-field=\"lastName\">\n {savedValues.lastName}\n </p>\n );\n }\n\n return (\n <Field.Root\n className={className}\n invalid={!!error}\n disabled={pending}\n data-fs-my-account-profile-last-name=\"\"\n data-fs-my-account-profile-field=\"lastName\"\n >\n <Field.Label>{label}</Field.Label>\n <Field.Control\n value={draft.lastName}\n onChange={(event) => setField('lastName', event.target.value)}\n disabled={pending}\n />\n {error ? <Field.Error match>{error}</Field.Error> : null}\n </Field.Root>\n );\n}\n\nexport type MyAccountProfilePhoneControlProps = Readonly<{\n label?: string;\n /** Which draft key this instance binds. Compose the Control twice to expose both numbers. */\n field?: 'homePhone' | 'mobilePhone';\n country?: PhoneCountry;\n invalidMessage?: string;\n className?: string;\n}>;\n\nexport const MyAccountProfilePhoneControlDefinition = defineComponent<MyAccountProfilePhoneControlProps>({\n name: 'MyAccountProfilePhoneControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfilePhoneControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Phone Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Phone', label: 'Label' },\n field: { type: ['homePhone', 'mobilePhone'] as const, default: 'mobilePhone', label: 'Bound field' },\n country: { type: ['US', 'BR'] as const, default: 'US', label: 'Country' },\n invalidMessage: { type: 'string', default: 'Invalid phone number', label: 'Invalid message' },\n },\n guideline:\n \"Draft-bound, optional phone field bound to either homePhone or mobilePhone via the field prop (Decision 1) — compose it twice to expose both numbers. Normalizes to E.164 on the Root's Save. Absent from the composition means absent from the payload. Must be a descendant of MyAccountProfileRoot.\",\n});\n\nexport function MyAccountProfilePhoneControl({\n label = 'Phone',\n field = 'mobilePhone',\n country = 'US',\n invalidMessage = 'Invalid phone number',\n className,\n}: MyAccountProfilePhoneControlProps) {\n const { mode, draft, savedValues, fieldErrors, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({\n key: field,\n validate: (value) => (value.trim() && !validatePhoneNumber(value, country) ? invalidMessage : null),\n normalize: (value) => (value.trim() ? toE164(value, country) : value),\n });\n }, [field, country, invalidMessage, registerField]);\n\n const error = fieldErrors[field];\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-phone={field} data-fs-my-account-profile-field={field}>\n {savedValues[field] ? applyPhoneMask(savedValues[field], country) : ''}\n </p>\n );\n }\n\n return (\n <div data-fs-my-account-profile-field={field}>\n <PhoneField\n className={className}\n label={label}\n country={country}\n requirement=\"optional\"\n value={draft[field]}\n onValueChange={(value) => setField(field, value)}\n invalid={!!error}\n error={error ?? undefined}\n errorInvalid={invalidMessage}\n isDisabled={pending}\n data-fs-my-account-profile-phone={field}\n />\n </div>\n );\n}\n\nexport type MyAccountProfileTaxIdControlProps = Readonly<{\n label?: string;\n invalidMessage?: string;\n /** Inline reason shown beside the locked saved CPF. */\n lockedReason?: string;\n className?: string;\n}>;\n\nexport const MyAccountProfileTaxIdControlDefinition = defineComponent<MyAccountProfileTaxIdControlProps>({\n name: 'MyAccountProfileTaxIdControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileTaxIdControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Tax ID Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'National tax ID', label: 'Label' },\n invalidMessage: { type: 'string', default: 'Invalid document number.', label: 'Invalid message' },\n lockedReason: { type: 'string', default: \"Your document ID can't be edited.\", label: 'Locked reason' },\n },\n guideline:\n \"Draft-bound, optional national tax-ID field (CPF in V0). Self-gates on the Root's active document type. A saved value renders as a disabled, locked input in the edit state rather than disappearing (Decision 4); an unsaved value renders as an editable field. Must be a descendant of MyAccountProfileRoot.\",\n});\n\nexport function MyAccountProfileTaxIdControl({\n label = 'National tax ID',\n invalidMessage = 'Invalid document number.',\n lockedReason = \"Your document ID can't be edited.\",\n className,\n}: MyAccountProfileTaxIdControlProps) {\n const { mode, draft, savedValues, fieldErrors, pending, activeDocumentType, registerField, setField } =\n useMyAccountProfile();\n const documentType =\n activeDocumentType && isSupportedDocumentType(activeDocumentType) ? activeDocumentType : undefined;\n const hasSavedDocument = savedValues.document.trim() !== '';\n\n useEffect(() => {\n if (!documentType || hasSavedDocument) return;\n return registerField({\n key: 'document',\n validate: (value) => (value.trim() && !isValidDocument(value, documentType) ? invalidMessage : null),\n // DocumentField reports back the masked value (e.g. `111.444.777-35`); strip the punctuation\n // before it reaches the API, matching the checkout form's `stripNonDigits`.\n normalize: (value) => value.replaceAll(/\\D/g, ''),\n });\n }, [documentType, hasSavedDocument, invalidMessage, registerField]);\n\n if (!documentType) return null;\n\n const error = fieldErrors.document;\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-tax-id=\"\" data-fs-my-account-profile-field=\"document\">\n {savedValues.document ? maskDocumentValue(savedValues.document, documentType) : ''}\n </p>\n );\n }\n\n if (hasSavedDocument) {\n return (\n <Field.Root\n className={className}\n data-fs-my-account-profile-tax-id=\"\"\n data-fs-my-account-profile-field=\"document\"\n >\n <Field.Label>{label}</Field.Label>\n <Field.Control\n readOnly\n aria-disabled=\"true\"\n title={lockedReason}\n value={maskDocumentValue(savedValues.document, documentType)}\n data-fs-my-account-profile-tax-id-readonly=\"\"\n />\n <Field.Description>{lockedReason}</Field.Description>\n </Field.Root>\n );\n }\n\n return (\n <DocumentField\n className={className}\n label={label}\n documentType={documentType}\n value={draft.document}\n onValueChange={(value) => setField('document', value)}\n invalid={!!error}\n errorMessage={error}\n disabled={pending}\n data-fs-my-account-profile-tax-id=\"\"\n data-fs-my-account-profile-field=\"document\"\n />\n );\n}\n\nexport type MyAccountProfileBirthDateControlProps = Readonly<{ label?: string; className?: string }>;\n\nexport const MyAccountProfileBirthDateControlDefinition = defineComponent<MyAccountProfileBirthDateControlProps>({\n name: 'MyAccountProfileBirthDateControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileBirthDateControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Birth Date Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Birth date', label: 'Label' },\n },\n guideline:\n 'Draft-bound, optional birth-date field over a native date input. Maps the native yyyy-mm-dd value to the stored profile format on read and write. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileBirthDateControl({\n label = 'Birth date',\n className,\n}: MyAccountProfileBirthDateControlProps) {\n const { mode, draft, savedValues, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({ key: 'birthDate', normalize: (value) => toStoredDate(value) });\n }, [registerField]);\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-birth-date=\"\" data-fs-my-account-profile-field=\"birthDate\">\n {savedValues.birthDate}\n </p>\n );\n }\n\n function handleChange(event: ChangeEvent<HTMLInputElement>) {\n setField('birthDate', toStoredDate(event.target.value));\n }\n\n return (\n <Field.Root\n className={className}\n data-fs-my-account-profile-birth-date=\"\"\n data-fs-my-account-profile-field=\"birthDate\"\n >\n <Field.Label>{label}</Field.Label>\n <Input type=\"date\" value={toNativeDate(draft.birthDate)} onChange={handleChange} disabled={pending} />\n </Field.Root>\n );\n}\n\nexport type MyAccountProfileGenderOption = Readonly<{ value: string; label: string }>;\n\nexport type MyAccountProfileGenderControlProps = Readonly<{\n label?: string;\n placeholder?: string;\n clearLabel?: string;\n options?: readonly MyAccountProfileGenderOption[];\n className?: string;\n}>;\n\nexport const MyAccountProfileGenderControlDefinition = defineComponent<MyAccountProfileGenderControlProps>({\n name: 'MyAccountProfileGenderControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileGenderControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Gender Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Gender', label: 'Label' },\n placeholder: { type: 'string', default: 'Select', label: 'Placeholder' },\n clearLabel: { type: 'string', default: 'Clear', label: 'Clear button label' },\n },\n guideline:\n 'Draft-bound, optional gender field over a store-configurable set of options (the options prop). Free-string storage — no server-side enum. A Clear button erases a selected value back to empty, since the Select itself offers no such option. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileGenderControl({\n label = 'Gender',\n placeholder = 'Select',\n clearLabel = 'Clear',\n options = DEFAULT_GENDER_OPTIONS,\n className,\n}: MyAccountProfileGenderControlProps) {\n const { mode, draft, savedValues, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({ key: 'gender' });\n }, [registerField]);\n\n if (mode === 'view') {\n const selected = options.find((option) => option.value === savedValues.gender);\n return (\n <p className={className} data-fs-my-account-profile-gender=\"\" data-fs-my-account-profile-field=\"gender\">\n {selected?.label ?? savedValues.gender}\n </p>\n );\n }\n\n return (\n <div className={className} data-fs-my-account-profile-gender=\"\" data-fs-my-account-profile-field=\"gender\">\n <Select.Root value={draft.gender} onValueChange={(value) => setField('gender', value ?? '')} disabled={pending}>\n <Select.Label>{label}</Select.Label>\n <Select.Trigger>\n <Select.Value placeholder={placeholder} />\n <Select.Icon />\n </Select.Trigger>\n <Select.Portal>\n <Select.Positioner>\n <Select.Popup>\n <Select.List>\n {options.map((option) => (\n <Select.Item key={option.value} value={option.value}>\n <Select.ItemText>{option.label}</Select.ItemText>\n </Select.Item>\n ))}\n </Select.List>\n </Select.Popup>\n </Select.Positioner>\n </Select.Portal>\n </Select.Root>\n {draft.gender ? (\n <button\n type=\"button\"\n onClick={() => setField('gender', '')}\n disabled={pending}\n data-fs-my-account-profile-gender-clear=\"\"\n >\n {clearLabel}\n </button>\n ) : null}\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Namespace export\n// ---------------------------------------------------------------------------\n\nexport const MyAccountProfile = {\n Root: MyAccountProfileRoot,\n RootDefinition: MyAccountProfileRootDefinition,\n EditButton: MyAccountProfileEditButton,\n EditButtonDefinition: MyAccountProfileEditButtonDefinition,\n SaveButton: MyAccountProfileSaveButton,\n SaveButtonDefinition: MyAccountProfileSaveButtonDefinition,\n CancelButton: MyAccountProfileCancelButton,\n CancelButtonDefinition: MyAccountProfileCancelButtonDefinition,\n Email: MyAccountProfileEmail,\n EmailDefinition: MyAccountProfileEmailDefinition,\n Skeleton: MyAccountProfileSkeleton,\n SkeletonDefinition: MyAccountProfileSkeletonDefinition,\n FirstNameControl: MyAccountProfileFirstNameControl,\n FirstNameControlDefinition: MyAccountProfileFirstNameControlDefinition,\n LastNameControl: MyAccountProfileLastNameControl,\n LastNameControlDefinition: MyAccountProfileLastNameControlDefinition,\n PhoneControl: MyAccountProfilePhoneControl,\n PhoneControlDefinition: MyAccountProfilePhoneControlDefinition,\n TaxIdControl: MyAccountProfileTaxIdControl,\n TaxIdControlDefinition: MyAccountProfileTaxIdControlDefinition,\n BirthDateControl: MyAccountProfileBirthDateControl,\n BirthDateControlDefinition: MyAccountProfileBirthDateControlDefinition,\n GenderControl: MyAccountProfileGenderControl,\n GenderControlDefinition: MyAccountProfileGenderControlDefinition,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,WAAyB;;;;;;;;;;;;;;;;;AAuD/B,MAAM,aAAkD;CACtD;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAuDA,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAE9B,SAAS,iBAAiB,OAAiE;CACzF,OAAO;EACL,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,WAAW,OAAO,aAAa;EAC/B,aAAa,OAAO,eAAe;EACnC,UAAU,OAAO,YAAY;EAC7B,WAAW,OAAO,aAAa;EAC/B,QAAQ,OAAO,UAAU;CAC3B;AACF;;;;;;;AAQA,SAAS,aAAa,QAAwB;CAC5C,MAAM,CAAC,YAAY,OAAO,MAAM,GAAG;CACnC,OAAO,YAAY;AACrB;AACA,SAAS,aAAa,QAAwB;CAC5C,OAAO;AACT;AAEA,MAAM,yBAAkE;CACtE;EAAE,OA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GAAvG,UAAA;IACE,oBAAC,OAAO,OAAR,EAAA,UAAe,MAAoB,CAAA;IACnC,qBAAC,OAAO,SAAR,EAAA,UAAA,CACE,oBAAC,OAAO,OAAR,EAA2B,YAAc,CAAA,GACzC,oBAAC,OAAO,MAAR,CAAc,CAAA,CACA,EAAA,CAAA;IAChB,oBAAC,OAAO,QAAR,EAAA,UACE,oBAAC,OAAO,YAAR,EAAA,UACE,oBAAC,OAAO,OAAR,EAAA,UACE,oBAAC,OAAO,MAAR,EAAA,UACG,QAAQ,KAAK,WACZ,oBAAC,OAAO,MAAR;KAAgC,OAAO,OAAO;KAC5C,UAAA,oBAAC,OAAO,UAAR,EAAA,UAAkB,OAAO,MAAuB,CAAA;IACrC,GAFK,OAAO,KAEZ,CACd,EACU,CAAA,EACD,CAAA,EACG,CAAA,EACN,CAAA;GACJ;EACZ,CAAA,GAAA,MAAM,SACL,oBAAC,UAAD;GACE,MAAK;GACL,eAAe,SAAS,UAAU,EAAE;GACpC,UAAU;GACV,2CAAwC;GAEvC,UAAA;EACK,CAAA,IACN,IACD;;AAET;AAMA,MAAa,mBAAmB;CAC9B,MAAM;CACN,gBAAgB;CAChB,YAAY;CACZ,sBAAsB;CACtB,YAAY;CACZ,sBAAsB;CACtB,cAAc;CACd,wBAAwB;CACxB,OAAO;CACP,iBAAiB;CACjB,UAAU;CACV,oBAAoB;CACpB,kBAAkB;CAClB,4BAA4B;CAC5B,iBAAiB;CACjB,2BAA2B;CAC3B,cAAc;CACd,wBAAwB;CACxB,cAAc;CACd,wBAAwB;CACxB,kBAAkB;CAClB,4BAA4B;CAC5B,eAAe;CACf,yBAAyB;AAC3B"}
|
|
1
|
+
{"version":3,"file":"my-account-profile.js","names":[],"sources":["../../../src/matter/my-account-profile/my-account-profile.tsx"],"sourcesContent":["'use client';\n\nimport { defineComponent } from '@vtex/fs-core';\nimport {\n type ChangeEvent,\n type ComponentPropsWithRef,\n createContext,\n type ReactNode,\n type SyntheticEvent,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport {\n DocumentField,\n isSupportedDocumentType,\n isValidDocument,\n maskDocumentValue,\n} from '../../particles/document-field/document-field.js';\nimport { Field } from '../../particles/field/field.js';\nimport { Input } from '../../particles/input/input.js';\nimport {\n applyPhoneMask,\n type PhoneCountry,\n PhoneField,\n toE164,\n validatePhoneNumber,\n} from '../../particles/phone-field/phone-field.js';\nimport { Select } from '../../particles/select/select.js';\nimport { useToast } from '../../particles/toast/toast.js';\nimport { useActionsOverride } from '../../sdk/actions/actions-override-context.js';\nimport type { ComponentActions } from '../../sdk/actions/types.js';\nimport { useDataOverride } from '../../sdk/data/data-override-context.js';\nimport type { CustomerProfileUserError } from '../../sdk/identity/operations.js';\nimport { loggableErrorName } from '../../utils/loggable-error-name.js';\nimport { useSession } from '../session/session.js';\n\n/**\n * The `my-account-profile` compound (see my-account-profile.md; spec archived at the specs-archive tag) — the data root\n * plus form mechanics for the shopper's persistent account profile. `Root` owns the saved profile,\n * the draft, the view↔edit toggle, and the single batched Save; it publishes a context whose\n * registration API is the seam every field Control attaches to.\n *\n * Unlike `ClientProfileFormRoot`, the Root does not enumerate the field set: a Control registers\n * its key plus an optional validator and normalizer, and the Root derives which fields to validate,\n * which to send, and which to focus from the live registry only. A field absent from the\n * composition is absent from the payload by construction (Decision 1).\n */\n\n// ---------------------------------------------------------------------------\n// GraphQL fragment — raw literal, outside codegen (Decision 8)\n// ---------------------------------------------------------------------------\n\nconst fragment = /* GraphQL */ `\n fragment MyAccountProfileData on Query {\n customerProfile {\n __typename\n id\n firstName\n lastName\n email\n homePhone\n mobilePhone\n document\n documentType\n birthDate\n gender\n }\n }\n`;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * The `$data` slice forwarded by the reactive runtime — the `customerProfile` entity itself, not the\n * `Query` shape the fragment above is authored against. The compiler derives an entity fragment `on\n * CustomerProfile` from the root-field selection for the reactive path (rfc-data-layer.md §\"Entity\n * fragments and schema introspection\"), and `ReactiveDataProvider` publishes that entity data\n * directly — the same convention `SessionRoot` reads `$data.loggedIn` under, not `$data.session`.\n *\n * `null` whenever `customerProfile` is: an anonymous session, or a signed-in read that failed. The\n * Root treats it as unresolved data, so the first renders nothing and the second keeps the skeleton.\n */\nexport type MyAccountProfileData = {\n id?: string | null;\n firstName?: string | null;\n lastName?: string | null;\n email?: string | null;\n homePhone?: string | null;\n mobilePhone?: string | null;\n document?: string | null;\n documentType?: string | null;\n birthDate?: string | null;\n gender?: string | null;\n} | null;\n\n/**\n * The shopper-editable keys. `email` is absent (login identifier) and `documentType` is absent\n * (read for the tax-ID control's active type; not writable in V0).\n */\nexport type MyAccountProfileFieldKey =\n | 'firstName'\n | 'lastName'\n | 'homePhone'\n | 'mobilePhone'\n | 'document'\n | 'birthDate'\n | 'gender';\n\nconst FIELD_KEYS: readonly MyAccountProfileFieldKey[] = [\n 'firstName',\n 'lastName',\n 'homePhone',\n 'mobilePhone',\n 'document',\n 'birthDate',\n 'gender',\n];\n\nexport type MyAccountProfileMode = 'view' | 'edit';\n\n/** Every editable key, always a string — a `null` upstream value is seeded as `''`. */\nexport type MyAccountProfileValues = Readonly<Record<MyAccountProfileFieldKey, string>>;\n\n/**\n * What a Control hands the Root. `validate` returns a message when the value is unacceptable and\n * `null` when it is fine — requiredness is expressed as a validator that rejects `''`. `normalize`\n * is applied on Save, to dirty values only.\n */\nexport type MyAccountProfileFieldRegistration = Readonly<{\n key: MyAccountProfileFieldKey;\n validate?: (value: string) => string | null;\n normalize?: (value: string) => string;\n}>;\n\nexport type MyAccountProfileFieldErrors = Readonly<Partial<Record<MyAccountProfileFieldKey, string>>>;\n\nexport type MyAccountProfileContextValue = Readonly<{\n mode: MyAccountProfileMode;\n savedValues: MyAccountProfileValues;\n draft: MyAccountProfileValues;\n fieldErrors: MyAccountProfileFieldErrors;\n email: string;\n activeDocumentType: string | undefined;\n pending: boolean;\n registerField: (registration: MyAccountProfileFieldRegistration) => () => void;\n setField: (key: MyAccountProfileFieldKey, value: string) => void;\n edit: () => void;\n cancel: () => void;\n}>;\n\nexport type MyAccountProfileRootProps = Readonly<{\n /** Store-configured tax-ID type fallback, used when the saved `documentType` is not registered. */\n documentType?: string;\n saveFailedMessage?: string;\n savedMessage?: string;\n className?: string;\n children?: ReactNode;\n $data?: MyAccountProfileData;\n /** Compiler-injected action surface; carries `identity.customerProfileUpdate`. */\n $actions?: ComponentActions;\n}>;\n\nexport type MyAccountProfileEditButtonProps = Readonly<{ label?: string; className?: string; children?: ReactNode }>;\nexport type MyAccountProfileSaveButtonProps = Readonly<{ label?: string; className?: string; children?: ReactNode }>;\nexport type MyAccountProfileCancelButtonProps = Readonly<{\n label?: string;\n className?: string;\n children?: ReactNode;\n}>;\nexport type MyAccountProfileEmailProps = Readonly<{ className?: string }>;\n\nconst DEFAULT_SAVE_FAILED_MESSAGE = 'Unable to save your profile. Please try again.';\nconst DEFAULT_SAVED_MESSAGE = 'Your profile has been saved.';\n\nfunction buildSavedValues($data: MyAccountProfileData | undefined): MyAccountProfileValues {\n return {\n firstName: $data?.firstName ?? '',\n lastName: $data?.lastName ?? '',\n homePhone: $data?.homePhone ?? '',\n mobilePhone: $data?.mobilePhone ?? '',\n document: $data?.document ?? '',\n birthDate: $data?.birthDate ?? '',\n gender: $data?.gender ?? '',\n };\n}\n\n/**\n * Native `<input type=\"date\">` values and the profile's stored `birthDate` are both `yyyy-mm-dd`.\n * `toNativeDate` stays defensive against a `yyyy-mm-ddTHH:mm:ss...` upstream value slipping through\n * unnormalized — the resolver already strips the time component, this is a second line of defense —\n * since the native input rejects anything but the date-only form outright.\n */\nfunction toNativeDate(stored: string): string {\n const [datePart] = stored.split('T');\n return datePart ?? '';\n}\nfunction toStoredDate(native: string): string {\n return native;\n}\n\nconst DEFAULT_GENDER_OPTIONS: readonly MyAccountProfileGenderOption[] = [\n { value: 'female', label: 'Female' },\n { value: 'male', label: 'Male' },\n { value: 'other', label: 'Other' },\n { value: 'prefer_not_to_say', label: 'Prefer not to say' },\n];\n\n// ---------------------------------------------------------------------------\n// Context — Root publishes the draft + registration API to its Controls\n// ---------------------------------------------------------------------------\n\nconst MY_ACCOUNT_PROFILE_UNSET = Symbol('MyAccountProfileContextUnset');\n\nconst MyAccountProfileContext = createContext<MyAccountProfileContextValue | typeof MY_ACCOUNT_PROFILE_UNSET>(\n MY_ACCOUNT_PROFILE_UNSET,\n);\n\n/** Throws when used outside `MyAccountProfileRoot`, per ADR-0009. */\nexport function useMyAccountProfile(): MyAccountProfileContextValue {\n const ctx = useContext(MyAccountProfileContext);\n if (ctx === MY_ACCOUNT_PROFILE_UNSET) {\n throw new Error('MyAccountProfile components must be used inside MyAccountProfileRoot.');\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Root\n// ---------------------------------------------------------------------------\n\nexport const MyAccountProfileRootDefinition = defineComponent<MyAccountProfileRootProps>({\n name: 'MyAccountProfileRoot',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileRoot,\n fragment,\n fetchStrategy: 'reactive',\n requiresContext: 'session',\n providesContext: 'my-account-profile',\n actions: { identity: ['customerProfileUpdate'] },\n skeleton: MyAccountProfileSkeleton,\n editor: { label: 'My Account Profile Root', category: 'identity' },\n schema: {\n documentType: { type: 'string', label: 'Default document type (e.g. CPF)' },\n saveFailedMessage: {\n type: 'string',\n default: 'Unable to save your profile. Please try again.',\n label: 'Save failure message',\n },\n savedMessage: {\n type: 'string',\n default: 'Your profile has been saved.',\n label: 'Save success message',\n },\n },\n guideline:\n 'Data root + form mechanics for the persistent My Account profile: owns the saved profile, the draft, the view/edit toggle, and the single batched Save (dispatches only dirty, registered fields; an empty string erases, an omitted field is untouched). Self-gates on the authenticated (loggedIn) session; requires a SessionRoot ancestor and a mounted ToastProvider ancestor — Save success/failure surface as a toast, not an inline part. Field Controls register their key plus an optional validator and normalizer through useMyAccountProfile() — the field set is a merchant composition decision, never enumerated here. Compose EditButton (view state), SaveButton/CancelButton (edit state), and Email as children in any order. See my-account-profile.md.',\n});\n\nexport function MyAccountProfileRoot({\n $data: $dataProp,\n $actions: $actionsProp,\n documentType: documentTypeProp,\n saveFailedMessage = DEFAULT_SAVE_FAILED_MESSAGE,\n savedMessage = DEFAULT_SAVED_MESSAGE,\n className,\n children,\n}: MyAccountProfileRootProps) {\n // Enforces the SessionRoot ancestor: useSession() throws when rendered outside one.\n const { state } = useSession();\n // Enforces the ToastProvider ancestor: useToast() throws when rendered outside one (Decision 10).\n const toast = useToast();\n const $data = useDataOverride($dataProp);\n const $actions = useActionsOverride($actionsProp);\n const resolved = $data != null;\n\n const savedValues = useMemo(() => buildSavedValues($data), [$data]);\n const savedEmail = $data?.email ?? '';\n const savedDocumentType = $data?.documentType?.toUpperCase();\n const activeDocumentType =\n savedDocumentType && isSupportedDocumentType(savedDocumentType) ? savedDocumentType : documentTypeProp;\n\n const [mode, setMode] = useState<MyAccountProfileMode>('view');\n const [draft, setDraft] = useState<MyAccountProfileValues>(savedValues);\n const [fieldErrors, setFieldErrors] = useState<MyAccountProfileFieldErrors>({});\n const [pending, setPending] = useState(false);\n const [registry, setRegistry] = useState<ReadonlyMap<MyAccountProfileFieldKey, MyAccountProfileFieldRegistration>>(\n () => new Map(),\n );\n\n const formRef = useRef<HTMLFormElement>(null);\n\n // Re-seed pristine fields when the saved profile changes underneath an open edit; a field the\n // shopper has touched (draft no longer equals the previous saved value) is never clobbered. Runs\n // during render (previous-saved in state, not a ref) so the re-seed lands in the same commit.\n const [prevSaved, setPrevSaved] = useState(savedValues);\n const changedKeys = FIELD_KEYS.filter((key) => prevSaved[key] !== savedValues[key]);\n if (changedKeys.length > 0) {\n setPrevSaved(savedValues);\n setDraft((prevDraft) => {\n let next = prevDraft;\n for (const key of changedKeys) {\n if (prevDraft[key] !== prevSaved[key]) continue;\n if (next === prevDraft) next = { ...prevDraft };\n (next as Record<MyAccountProfileFieldKey, string>)[key] = savedValues[key];\n }\n return next;\n });\n }\n\n const registerField = useCallback((registration: MyAccountProfileFieldRegistration) => {\n setRegistry((prev) => {\n const next = new Map(prev);\n next.set(registration.key, registration);\n return next;\n });\n return () => {\n setRegistry((prev) => {\n if (!prev.has(registration.key)) return prev;\n const next = new Map(prev);\n next.delete(registration.key);\n return next;\n });\n };\n }, []);\n\n const setField = useCallback((key: MyAccountProfileFieldKey, value: string) => {\n setDraft((prev) => ({ ...prev, [key]: value }));\n setFieldErrors((prev) => {\n if (!prev[key]) return prev;\n const next = { ...prev };\n delete next[key];\n return next;\n });\n }, []);\n\n // Opening an edit always starts from the latest truth, so a value the server normalized (e.g. a\n // reformatted phone) on a previous save is what the shopper sees, not their own stale keystrokes.\n const edit = useCallback(() => {\n setDraft(savedValues);\n setFieldErrors({});\n setMode('edit');\n }, [savedValues]);\n\n const cancel = useCallback(() => {\n setDraft(savedValues);\n setFieldErrors({});\n setMode('view');\n }, [savedValues]);\n\n function focusFirstInvalid(errors: MyAccountProfileFieldErrors) {\n const wrappers = formRef.current?.querySelectorAll<HTMLElement>('[data-fs-my-account-profile-field]');\n if (!wrappers) return;\n for (const wrapper of wrappers) {\n const key = wrapper.dataset.fsMyAccountProfileField as MyAccountProfileFieldKey | undefined;\n if (key && errors[key]) {\n const target = wrapper.querySelector<HTMLElement>('input, select, textarea') ?? wrapper;\n target.focus();\n return;\n }\n }\n }\n\n async function handleSubmit(event: SyntheticEvent<HTMLFormElement>) {\n event.preventDefault();\n if (pending) return;\n\n const dirtyKeys = Array.from(registry.keys()).filter((key) => draft[key] !== savedValues[key]);\n if (dirtyKeys.length === 0) {\n setFieldErrors({});\n setMode('view');\n toast.add({ title: savedMessage, type: 'success' });\n return;\n }\n\n // Validate only the fields the shopper actually changed (Decision 9, product-confirmed): a\n // stale invalid value the shopper never touched must not block an unrelated field's save.\n const errors: Record<string, string> = {};\n for (const key of dirtyKeys) {\n const registration = registry.get(key);\n const message = registration?.validate?.(draft[key]);\n if (message) errors[key] = message;\n }\n if (Object.keys(errors).length > 0) {\n setFieldErrors(errors as MyAccountProfileFieldErrors);\n focusFirstInvalid(errors as MyAccountProfileFieldErrors);\n return;\n }\n setFieldErrors({});\n\n const identity = $actions?.identity;\n if (!identity?.customerProfileUpdate) {\n // A composition/platform gap (the provider chain never delivered customerProfileUpdate) is\n // otherwise indistinguishable from a dead button — surface it the same way a rejected write\n // would, rather than returning silently.\n toast.add({ title: saveFailedMessage, type: 'error' });\n return;\n }\n\n const payload: Partial<Record<MyAccountProfileFieldKey, string>> = {};\n for (const key of dirtyKeys) {\n const registration = registry.get(key);\n const rawValue = draft[key];\n payload[key] = registration?.normalize ? registration.normalize(rawValue) : rawValue;\n }\n\n setPending(true);\n try {\n const userErrors: readonly CustomerProfileUserError[] = await identity.customerProfileUpdate(payload);\n if (userErrors.length > 0) {\n toast.add({ title: userErrors[0]?.message ?? saveFailedMessage, type: 'error' });\n return;\n }\n setMode('view');\n toast.add({ title: savedMessage, type: 'success' });\n } catch (error) {\n // Log only the error name — the message can echo a submitted profile value (PII).\n console.error('[MyAccountProfileRoot] customerProfileUpdate failed', loggableErrorName(error));\n toast.add({ title: saveFailedMessage, type: 'error' });\n } finally {\n setPending(false);\n }\n }\n\n const contextValue = useMemo<MyAccountProfileContextValue>(\n () => ({\n mode,\n savedValues,\n draft,\n fieldErrors,\n email: savedEmail,\n activeDocumentType,\n pending,\n registerField,\n setField,\n edit,\n cancel,\n }),\n [\n mode,\n savedValues,\n draft,\n fieldErrors,\n savedEmail,\n activeDocumentType,\n pending,\n registerField,\n setField,\n edit,\n cancel,\n ],\n );\n\n // Self-gate: an anonymous or identified-but-not-authenticated session never reaches the DOM,\n // even if the topology's SessionGuard is missing (US-5).\n if (state !== 'loggedIn') return null;\n\n // Empty is a post-resolution state — the skeleton renders while $data is unresolved, never an\n // empty summary.\n if (!resolved) return <MyAccountProfileSkeleton className={className} />;\n\n return (\n <MyAccountProfileContext value={contextValue}>\n <form\n ref={formRef}\n onSubmit={handleSubmit}\n className={className}\n data-fs-my-account-profile=\"\"\n data-fs-my-account-profile-mode={mode}\n {...(pending ? { 'data-fs-my-account-profile-pending': '' } : {})}\n >\n {children}\n </form>\n </MyAccountProfileContext>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Frame parts\n// ---------------------------------------------------------------------------\n\nexport const MyAccountProfileEditButtonDefinition = defineComponent<MyAccountProfileEditButtonProps>({\n name: 'MyAccountProfileEditButton',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileEditButton,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Edit Button', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Edit', label: 'Button label' },\n },\n guideline:\n 'Switches MyAccountProfileRoot from the view state to the edit state. Renders only in the view state. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileEditButton({ label = 'Edit', className, children }: MyAccountProfileEditButtonProps) {\n const { mode, edit } = useMyAccountProfile();\n if (mode !== 'view') return null;\n return (\n <button type=\"button\" onClick={edit} className={className} data-fs-my-account-profile-edit=\"\">\n {children ?? label}\n </button>\n );\n}\n\nexport const MyAccountProfileSaveButtonDefinition = defineComponent<MyAccountProfileSaveButtonProps>({\n name: 'MyAccountProfileSaveButton',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileSaveButton,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Save Button', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Save', label: 'Button label' },\n },\n guideline:\n \"Submits MyAccountProfileRoot's batched Save. Renders only in the edit state; disabled while the write is pending. Must be a descendant of MyAccountProfileRoot.\",\n});\n\nexport function MyAccountProfileSaveButton({ label = 'Save', className, children }: MyAccountProfileSaveButtonProps) {\n const { mode, pending } = useMyAccountProfile();\n if (mode !== 'edit') return null;\n return (\n <button type=\"submit\" disabled={pending} className={className} data-fs-my-account-profile-save=\"\">\n {children ?? label}\n </button>\n );\n}\n\nexport const MyAccountProfileCancelButtonDefinition = defineComponent<MyAccountProfileCancelButtonProps>({\n name: 'MyAccountProfileCancelButton',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileCancelButton,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Cancel Button', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Cancel', label: 'Button label' },\n },\n guideline:\n 'Reverts every field to its last saved value and returns MyAccountProfileRoot to the view state, without persisting. Renders only in the edit state; disabled while the write is pending. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileCancelButton({\n label = 'Cancel',\n className,\n children,\n}: MyAccountProfileCancelButtonProps) {\n const { mode, pending, cancel } = useMyAccountProfile();\n if (mode !== 'edit') return null;\n return (\n <button\n type=\"button\"\n disabled={pending}\n onClick={cancel}\n className={className}\n data-fs-my-account-profile-cancel=\"\"\n >\n {children ?? label}\n </button>\n );\n}\n\nexport const MyAccountProfileEmailDefinition = defineComponent<MyAccountProfileEmailProps>({\n name: 'MyAccountProfileEmail',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileEmail,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Email', category: 'identity' },\n schema: {},\n guideline:\n \"The shopper's read-only login identifier, or nothing when absent. Never editable — no edit-state rendering exists for it. Must be a descendant of MyAccountProfileRoot.\",\n});\n\nexport function MyAccountProfileEmail({ className }: MyAccountProfileEmailProps) {\n const { email } = useMyAccountProfile();\n if (!email) return null;\n return (\n <p className={className} data-fs-my-account-profile-email=\"\">\n {email}\n </p>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Skeleton — no context: it is rendered directly by the Root before any Provider exists\n// (mirrors ProductShelfSkeleton / PricingSkeleton; see spec deviation note).\n// ---------------------------------------------------------------------------\n\nexport const MyAccountProfileSkeletonDefinition = defineComponent<ComponentPropsWithRef<'div'>>({\n name: 'MyAccountProfileSkeleton',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileSkeleton,\n editor: { label: 'My Account Profile Skeleton', category: 'identity' },\n schema: {},\n guideline:\n 'Loading placeholder rendered by MyAccountProfileRoot while $data is unresolved. Declares no context requirement — it renders before the Root has anything to provide.',\n});\n\nexport function MyAccountProfileSkeleton({ className, ...props }: ComponentPropsWithRef<'div'>) {\n return (\n <div {...props} className={className} data-fs-my-account-profile-skeleton=\"\" aria-hidden=\"true\">\n <span data-fs-my-account-profile-skeleton-line=\"\" />\n <span data-fs-my-account-profile-skeleton-line=\"\" />\n <span data-fs-my-account-profile-skeleton-line=\"\" />\n </div>\n );\n}\n\nMyAccountProfileRoot.Skeleton = MyAccountProfileSkeleton;\n\n// ---------------------------------------------------------------------------\n// Field Controls\n//\n// Each Control is a thin binding over an existing presentational particle: it registers with the\n// Root's registration seam in an effect, reads its value off `mode` (savedValues in view, draft in\n// edit), writes through `setField`, and wraps its input in an element carrying\n// `data-fs-my-account-profile-field` — the Root's DOM-order focus seam. None persists on its own.\n// ---------------------------------------------------------------------------\n\nexport type MyAccountProfileFirstNameControlProps = Readonly<{\n label?: string;\n requiredMessage?: string;\n className?: string;\n}>;\n\nexport const MyAccountProfileFirstNameControlDefinition = defineComponent<MyAccountProfileFirstNameControlProps>({\n name: 'MyAccountProfileFirstNameControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileFirstNameControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile First Name Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'First name', label: 'Label' },\n requiredMessage: { type: 'string', default: 'First name is required.', label: 'Required message' },\n },\n guideline:\n 'Draft-bound, required first-name field. Blocks Save with an inline message and focus when left empty. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileFirstNameControl({\n label = 'First name',\n requiredMessage = 'First name is required.',\n className,\n}: MyAccountProfileFirstNameControlProps) {\n const { mode, draft, savedValues, fieldErrors, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({ key: 'firstName', validate: (value) => (value.trim() ? null : requiredMessage) });\n }, [requiredMessage, registerField]);\n\n const error = fieldErrors.firstName;\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-first-name=\"\" data-fs-my-account-profile-field=\"firstName\">\n {savedValues.firstName}\n </p>\n );\n }\n\n return (\n <Field.Root\n className={className}\n invalid={!!error}\n disabled={pending}\n data-fs-my-account-profile-first-name=\"\"\n data-fs-my-account-profile-field=\"firstName\"\n >\n <Field.Label>{label}</Field.Label>\n <Field.Control\n value={draft.firstName}\n onChange={(event) => setField('firstName', event.target.value)}\n disabled={pending}\n />\n {error ? <Field.Error match>{error}</Field.Error> : null}\n </Field.Root>\n );\n}\n\nexport type MyAccountProfileLastNameControlProps = Readonly<{\n label?: string;\n requiredMessage?: string;\n className?: string;\n}>;\n\nexport const MyAccountProfileLastNameControlDefinition = defineComponent<MyAccountProfileLastNameControlProps>({\n name: 'MyAccountProfileLastNameControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileLastNameControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Last Name Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Last name', label: 'Label' },\n requiredMessage: { type: 'string', default: 'Last name is required.', label: 'Required message' },\n },\n guideline:\n 'Draft-bound, required last-name field. Blocks Save with an inline message and focus when left empty. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileLastNameControl({\n label = 'Last name',\n requiredMessage = 'Last name is required.',\n className,\n}: MyAccountProfileLastNameControlProps) {\n const { mode, draft, savedValues, fieldErrors, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({ key: 'lastName', validate: (value) => (value.trim() ? null : requiredMessage) });\n }, [requiredMessage, registerField]);\n\n const error = fieldErrors.lastName;\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-last-name=\"\" data-fs-my-account-profile-field=\"lastName\">\n {savedValues.lastName}\n </p>\n );\n }\n\n return (\n <Field.Root\n className={className}\n invalid={!!error}\n disabled={pending}\n data-fs-my-account-profile-last-name=\"\"\n data-fs-my-account-profile-field=\"lastName\"\n >\n <Field.Label>{label}</Field.Label>\n <Field.Control\n value={draft.lastName}\n onChange={(event) => setField('lastName', event.target.value)}\n disabled={pending}\n />\n {error ? <Field.Error match>{error}</Field.Error> : null}\n </Field.Root>\n );\n}\n\nexport type MyAccountProfilePhoneControlProps = Readonly<{\n label?: string;\n /** Which draft key this instance binds. Compose the Control twice to expose both numbers. */\n field?: 'homePhone' | 'mobilePhone';\n country?: PhoneCountry;\n invalidMessage?: string;\n className?: string;\n}>;\n\nexport const MyAccountProfilePhoneControlDefinition = defineComponent<MyAccountProfilePhoneControlProps>({\n name: 'MyAccountProfilePhoneControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfilePhoneControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Phone Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Phone', label: 'Label' },\n field: { type: ['homePhone', 'mobilePhone'] as const, default: 'mobilePhone', label: 'Bound field' },\n country: { type: ['US', 'BR'] as const, default: 'US', label: 'Country' },\n invalidMessage: { type: 'string', default: 'Invalid phone number', label: 'Invalid message' },\n },\n guideline:\n \"Draft-bound, optional phone field bound to either homePhone or mobilePhone via the field prop (Decision 1) — compose it twice to expose both numbers. Normalizes to E.164 on the Root's Save. Absent from the composition means absent from the payload. Must be a descendant of MyAccountProfileRoot.\",\n});\n\nexport function MyAccountProfilePhoneControl({\n label = 'Phone',\n field = 'mobilePhone',\n country = 'US',\n invalidMessage = 'Invalid phone number',\n className,\n}: MyAccountProfilePhoneControlProps) {\n const { mode, draft, savedValues, fieldErrors, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({\n key: field,\n validate: (value) => (value.trim() && !validatePhoneNumber(value, country) ? invalidMessage : null),\n normalize: (value) => (value.trim() ? toE164(value, country) : value),\n });\n }, [field, country, invalidMessage, registerField]);\n\n const error = fieldErrors[field];\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-phone={field} data-fs-my-account-profile-field={field}>\n {savedValues[field] ? applyPhoneMask(savedValues[field], country) : ''}\n </p>\n );\n }\n\n return (\n <div data-fs-my-account-profile-field={field}>\n <PhoneField\n className={className}\n label={label}\n country={country}\n requirement=\"optional\"\n value={draft[field]}\n onValueChange={(value) => setField(field, value)}\n invalid={!!error}\n error={error ?? undefined}\n errorInvalid={invalidMessage}\n isDisabled={pending}\n data-fs-my-account-profile-phone={field}\n />\n </div>\n );\n}\n\nexport type MyAccountProfileTaxIdControlProps = Readonly<{\n label?: string;\n invalidMessage?: string;\n /** Inline reason shown beside the locked saved CPF. */\n lockedReason?: string;\n className?: string;\n}>;\n\nexport const MyAccountProfileTaxIdControlDefinition = defineComponent<MyAccountProfileTaxIdControlProps>({\n name: 'MyAccountProfileTaxIdControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileTaxIdControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Tax ID Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'National tax ID', label: 'Label' },\n invalidMessage: { type: 'string', default: 'Invalid document number.', label: 'Invalid message' },\n lockedReason: { type: 'string', default: \"Your document ID can't be edited.\", label: 'Locked reason' },\n },\n guideline:\n \"Draft-bound, optional national tax-ID field (CPF in V0). Self-gates on the Root's active document type. A saved value renders as a disabled, locked input in the edit state rather than disappearing (Decision 4); an unsaved value renders as an editable field. Must be a descendant of MyAccountProfileRoot.\",\n});\n\nexport function MyAccountProfileTaxIdControl({\n label = 'National tax ID',\n invalidMessage = 'Invalid document number.',\n lockedReason = \"Your document ID can't be edited.\",\n className,\n}: MyAccountProfileTaxIdControlProps) {\n const { mode, draft, savedValues, fieldErrors, pending, activeDocumentType, registerField, setField } =\n useMyAccountProfile();\n const documentType =\n activeDocumentType && isSupportedDocumentType(activeDocumentType) ? activeDocumentType : undefined;\n const hasSavedDocument = savedValues.document.trim() !== '';\n\n useEffect(() => {\n if (!documentType || hasSavedDocument) return;\n return registerField({\n key: 'document',\n validate: (value) => (value.trim() && !isValidDocument(value, documentType) ? invalidMessage : null),\n // DocumentField reports back the masked value (e.g. `111.444.777-35`); strip the punctuation\n // before it reaches the API, matching the checkout form's `stripNonDigits`.\n normalize: (value) => value.replaceAll(/\\D/g, ''),\n });\n }, [documentType, hasSavedDocument, invalidMessage, registerField]);\n\n if (!documentType) return null;\n\n const error = fieldErrors.document;\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-tax-id=\"\" data-fs-my-account-profile-field=\"document\">\n {savedValues.document ? maskDocumentValue(savedValues.document, documentType) : ''}\n </p>\n );\n }\n\n if (hasSavedDocument) {\n return (\n <Field.Root\n className={className}\n data-fs-my-account-profile-tax-id=\"\"\n data-fs-my-account-profile-field=\"document\"\n >\n <Field.Label>{label}</Field.Label>\n <Field.Control\n readOnly\n aria-disabled=\"true\"\n title={lockedReason}\n value={maskDocumentValue(savedValues.document, documentType)}\n data-fs-my-account-profile-tax-id-readonly=\"\"\n />\n <Field.Description>{lockedReason}</Field.Description>\n </Field.Root>\n );\n }\n\n return (\n <DocumentField\n className={className}\n label={label}\n documentType={documentType}\n value={draft.document}\n onValueChange={(value) => setField('document', value)}\n invalid={!!error}\n errorMessage={error}\n disabled={pending}\n data-fs-my-account-profile-tax-id=\"\"\n data-fs-my-account-profile-field=\"document\"\n />\n );\n}\n\nexport type MyAccountProfileBirthDateControlProps = Readonly<{ label?: string; className?: string }>;\n\nexport const MyAccountProfileBirthDateControlDefinition = defineComponent<MyAccountProfileBirthDateControlProps>({\n name: 'MyAccountProfileBirthDateControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileBirthDateControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Birth Date Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Birth date', label: 'Label' },\n },\n guideline:\n 'Draft-bound, optional birth-date field over a native date input. Maps the native yyyy-mm-dd value to the stored profile format on read and write. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileBirthDateControl({\n label = 'Birth date',\n className,\n}: MyAccountProfileBirthDateControlProps) {\n const { mode, draft, savedValues, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({ key: 'birthDate', normalize: (value) => toStoredDate(value) });\n }, [registerField]);\n\n if (mode === 'view') {\n return (\n <p className={className} data-fs-my-account-profile-birth-date=\"\" data-fs-my-account-profile-field=\"birthDate\">\n {savedValues.birthDate}\n </p>\n );\n }\n\n function handleChange(event: ChangeEvent<HTMLInputElement>) {\n setField('birthDate', toStoredDate(event.target.value));\n }\n\n return (\n <Field.Root\n className={className}\n data-fs-my-account-profile-birth-date=\"\"\n data-fs-my-account-profile-field=\"birthDate\"\n >\n <Field.Label>{label}</Field.Label>\n <Input type=\"date\" value={toNativeDate(draft.birthDate)} onChange={handleChange} disabled={pending} />\n </Field.Root>\n );\n}\n\nexport type MyAccountProfileGenderOption = Readonly<{ value: string; label: string }>;\n\nexport type MyAccountProfileGenderControlProps = Readonly<{\n label?: string;\n placeholder?: string;\n clearLabel?: string;\n options?: readonly MyAccountProfileGenderOption[];\n className?: string;\n}>;\n\nexport const MyAccountProfileGenderControlDefinition = defineComponent<MyAccountProfileGenderControlProps>({\n name: 'MyAccountProfileGenderControl',\n importPath: '@vtex/faststore/components',\n component: MyAccountProfileGenderControl,\n requiresContext: 'my-account-profile',\n editor: { label: 'My Account Profile Gender Control', category: 'identity' },\n schema: {\n label: { type: 'string', default: 'Gender', label: 'Label' },\n placeholder: { type: 'string', default: 'Select', label: 'Placeholder' },\n clearLabel: { type: 'string', default: 'Clear', label: 'Clear button label' },\n },\n guideline:\n 'Draft-bound, optional gender field over a store-configurable set of options (the options prop). Free-string storage — no server-side enum. A Clear button erases a selected value back to empty, since the Select itself offers no such option. Must be a descendant of MyAccountProfileRoot.',\n});\n\nexport function MyAccountProfileGenderControl({\n label = 'Gender',\n placeholder = 'Select',\n clearLabel = 'Clear',\n options = DEFAULT_GENDER_OPTIONS,\n className,\n}: MyAccountProfileGenderControlProps) {\n const { mode, draft, savedValues, pending, registerField, setField } = useMyAccountProfile();\n\n useEffect(() => {\n return registerField({ key: 'gender' });\n }, [registerField]);\n\n if (mode === 'view') {\n const selected = options.find((option) => option.value === savedValues.gender);\n return (\n <p className={className} data-fs-my-account-profile-gender=\"\" data-fs-my-account-profile-field=\"gender\">\n {selected?.label ?? savedValues.gender}\n </p>\n );\n }\n\n return (\n <div className={className} data-fs-my-account-profile-gender=\"\" data-fs-my-account-profile-field=\"gender\">\n <Select.Root value={draft.gender} onValueChange={(value) => setField('gender', value ?? '')} disabled={pending}>\n <Select.Label>{label}</Select.Label>\n <Select.Trigger>\n <Select.Value placeholder={placeholder} />\n <Select.Icon />\n </Select.Trigger>\n <Select.Portal>\n <Select.Positioner>\n <Select.Popup>\n <Select.List>\n {options.map((option) => (\n <Select.Item key={option.value} value={option.value}>\n <Select.ItemText>{option.label}</Select.ItemText>\n </Select.Item>\n ))}\n </Select.List>\n </Select.Popup>\n </Select.Positioner>\n </Select.Portal>\n </Select.Root>\n {draft.gender ? (\n <button\n type=\"button\"\n onClick={() => setField('gender', '')}\n disabled={pending}\n data-fs-my-account-profile-gender-clear=\"\"\n >\n {clearLabel}\n </button>\n ) : null}\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Namespace export\n// ---------------------------------------------------------------------------\n\nexport const MyAccountProfile = {\n Root: MyAccountProfileRoot,\n RootDefinition: MyAccountProfileRootDefinition,\n EditButton: MyAccountProfileEditButton,\n EditButtonDefinition: MyAccountProfileEditButtonDefinition,\n SaveButton: MyAccountProfileSaveButton,\n SaveButtonDefinition: MyAccountProfileSaveButtonDefinition,\n CancelButton: MyAccountProfileCancelButton,\n CancelButtonDefinition: MyAccountProfileCancelButtonDefinition,\n Email: MyAccountProfileEmail,\n EmailDefinition: MyAccountProfileEmailDefinition,\n Skeleton: MyAccountProfileSkeleton,\n SkeletonDefinition: MyAccountProfileSkeletonDefinition,\n FirstNameControl: MyAccountProfileFirstNameControl,\n FirstNameControlDefinition: MyAccountProfileFirstNameControlDefinition,\n LastNameControl: MyAccountProfileLastNameControl,\n LastNameControlDefinition: MyAccountProfileLastNameControlDefinition,\n PhoneControl: MyAccountProfilePhoneControl,\n PhoneControlDefinition: MyAccountProfilePhoneControlDefinition,\n TaxIdControl: MyAccountProfileTaxIdControl,\n TaxIdControlDefinition: MyAccountProfileTaxIdControlDefinition,\n BirthDateControl: MyAccountProfileBirthDateControl,\n BirthDateControlDefinition: MyAccountProfileBirthDateControlDefinition,\n GenderControl: MyAccountProfileGenderControl,\n GenderControlDefinition: MyAccountProfileGenderControlDefinition,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,WAAyB;;;;;;;;;;;;;;;;;AA0D/B,MAAM,aAAkD;CACtD;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAuDA,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAE9B,SAAS,iBAAiB,OAAiE;CACzF,OAAO;EACL,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,WAAW,OAAO,aAAa;EAC/B,aAAa,OAAO,eAAe;EACnC,UAAU,OAAO,YAAY;EAC7B,WAAW,OAAO,aAAa;EAC/B,QAAQ,OAAO,UAAU;CAC3B;AACF;;;;;;;AAQA,SAAS,aAAa,QAAwB;CAC5C,MAAM,CAAC,YAAY,OAAO,MAAM,GAAG;CACnC,OAAO,YAAY;AACrB;AACA,SAAS,aAAa,QAAwB;CAC5C,OAAO;AACT;AAEA,MAAM,yBAAkE;CACtE;EAAE,OAAO;EAAU,OAAO;CAAS;CACnC;EAAE,OAAO;EAAQ,OAAO;CAAO;CAC/B;EAAE,OAAO;EAAS,OAAO;CAAQ;CACjC;EAAE,OAAO;EAAqB,OAAO;CAAoB;AAC3D;AAMA,MAAM,2BAA2B,OAAO,8BAA8B;AAEtE,MAAM,0BAA0B,cAC9B,wBACF;;AAGA,SAAgB,sBAAoD;CAClE,MAAM,MAAM,WAAW,uBAAuB;CAC9C,IAAI,QAAQ,0BACV,MAAM,IAAI,MAAM,uEAAuE;CAEzF,OAAO;AACT;AAMA,M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O,MAAR;KAAgC,OAAO,OAAO;KAC5C,UAAA,oBAAC,OAAO,UAAR,EAAA,UAAkB,OAAO,MAAuB,CAAA;IACrC,GAFK,OAAO,KAEZ,CACd,EACU,CAAA,EACD,CAAA,EACG,CAAA,EACN,CAAA;GACJ;EACZ,CAAA,GAAA,MAAM,SACL,oBAAC,UAAD;GACE,MAAK;GACL,eAAe,SAAS,UAAU,EAAE;GACpC,UAAU;GACV,2CAAwC;GAEvC,UAAA;EACK,CAAA,IACN,IACD;;AAET;AAMA,MAAa,mBAAmB;CAC9B,MAAM;CACN,gBAAgB;CAChB,YAAY;CACZ,sBAAsB;CACtB,YAAY;CACZ,sBAAsB;CACtB,cAAc;CACd,wBAAwB;CACxB,OAAO;CACP,iBAAiB;CACjB,UAAU;CACV,oBAAoB;CACpB,kBAAkB;CAClB,4BAA4B;CAC5B,iBAAiB;CACjB,2BAA2B;CAC3B,cAAc;CACd,wBAAwB;CACxB,cAAc;CACd,wBAAwB;CACxB,kBAAkB;CAClB,4BAA4B;CAC5B,eAAe;CACf,yBAAyB;AAC3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment-controller.js","names":[],"sources":["../../../src/matter/payment/payment-controller.tsx"],"sourcesContent":["'use client';\n\nimport { defineComponent } from '@vtex/fs-core';\nimport { cloneElement, isValidElement, type ReactNode, useMemo, useState } from 'react';\nimport { useActionsOverride } from '../../sdk/actions/actions-override-context.js';\nimport type { ComponentActions } from '../../sdk/actions/types.js';\nimport { useDataOverride } from '../../sdk/data/data-override-context.js';\nimport { PaymentSubmissionProvider } from '../../sdk/payment/submission-registry.js';\nimport {\n DEFAULT_METHOD_GROUP,\n PaymentContext,\n type PaymentContextValue,\n type PaymentSectionRootData,\n} from './payment.js';\nimport { PaymentCardCaptureProvider } from './payment-card-capture.js';\nimport { usePaymentMethodSelection } from './use-payment-method-selection.js';\n\n/**\n * The collapsed payment section (centered modal / slide-in panel) as a state-only controller\n * (specs/payment-section-root.md, T5; docs/features/credit-card/rfc.md § D1). The page composes a raw\n * `DialogRoot` or `DrawerRoot` and each of its particles (`DialogTrigger` / `DialogBackdrop` /\n * `DialogPopup` …) directly as `page.json` nodes, so every part — including the portaled backdrop and\n * popup a descendant selector could not reach — is a swatch-addressable node with zero Tailwind baked\n * into the package, exactly as `DeliveryOptionsController` established.\n *\n * `PaymentSectionController` renders no markup: it runs the shared `usePaymentMethodSelection` engine,\n * holds the open state, provides the same `payment` context `PaymentSectionRoot` does (ADR-0009 matches\n * by contract identifier, so every leaf composes under either with no edit), then injects\n * `open` / `onOpenChange` into its single overlay-`Root` child via `cloneElement` — the same mechanism\n * as `CartOpenOnAdd` and `ShippingAddressSavedAddressDrawerController`.\n *\n * It diverges from `DeliveryOptionsController` in one deliberate way: a successful method selection\n * does **not** close the surface. Picking a delivery option completes that interaction; picking a\n * payment method is the first step of several — the shopper still types a card, picks an installment,\n * and places the order. Closing is therefore the composition's call, through the context's `setOpen`\n * (T14 on a placed order) or a `DrawerClose` / `DialogClose` particle.\n *\n * The trigger holds a static label (`Text`): no component echoes the current choice there, and none is\n * shipped here — `payment.md` documents the same composition.\n */\n\n// Repeats `PaymentSectionData`'s selection set verbatim under its own name. Two definitions cannot\n// share one fragment name in a page query, and the native catalog builder resolves\n// `defineComponent({ fragment })` statically — a value imported from another module is silently\n// dropped from the built catalog. `delivery-options` duplicates for the same reason;\n// `payment.test.tsx` asserts the two sets stay field-for-field identical.\nconst fragment = /* GraphQL */ `\n fragment PaymentSectionControllerData on Query {\n payment {\n __typename\n id\n methods {\n __typename\n id\n name\n groupName\n validator {\n __typename\n numberMask\n numberRegex\n cvvMask\n cvvRegex\n cvvRequired\n expirationRequired\n holderNameRequired\n billingAddressRequired\n documentDisplayable\n documentRequired\n }\n }\n selectedMethodId\n selectedAccountId\n selectedBin\n }\n cart {\n __typename\n id\n total {\n __typename\n amount\n currencyCode\n }\n }\n }\n`;\n\n// The minimal open-state shape the controller injects into its overlay-Root child; both `DialogRoot`\n// and `DrawerRoot` accept it.\ntype OverlayOpenProps = {\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n};\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport type PaymentSectionControllerProps = {\n /**\n * Scopes the method list to a **set** of `PaymentMethod.groupName` values — a method is in scope\n * when its `groupName` is a member (T140, FR-1, Decision 1). A single string is still accepted and\n * scopes to exactly that one group. An empty string scopes nothing.\n */\n group?: string | readonly string[];\n /** Keyed `{ payment, cart }` forwarded by the reactive runtime (arity-2 fragment, ADR-0015). */\n $data?: PaymentSectionRootData;\n /** Compiler-injected action surface; carries `payment.setMethod`, `payment.sendPayments`, and `analytics.track`. */\n $actions?: ComponentActions;\n /** The single overlay `Root` to control — a `DialogRoot` (modal) or `DrawerRoot` (slide-in). */\n children?: ReactNode;\n};\n\n// ---------------------------------------------------------------------------\n// Definition\n// ---------------------------------------------------------------------------\n\nexport const PaymentSectionControllerDefinition = defineComponent<PaymentSectionControllerProps>({\n name: 'PaymentSectionController',\n importPath: '@vtex/faststore/components',\n component: PaymentSectionController,\n fragment,\n fetchStrategy: 'reactive',\n actions: { payment: ['setMethod', 'sendPayments'], analytics: ['track'] },\n providesContext: ['payment', 'card-capture'],\n editor: { label: 'Payment Section Controller', category: 'commerce' },\n schema: {\n // Literal, not `DEFAULT_METHOD_GROUP` — see the same note on `PaymentSectionRootDefinition`.\n // T140, Decision 2/OQ-6: same widened shape as `PaymentSectionRootDefinition` — see its own note.\n group: {\n type: 'array',\n default: ['creditCardPaymentGroup', 'debitCardPaymentGroup'],\n label: 'Payment method group',\n },\n },\n guideline:\n \"State-only controller for a collapsed payment section: wrap a single DialogRoot (centered modal) or DrawerRoot (slide-in) child and it becomes controlled. Renders no markup and bakes no styling — compose the overlay particles (DialogTrigger/DialogPortal/DialogBackdrop/DialogPopup or the Drawer equivalents) directly as page nodes, put a static label (Text) inside the trigger — no component echoes the current choice there, and put PaymentMethodList plus the payment leaves (CardEntry, Installments, SavedCards, PlaceOrder, …) inside the popup. Provides the same 'payment' and 'card-capture' contexts as PaymentSectionRoot, so every leaf composes under either with no change. Unlike the delivery-options controller it does NOT close on a successful selection — picking a method is mid-flow — so close it from a DrawerClose/DialogClose particle or from the leaf that finishes the flow. See payment.md.\",\n // The convention-based `<file-stem>.md` (`payment-controller.md`) does not exist — this component's\n // doc is `payment.md`, shared with PaymentSectionRoot/PaymentMethodList (T25/FR-8).\n docPath: './payment.md',\n});\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nexport function PaymentSectionController({\n group = DEFAULT_METHOD_GROUP,\n $data: $dataProp,\n $actions: $actionsProp,\n children,\n}: Readonly<PaymentSectionControllerProps>) {\n const $data = useDataOverride($dataProp);\n const $actions = useActionsOverride($actionsProp);\n const selection = usePaymentMethodSelection({ group, $data: $data?.payment ?? null, $actions });\n const [open, setOpen] = useState(false);\n const payment = useMemo<PaymentContextValue>(() => ({ ...selection, open, setOpen }), [selection, open]);\n\n if (!isValidElement<OverlayOpenProps>(children)) {\n return children;\n }\n\n return (\n <PaymentContext value={payment}>\n <PaymentSubmissionProvider path={selection.draft.path}>\n <PaymentCardCaptureProvider selection={selection} cart={$data?.cart} $actions={$actions}>\n {cloneElement(children, { open, onOpenChange: setOpen })}\n </PaymentCardCaptureProvider>\n </PaymentSubmissionProvider>\n </PaymentContext>\n );\n}\n"],"mappings":";;;;;;;;;;;AAoHA,MAAa,qCAAqC,gBAA+C;CAC/F,MAAM;CACN,YAAY;CACZ,WAAW;CACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CACA,eAAe;CACf,SAAS;EAAE,SAAS,CAAC,aAAa,cAAc;EAAG,WAAW,CAAC,OAAO;CAAE;CACxE,iBAAiB,CAAC,WAAW,cAAc;CAC3C,QAAQ;EAAE,OAAO;EAA8B,UAAU;CAAW;CACpE,QAAQ,EAGN,OAAO;EACL,MAAM;EACN,SAAS,CAAC,0BAA0B,uBAAuB;EAC3D,OAAO;CACT,EACF;CACA,WACE;CAGF,SAAS;AACX,CAAC;AAMD,SAAgB,yBAAyB,EACvC,QAAQ,sBACR,OAAO,WACP,UAAU,cACV,YAC0C;CAC1C,MAAM,QAAQ,gBAAgB,SAAS;CACvC,MAAM,WAAW,mBAAmB,YAAY;CAChD,MAAM,YAAY,0BAA0B;EAAE;EAAO,OAAO,OAAO,WAAW;EAAM;CAAS,CAAC;CAC9F,MAAM,CAAC,MAAM,WAAW,SAAS,KAAK;CACtC,MAAM,UAAU,eAAoC;EAAE,GAAG;EAAW;EAAM;CAAQ,IAAI,CAAC,WAAW,IAAI,CAAC;CAEvG,IAAI,CAAC,eAAiC,QAAQ,GAC5C,OAAO;CAGT,OACE,oBAAC,gBAAD;EAAgB,OAAO;EACrB,UAAA,oBAAC,2BAAD;GAA2B,MAAM,UAAU,MAAM;GAC/C,UAAA,oBAAC,4BAAD;IAAuC;IAAW,MAAM,OAAO;IAAgB;IAC5E,UAAA,aAAa,UAAU;KAAE;KAAM,cAAc;IAAQ,CAAC;GAC7B,CAAA;EACH,CAAA;CACb,CAAA;AAEpB"}
|
|
1
|
+
{"version":3,"file":"payment-controller.js","names":[],"sources":["../../../src/matter/payment/payment-controller.tsx"],"sourcesContent":["'use client';\n\nimport { defineComponent } from '@vtex/fs-core';\nimport { cloneElement, isValidElement, type ReactNode, useMemo, useState } from 'react';\nimport { useActionsOverride } from '../../sdk/actions/actions-override-context.js';\nimport type { ComponentActions } from '../../sdk/actions/types.js';\nimport { useDataOverride } from '../../sdk/data/data-override-context.js';\nimport { PaymentSubmissionProvider } from '../../sdk/payment/submission-registry.js';\nimport {\n DEFAULT_METHOD_GROUP,\n PaymentContext,\n type PaymentContextValue,\n type PaymentSectionRootData,\n} from './payment.js';\nimport { PaymentCardCaptureProvider } from './payment-card-capture.js';\nimport { usePaymentMethodSelection } from './use-payment-method-selection.js';\n\n/**\n * The collapsed payment section (centered modal / slide-in panel) as a state-only controller\n * (specs/payment-section-root.md, T5; docs/features/credit-card/rfc.md § D1). The page composes a raw\n * `DialogRoot` or `DrawerRoot` and each of its particles (`DialogTrigger` / `DialogBackdrop` /\n * `DialogPopup` …) directly as `page.json` nodes, so every part — including the portaled backdrop and\n * popup a descendant selector could not reach — is a swatch-addressable node with zero Tailwind baked\n * into the package, exactly as `DeliveryOptionsController` established.\n *\n * `PaymentSectionController` renders no markup: it runs the shared `usePaymentMethodSelection` engine,\n * holds the open state, provides the same `payment` context `PaymentSectionRoot` does (ADR-0009 matches\n * by contract identifier, so every leaf composes under either with no edit), then injects\n * `open` / `onOpenChange` into its single overlay-`Root` child via `cloneElement` — the same mechanism\n * as `CartOpenOnAdd` and `ShippingAddressSavedAddressDrawerController`.\n *\n * It diverges from `DeliveryOptionsController` in one deliberate way: a successful method selection\n * does **not** close the surface. Picking a delivery option completes that interaction; picking a\n * payment method is the first step of several — the shopper still types a card, picks an installment,\n * and places the order. Closing is therefore the composition's call, through the context's `setOpen`\n * (T14 on a placed order) or a `DrawerClose` / `DialogClose` particle.\n *\n * The trigger holds a static label (`Text`): no component echoes the current choice there, and none is\n * shipped here — `payment.md` documents the same composition.\n */\n\n// Repeats `PaymentSectionData`'s selection set verbatim under its own name. Two definitions cannot\n// share one fragment name in a page query, and the native catalog builder resolves\n// `defineComponent({ fragment })` statically — a value imported from another module is silently\n// dropped from the built catalog. `delivery-options` duplicates for the same reason;\n// `payment.test.tsx` asserts the two sets stay field-for-field identical.\nconst fragment = /* GraphQL */ `\n fragment PaymentSectionControllerData on Query {\n payment {\n __typename\n id\n methods {\n __typename\n id\n name\n groupName\n validator {\n __typename\n numberMask\n numberRegex\n cvvMask\n cvvRegex\n cvvRequired\n expirationRequired\n holderNameRequired\n billingAddressRequired\n documentDisplayable\n documentRequired\n }\n }\n selectedMethodId\n selectedAccountId\n selectedBin\n }\n cart {\n __typename\n id\n total {\n __typename\n amount\n currencyCode\n }\n }\n }\n`;\n\n// The minimal open-state shape the controller injects into its overlay-Root child; both `DialogRoot`\n// and `DrawerRoot` accept it.\ntype OverlayOpenProps = {\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n};\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport type PaymentSectionControllerProps = {\n /**\n * Scopes the method list to a **set** of `PaymentMethod.groupName` values — a method is in scope\n * when its `groupName` is a member (T140, FR-1, Decision 1). A single string is still accepted and\n * scopes to exactly that one group. An empty string scopes nothing.\n */\n group?: string | readonly string[];\n /** Keyed `{ payment, cart }` forwarded by the reactive runtime (arity-2 fragment, ADR-0015). */\n $data?: PaymentSectionRootData;\n /** Compiler-injected action surface; carries `payment.setMethod`, `payment.sendPayments`, and `analytics.track`. */\n $actions?: ComponentActions;\n /** The single overlay `Root` to control — a `DialogRoot` (modal) or `DrawerRoot` (slide-in). */\n children?: ReactNode;\n};\n\n// ---------------------------------------------------------------------------\n// Definition\n// ---------------------------------------------------------------------------\n\nexport const PaymentSectionControllerDefinition = defineComponent<PaymentSectionControllerProps>({\n name: 'PaymentSectionController',\n importPath: '@vtex/faststore/components',\n component: PaymentSectionController,\n fragment,\n fetchStrategy: 'reactive',\n actions: { payment: ['setMethod', 'sendPayments'], analytics: ['track'] },\n providesContext: ['payment', 'card-capture'],\n hardened: true,\n editor: { label: 'Payment Section Controller', category: 'commerce' },\n schema: {\n // Literal, not `DEFAULT_METHOD_GROUP` — see the same note on `PaymentSectionRootDefinition`.\n // T140, Decision 2/OQ-6: same widened shape as `PaymentSectionRootDefinition` — see its own note.\n group: {\n type: 'array',\n default: ['creditCardPaymentGroup', 'debitCardPaymentGroup'],\n label: 'Payment method group',\n },\n },\n guideline:\n \"State-only controller for a collapsed payment section: wrap a single DialogRoot (centered modal) or DrawerRoot (slide-in) child and it becomes controlled. Renders no markup and bakes no styling — compose the overlay particles (DialogTrigger/DialogPortal/DialogBackdrop/DialogPopup or the Drawer equivalents) directly as page nodes, put a static label (Text) inside the trigger — no component echoes the current choice there, and put PaymentMethodList plus the payment leaves (CardEntry, Installments, SavedCards, PlaceOrder, …) inside the popup. Provides the same 'payment' and 'card-capture' contexts as PaymentSectionRoot, so every leaf composes under either with no change. Unlike the delivery-options controller it does NOT close on a successful selection — picking a method is mid-flow — so close it from a DrawerClose/DialogClose particle or from the leaf that finishes the flow. See payment.md.\",\n // The convention-based `<file-stem>.md` (`payment-controller.md`) does not exist — this component's\n // doc is `payment.md`, shared with PaymentSectionRoot/PaymentMethodList (T25/FR-8).\n docPath: './payment.md',\n});\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nexport function PaymentSectionController({\n group = DEFAULT_METHOD_GROUP,\n $data: $dataProp,\n $actions: $actionsProp,\n children,\n}: Readonly<PaymentSectionControllerProps>) {\n const $data = useDataOverride($dataProp);\n const $actions = useActionsOverride($actionsProp);\n const selection = usePaymentMethodSelection({ group, $data: $data?.payment ?? null, $actions });\n const [open, setOpen] = useState(false);\n const payment = useMemo<PaymentContextValue>(() => ({ ...selection, open, setOpen }), [selection, open]);\n\n if (!isValidElement<OverlayOpenProps>(children)) {\n return children;\n }\n\n return (\n <PaymentContext value={payment}>\n <PaymentSubmissionProvider path={selection.draft.path}>\n <PaymentCardCaptureProvider selection={selection} cart={$data?.cart} $actions={$actions}>\n {cloneElement(children, { open, onOpenChange: setOpen })}\n </PaymentCardCaptureProvider>\n </PaymentSubmissionProvider>\n </PaymentContext>\n );\n}\n"],"mappings":";;;;;;;;;;;AAoHA,MAAa,qCAAqC,gBAA+C;CAC/F,MAAM;CACN,YAAY;CACZ,WAAW;CACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CACA,eAAe;CACf,SAAS;EAAE,SAAS,CAAC,aAAa,cAAc;EAAG,WAAW,CAAC,OAAO;CAAE;CACxE,iBAAiB,CAAC,WAAW,cAAc;CAC3C,UAAU;CACV,QAAQ;EAAE,OAAO;EAA8B,UAAU;CAAW;CACpE,QAAQ,EAGN,OAAO;EACL,MAAM;EACN,SAAS,CAAC,0BAA0B,uBAAuB;EAC3D,OAAO;CACT,EACF;CACA,WACE;CAGF,SAAS;AACX,CAAC;AAMD,SAAgB,yBAAyB,EACvC,QAAQ,sBACR,OAAO,WACP,UAAU,cACV,YAC0C;CAC1C,MAAM,QAAQ,gBAAgB,SAAS;CACvC,MAAM,WAAW,mBAAmB,YAAY;CAChD,MAAM,YAAY,0BAA0B;EAAE;EAAO,OAAO,OAAO,WAAW;EAAM;CAAS,CAAC;CAC9F,MAAM,CAAC,MAAM,WAAW,SAAS,KAAK;CACtC,MAAM,UAAU,eAAoC;EAAE,GAAG;EAAW;EAAM;CAAQ,IAAI,CAAC,WAAW,IAAI,CAAC;CAEvG,IAAI,CAAC,eAAiC,QAAQ,GAC5C,OAAO;CAGT,OACE,oBAAC,gBAAD;EAAgB,OAAO;EACrB,UAAA,oBAAC,2BAAD;GAA2B,MAAM,UAAU,MAAM;GAC/C,UAAA,oBAAC,4BAAD;IAAuC;IAAW,MAAM,OAAO;IAAgB;IAC5E,UAAA,aAAa,UAAU;KAAE;KAAM,cAAc;IAAQ,CAAC;GAC7B,CAAA;EACH,CAAA;CACb,CAAA;AAEpB"}
|