@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
package/dist/internal/server.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import { resolveSignInHref } from "../utils/safe-href.js";
|
|
1
2
|
import { buildStorefrontContextHeaders } from "../sdk/context/headers.js";
|
|
2
3
|
import { createClient } from "../sdk/client/create-client.js";
|
|
3
4
|
import { fetchPageData } from "../sdk/client/fetch-page-data.js";
|
|
4
5
|
import { registerPreloadQuery } from "../sdk/client/register-preload-query.js";
|
|
6
|
+
import { variablesFromContent } from "../sdk/data/variables-from-content.js";
|
|
5
7
|
import { getIntl, loadMessages } from "../sdk/i18n/server.js";
|
|
6
|
-
|
|
8
|
+
import { readServerSession } from "../sdk/session/read-server-session.js";
|
|
9
|
+
export { buildStorefrontContextHeaders, createClient, fetchPageData, getIntl, loadMessages, readServerSession, registerPreloadQuery, resolveSignInHref, variablesFromContent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account-access-gate.js","names":[],"sources":["../../../src/matter/account-access-gate/account-access-gate.tsx"],"sourcesContent":["'use client';\n\nimport { type ContentValue, defineComponent, defineContentType } from '@vtex/fs-core';\nimport { usePathname, useRouter } from 'next/navigation';\nimport { type ComponentPropsWithRef, type ReactNode, useEffect, useRef, useState } from 'react';\nimport { flushSync } from 'react-dom';\nimport { NavigationLink } from '../../particles/navigation-link/navigation-link.js';\nimport { useSessionRevalidation } from '../../sdk/session/use-session-revalidation.js';\nimport { resolveSignInHref } from '../../utils/safe-href.js';\nimport { type SessionState, useSession } from '../session/session.js';\nimport { useSignOutIntent, withdrawSignOutIntent } from './sign-out-intent.js';\n\n// Nothing is required, following the shipped identity components: an entry may author any subset, and\n// a slice missing a required property is shape-invalid, which drops the whole element rather than the\n// one field.\nexport const AccountAccessGateContent = defineContentType({\n id: 'account-access-gate',\n title: 'Account Access Gate',\n description: 'What the shopper is told while the account resolves and when it will not open for them.',\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n loadingLabel: { type: 'string', minLength: 1, title: 'Loading announcement' },\n expiredMessage: { type: 'string', minLength: 1, title: 'Session ended message' },\n signInIncompleteMessage: { type: 'string', minLength: 1, title: 'Sign-in did not complete message' },\n signInLabel: { type: 'string', minLength: 1, title: 'Sign-in link label' },\n },\n },\n});\n\n/** Why the account will not open, as a bounded value: a style target and the choice of message. */\nexport type AccountAccessGateNoticeReason = 'expired' | 'sign-in-incomplete';\n\n/** Props for {@link AccountAccessGate}. It renders a different element per outcome and forwards no\n * element props of its own; each rendered part carries its own. */\nexport type AccountAccessGateProps = {\n /** Text announced while the session resolves. */\n loadingLabel?: string;\n /** What a shopper whose session ended mid-visit is told. */\n expiredMessage?: string;\n /** What a shopper who came back from sign-in still signed out is told. */\n signInIncompleteMessage?: string;\n /** Label of the link out of either notice. Without it no link renders — a focusable link a screen\n * reader announces as its bare URL is worse than no control at all. */\n signInLabel?: string;\n /** Merchant-authored fields, sliced from the layout content entry; win over the props field by field\n * when present. Absent in a non-CMS store — the props are the fallback. */\n $content?: ContentValue<typeof AccountAccessGateContent>;\n /** The account. Rendered only for a signed-in shopper. */\n children?: ReactNode;\n};\n\n/** Props for {@link AccountAccessGateLoading}. Extends native `<output>` attributes. */\nexport type AccountAccessGateLoadingProps = ComponentPropsWithRef<'output'>;\n\n/** Props for {@link AccountAccessGateNotice}. Extends native `<output>` attributes. */\nexport type AccountAccessGateNoticeProps = Omit<ComponentPropsWithRef<'output'>, 'children'> & {\n reason: AccountAccessGateNoticeReason;\n /** The message for this reason. Nothing renders in its place when unauthored. */\n message?: string;\n /** Where the link out leads, built by the gate from the page the shopper is on. */\n signInHref: string;\n /** Label of the link out. No label, no link. */\n signInLabel?: string;\n};\n\nexport const AccountAccessGateDefinition = defineComponent<AccountAccessGateProps>({\n name: 'AccountAccessGate',\n importPath: '@vtex/faststore/components',\n component: AccountAccessGate,\n content: AccountAccessGateContent,\n editor: { label: 'Account Access Gate', category: 'identity' },\n requiresContext: 'session',\n schema: {\n // Mirrored from the content model on purpose, as every content-bearing component in the library\n // does: the entry wins when published, and this is what a store without a CMS authors.\n loadingLabel: { type: 'string', label: 'Loading Announcement' },\n expiredMessage: { type: 'string', label: 'Session Ended Message' },\n signInIncompleteMessage: { type: 'string', label: 'Sign-in Did Not Complete Message' },\n signInLabel: { type: 'string', label: 'Sign-in Link Label' },\n },\n guideline:\n \"The account's single access decision: place it once in the account layout, wrapping the body, and every page that declares that layout inherits it — never restate it per section. It renders its children only for a logged-in shopper; it shows a composed loading look while the session resolves, replaces the current history entry with the sign-in destination for a visitor who arrived signed out (identified counts as signed out), tells a shopper whose session ended mid-visit rather than bouncing them, and stands down while AccountMenuSignOut navigates. It redirects at most once per visit: a shopper who comes back from sign-in still signed out gets a message and a link rather than a second hop. Must be inside SessionRoot, which the same layout hosts. Never place the /login route under it — the gate redirects there, and a gated /login would redirect to itself.\",\n});\n\n/** The one automatic hop the gate has already spent, surviving the full document load out to the\n * platform and back, and no further than this tab. */\nconst SIGN_IN_ATTEMPT_KEY = 'fs::account-access-gate::sign-in-attempt';\n\n/**\n * What the gate renders, in precedence order. `signing-in` covers both the frame that decides whether\n * the hop is still available and the frame after the replace is issued: they render the same nothing,\n * and only the effect tells them apart.\n */\ntype AccountAccessGateOutcome = 'stand-down' | 'expired' | 'loading' | 'account' | 'sign-in-incomplete' | 'signing-in';\n\nexport function AccountAccessGate({\n loadingLabel,\n expiredMessage,\n signInIncompleteMessage,\n signInLabel,\n $content,\n children,\n}: Readonly<AccountAccessGateProps>) {\n const { state, loading } = useSession();\n const signingOut = useSignOutIntent();\n const pathname = usePathname();\n const router = useRouter();\n const revalidate = useSessionRevalidation();\n\n // Whether this gate has ever resolved to a signed-in shopper. It is what separates a session that\n // ended from a visitor who arrived signed out — the tri-state spells both `anonymous`.\n const [wasSignedIn, setWasSignedIn] = useState(false);\n // A revalidation that could not answer. It outranks `loading` because the discard that preceded it\n // is what leaves the session unresolved, so nothing else is coming to end that wait.\n const [unconfirmed, setUnconfirmed] = useState(false);\n // A re-read in flight. The gate withholds the account for itself rather than waiting to be told:\n // discarding the cached session leaves the data layer unresolved, but it reaches the gate only once\n // the watched query has re-read, and the account must be gone in the frame the restore arrives.\n const [revalidating, setRevalidating] = useState(false);\n // Which re-read the gate is still listening to. Two restores in a row put two answers in flight, and\n // the older one may land last.\n const restoreGeneration = useRef(0);\n // `null` until the arrival path has read the record. Read from an effect rather than from the render\n // body: session storage does not exist on the server, and a value that appeared between the server\n // pass and hydration would change what renders underneath it.\n const [hopSpent, setHopSpent] = useState<boolean | null>(null);\n // `null` until the document has been read, for the same two reasons, and read from the document\n // rather than through `useSearchParams()`, which would require a `Suspense` boundary the generator\n // does not emit on a prerendered route — the reason `SignInRedirect` gives for reading it this way.\n const [search, setSearch] = useState<string | null>(null);\n\n // Deliberately on every commit rather than on mount: `usePathname()` re-renders the gate when the\n // path changes but says nothing about the query, and a shopper who pages through their orders\n // changes only the query. Setting the same string is a bail-out, so this does not loop.\n useEffect(() => {\n setSearch(globalThis.location.search);\n });\n\n // Where the shopper comes back to. `usePathname()` yields the path alone, so a gate that stopped\n // there would return someone reading `/account/orders?page=2` to the first page of it.\n const returnPath = pathname === null ? null : `${pathname}${search ?? ''}`;\n\n const outcome = resolveOutcome({ signingOut, unconfirmed, revalidating, loading, state, wasSignedIn, hopSpent });\n\n useEffect(() => {\n switch (outcome) {\n case 'account':\n setWasSignedIn(true);\n setUnconfirmed(false);\n clearSignInAttempt();\n return;\n case 'expired':\n case 'sign-in-incomplete':\n // Every outcome that is not the hop returns it: a shopper who signs in, browses, and comes\n // back later arrives fresh rather than carrying a spent attempt from an earlier one.\n clearSignInAttempt();\n return;\n case 'signing-in': {\n // One more frame before deciding, until the document has been read: a hop recorded against the\n // bare path is the one the shopper comes back to, and there is no second chance at it.\n if (hopSpent !== null || search === null) {\n return;\n }\n if (readSignInAttempt() !== null) {\n setHopSpent(true);\n return;\n }\n const destination = resolveSignInHref(returnPath);\n recordSignInAttempt(destination);\n setHopSpent(false);\n // Replace rather than push: back from the platform's login should reach the page the shopper\n // came from, not the account that threw them at it.\n // react-doctor-disable-next-line nextjs-no-client-side-redirect -- the session resolves on the client, so the server has nothing to decide with\n router.replace(destination);\n return;\n }\n case 'stand-down':\n case 'loading':\n return;\n default:\n assertUnreachable(outcome);\n }\n }, [outcome, hopSpent, search, returnPath, router]);\n\n useEffect(() => {\n function handlePageHide(event: PageTransitionEvent): void {\n if (!event.persisted) {\n return;\n }\n // What the browser freezes is the DOM, and a restore puts that same DOM back before any script\n // runs. Standing the account down on the way out rather than on the way back is what keeps the\n // restored document from showing it in the frames before `pageshow` can decide again.\n flushSync(() => {\n setRevalidating(true);\n });\n }\n\n function handlePageShow(event: PageTransitionEvent): void {\n // An ordinary load re-decides by mounting. Only a restore resumes a heap that already holds an\n // answer, and `persisted` is the browser's own word for it.\n if (!event.persisted) {\n return;\n }\n const generation = restoreGeneration.current + 1;\n restoreGeneration.current = generation;\n // The navigation this authorized has already happened; a restored document holding it would\n // stand down forever. Withdrawn before the re-read so the gate is deciding again by the time\n // the answer lands.\n withdrawSignOutIntent();\n setUnconfirmed(false);\n setRevalidating(true);\n void revalidate().then((result) => {\n // A later restore has already asked the same question, and its answer is the one that counts.\n // This one describes a session the gate has since discarded a second time.\n if (generation !== restoreGeneration.current) {\n return;\n }\n setRevalidating(false);\n switch (result) {\n case 'failed':\n setUnconfirmed(true);\n return;\n case 'revalidated':\n case 'unavailable':\n // Nothing left to distrust: either the session was re-read, or there was no cached\n // session to discard in the first place and the one in the tree came from a prop.\n return;\n default:\n assertUnreachable(result);\n }\n });\n }\n\n globalThis.addEventListener('pagehide', handlePageHide);\n globalThis.addEventListener('pageshow', handlePageShow);\n return () => {\n globalThis.removeEventListener('pagehide', handlePageHide);\n globalThis.removeEventListener('pageshow', handlePageShow);\n };\n }, [revalidate]);\n\n // The intent authorizes one transition and this gate is its only reader, so it must not survive the\n // gate. A sign-out that navigates client-side takes the account layout down without reloading the\n // document, and nothing else would ever take the flag back: the next account page the shopper opens\n // would mount into a standing intent and render nothing at all, with no error to explain it.\n useEffect(() => withdrawSignOutIntent, []);\n\n // Blank entry fields fall through, so clearing one in the Admin reads as unauthored.\n const entryLoadingLabel = $content?.loadingLabel?.trim() ? $content.loadingLabel : loadingLabel;\n const entryExpiredMessage = $content?.expiredMessage?.trim() ? $content.expiredMessage : expiredMessage;\n const entryIncompleteMessage = $content?.signInIncompleteMessage?.trim()\n ? $content.signInIncompleteMessage\n : signInIncompleteMessage;\n const entrySignInLabel = $content?.signInLabel?.trim() ? $content.signInLabel : signInLabel;\n\n switch (outcome) {\n case 'stand-down':\n case 'signing-in':\n return null;\n case 'loading':\n return (\n // The part carries its own hook; the component's identity travels from here, which is how a\n // store targets it by name the way every other component is targeted.\n <AccountAccessGateLoading data-fs-account-access-gate=\"\">{entryLoadingLabel}</AccountAccessGateLoading>\n );\n case 'account':\n return <>{children}</>;\n case 'expired':\n case 'sign-in-incomplete':\n return (\n <AccountAccessGateNotice\n data-fs-account-access-gate=\"\"\n reason={outcome === 'expired' ? 'expired' : 'sign-in-incomplete'}\n message={outcome === 'expired' ? entryExpiredMessage : entryIncompleteMessage}\n signInHref={resolveSignInHref(returnPath)}\n signInLabel={entrySignInLabel}\n />\n );\n default:\n return assertUnreachable(outcome);\n }\n}\n\n/**\n * The whole decision, as one ordered read of the gate's inputs.\n *\n * `signingOut` outranks everything, including a session still reading `loggedIn`: the sign-out records\n * its intent before it awaits the mutation, and the frame between the payload landing and the document\n * load starting is exactly the one this ordering protects.\n *\n * `loading` outranks the tri-state for the reason `AccountEntryPoint` gives: an unresolved session\n * reports `anonymous`, so reading the state first would bounce a shopper who is signed in. A re-read\n * in flight reads as the same wait: the session it is checking is one the gate has stopped believing.\n */\nfunction resolveOutcome({\n signingOut,\n unconfirmed,\n revalidating,\n loading,\n state,\n wasSignedIn,\n hopSpent,\n}: {\n signingOut: boolean;\n unconfirmed: boolean;\n revalidating: boolean;\n loading: boolean;\n state: SessionState;\n wasSignedIn: boolean;\n hopSpent: boolean | null;\n}): AccountAccessGateOutcome {\n if (signingOut) {\n return 'stand-down';\n }\n // A re-read that could not answer says nothing about how the shopper got here, so the notice keeps\n // the history the gate already has. Telling someone who never reached the account that their session\n // ended names an event that never happened; the incomplete sign-in is the one they actually had.\n if (unconfirmed) {\n return wasSignedIn ? 'expired' : 'sign-in-incomplete';\n }\n if (revalidating || loading) {\n return 'loading';\n }\n if (state === 'loggedIn') {\n return 'account';\n }\n if (wasSignedIn) {\n return 'expired';\n }\n return hopSpent === true ? 'sign-in-incomplete' : 'signing-in';\n}\n\nfunction assertUnreachable(outcome: never): never {\n throw new Error(`[AccountAccessGate] unhandled outcome: ${String(outcome)}`);\n}\n\n/**\n * The look of a session that has not answered yet. A real part with its own hook rather than an ad hoc\n * spinner, so a store can style it and a story can render it.\n */\nexport function AccountAccessGateLoading({ className, children, ...props }: AccountAccessGateLoadingProps) {\n return (\n <output {...props} aria-live=\"polite\" className={className} data-fs-account-access-gate-loading=\"\">\n {children}\n </output>\n );\n}\n\n/**\n * What renders in the account's place when it will not open: the message for this reason, and a link\n * the shopper may take back into sign-in.\n *\n * The link is the whole of the escape from a sign-in loop. The gate stops redirecting after one\n * automatic hop, so the next attempt is a click rather than a bounce — and a shopper who keeps landing\n * here at least lands on a page that says so.\n */\nexport function AccountAccessGateNotice({\n reason,\n message,\n signInHref,\n signInLabel,\n className,\n ...props\n}: AccountAccessGateNoticeProps) {\n return (\n <output\n {...props}\n aria-live=\"polite\"\n className={className}\n data-fs-account-access-gate-notice=\"\"\n data-fs-account-access-gate-notice-reason={reason}\n >\n {message ? <span data-fs-account-access-gate-notice-message=\"\">{message}</span> : null}\n {signInLabel?.trim() ? (\n <NavigationLink\n href={signInHref}\n // The destination is a trampoline that redirects on mount, so the default prefetch would\n // fire that GET from a page the shopper may never leave.\n prefetch={false}\n data-fs-account-access-gate-notice-action=\"\"\n >\n {signInLabel}\n </NavigationLink>\n ) : null}\n </output>\n );\n}\n\n/**\n * Session storage, guarded at every access. A browser that refuses it — a shopper blocking site data —\n * throws rather than returning null, and a gate that cannot read its own record still has a shopper to\n * get to sign-in. A refusal therefore reads as \"no record\", which spends the hop; the cost is that the\n * loop protection is absent in that browser, which is the lesser of the two failures.\n */\nfunction readSignInAttempt(): string | null {\n try {\n return globalThis.sessionStorage.getItem(SIGN_IN_ATTEMPT_KEY);\n } catch {\n return null;\n }\n}\n\nfunction recordSignInAttempt(destination: string): void {\n try {\n globalThis.sessionStorage.setItem(SIGN_IN_ATTEMPT_KEY, destination);\n } catch {\n // Nothing to fall back to: the record is the only thing that outlives the hop.\n }\n}\n\nfunction clearSignInAttempt(): void {\n try {\n globalThis.sessionStorage.removeItem(SIGN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,SAAwC;CACzG,OACE,oBAAC,UAAD;EAAQ,GAAI;EAAO,aAAU;EAAoB;EAAW,uCAAoC;EAC7F;CACK,CAAA;AAEZ;;;;;;;;;AAUA,SAAgB,wBAAwB,EACtC,QACA,SACA,YACA,aACA,WACA,GAAG,SAC4B;CAC/B,OACE,qBAAC,UAAD;EACE,GAAI;EACJ,aAAU;EACC;EACX,sCAAmC;EACnC,6CAA2C;EAL7C,UAAA,CAOG,UAAU,oBAAC,QAAD;GAAM,8CAA2C;GAAI,UAAA;EAAc,CAAA,IAAI,MACjF,aAAa,KAAK,IACjB,oBAAC,gBAAD;GACE,MAAM;GAGN,UAAU;GACV,6CAA0C;GAEzC,UAAA;EACa,CAAA,IACd,IACE;;AAEZ;;;;;;;AAQA,SAAS,oBAAmC;CAC1C,IAAI;EACF,OAAO,WAAW,eAAe,QAAQ,mBAAmB;CAC9D,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,oBAAoB,aAA2B;CACtD,IAAI;EACF,WAAW,eAAe,QAAQ,qBAAqB,WAAW;CACpE,QAAQ,CAER;AACF;AAEA,SAAS,qBAA2B;CAClC,IAAI;EACF,WAAW,eAAe,WAAW,mBAAmB;CAC1D,QAAQ,CAER;AACF"}
|
|
1
|
+
{"version":3,"file":"account-access-gate.js","names":[],"sources":["../../../src/matter/account-access-gate/account-access-gate.tsx"],"sourcesContent":["'use client';\n\nimport { type ContentValue, defineComponent, defineContentType } from '@vtex/fs-core';\nimport { usePathname, useRouter } from 'next/navigation';\nimport { type ComponentPropsWithRef, type ReactNode, useEffect, useRef, useState } from 'react';\nimport { flushSync } from 'react-dom';\nimport { NavigationLink } from '../../particles/navigation-link/navigation-link.js';\nimport { useSessionRevalidation } from '../../sdk/session/use-session-revalidation.js';\nimport { resolveSignInHref } from '../../utils/safe-href.js';\nimport { type SessionState, useSession } from '../session/session.js';\nimport { useSignOutIntent, withdrawSignOutIntent } from './sign-out-intent.js';\n\n// Nothing is required, following the shipped identity components: an entry may author any subset, and\n// a slice missing a required property is shape-invalid, which drops the whole element rather than the\n// one field.\nexport const AccountAccessGateContent = defineContentType({\n id: 'account-access-gate',\n title: 'Account Access Gate',\n description: 'What the shopper is told while the account resolves and when it will not open for them.',\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n loadingLabel: { type: 'string', minLength: 1, title: 'Loading announcement' },\n expiredMessage: { type: 'string', minLength: 1, title: 'Session ended message' },\n signInIncompleteMessage: { type: 'string', minLength: 1, title: 'Sign-in did not complete message' },\n signInLabel: { type: 'string', minLength: 1, title: 'Sign-in link label' },\n },\n },\n});\n\n/** Why the account will not open, as a bounded value: a style target and the choice of message. */\nexport type AccountAccessGateNoticeReason = 'expired' | 'sign-in-incomplete';\n\n/** Props for {@link AccountAccessGate}. It renders a different element per outcome and forwards no\n * element props of its own; each rendered part carries its own. */\nexport type AccountAccessGateProps = {\n /** Text announced while the session resolves. */\n loadingLabel?: string;\n /** What a shopper whose session ended mid-visit is told. */\n expiredMessage?: string;\n /** What a shopper who came back from sign-in still signed out is told. */\n signInIncompleteMessage?: string;\n /** Label of the link out of either notice. Without it no link renders — a focusable link a screen\n * reader announces as its bare URL is worse than no control at all. */\n signInLabel?: string;\n /** Merchant-authored fields, sliced from the layout content entry; win over the props field by field\n * when present. Absent in a non-CMS store — the props are the fallback. */\n $content?: ContentValue<typeof AccountAccessGateContent>;\n /** The account. Rendered only for a signed-in shopper. */\n children?: ReactNode;\n};\n\n/** Props for {@link AccountAccessGateLoading}. Extends native `<output>` attributes. */\nexport type AccountAccessGateLoadingProps = ComponentPropsWithRef<'output'>;\n\n/** Props for {@link AccountAccessGateNotice}. Extends native `<output>` attributes. */\nexport type AccountAccessGateNoticeProps = Omit<ComponentPropsWithRef<'output'>, 'children'> & {\n reason: AccountAccessGateNoticeReason;\n /** The message for this reason. Nothing renders in its place when unauthored. */\n message?: string;\n /** Where the link out leads, built by the gate from the page the shopper is on. */\n signInHref: string;\n /** Label of the link out. No label, no link. */\n signInLabel?: string;\n};\n\nexport const AccountAccessGateDefinition = defineComponent<AccountAccessGateProps>({\n name: 'AccountAccessGate',\n importPath: '@vtex/faststore/components',\n component: AccountAccessGate,\n content: AccountAccessGateContent,\n editor: { label: 'Account Access Gate', category: 'identity' },\n requiresContext: 'session',\n schema: {\n // Mirrored from the content model on purpose, as every content-bearing component in the library\n // does: the entry wins when published, and this is what a store without a CMS authors.\n loadingLabel: { type: 'string', label: 'Loading Announcement' },\n expiredMessage: { type: 'string', label: 'Session Ended Message' },\n signInIncompleteMessage: { type: 'string', label: 'Sign-in Did Not Complete Message' },\n signInLabel: { type: 'string', label: 'Sign-in Link Label' },\n },\n guideline:\n \"The account's single access decision: place it once in the account layout, wrapping the body, and every page that declares that layout inherits it — never restate it per section. It renders its children only for a logged-in shopper; it shows a composed loading look while the session resolves, replaces the current history entry with the sign-in destination for a visitor who arrived signed out (identified counts as signed out), tells a shopper whose session ended mid-visit rather than bouncing them, and stands down while AccountMenuSignOut navigates. It redirects at most once per visit: a shopper who comes back from sign-in still signed out gets a message and a link rather than a second hop. Must be inside SessionRoot, which the same layout hosts. Never place the /login route under it — the gate redirects there, and a gated /login would redirect to itself.\",\n});\n\n/** The one automatic hop the gate has already spent, surviving the full document load out to the\n * platform and back, and no further than this tab. */\nconst SIGN_IN_ATTEMPT_KEY = 'fs::account-access-gate::sign-in-attempt';\n\n/**\n * What the gate renders, in precedence order. `signing-in` covers both the frame that decides whether\n * the hop is still available and the frame after the replace is issued: they render the same nothing,\n * and only the effect tells them apart.\n */\ntype AccountAccessGateOutcome = 'stand-down' | 'expired' | 'loading' | 'account' | 'sign-in-incomplete' | 'signing-in';\n\nexport function AccountAccessGate({\n loadingLabel,\n expiredMessage,\n signInIncompleteMessage,\n signInLabel,\n $content,\n children,\n}: Readonly<AccountAccessGateProps>) {\n const { state, loading } = useSession();\n const signingOut = useSignOutIntent();\n const pathname = usePathname();\n const router = useRouter();\n const revalidate = useSessionRevalidation();\n\n // Whether this gate has ever resolved to a signed-in shopper. It is what separates a session that\n // ended from a visitor who arrived signed out — the tri-state spells both `anonymous`.\n const [wasSignedIn, setWasSignedIn] = useState(false);\n // A revalidation that could not answer. It outranks `loading` because the discard that preceded it\n // is what leaves the session unresolved, so nothing else is coming to end that wait.\n const [unconfirmed, setUnconfirmed] = useState(false);\n // A re-read in flight. The gate withholds the account for itself rather than waiting to be told:\n // discarding the cached session leaves the data layer unresolved, but it reaches the gate only once\n // the watched query has re-read, and the account must be gone in the frame the restore arrives.\n const [revalidating, setRevalidating] = useState(false);\n // Which re-read the gate is still listening to. Two restores in a row put two answers in flight, and\n // the older one may land last.\n const restoreGeneration = useRef(0);\n // `null` until the arrival path has read the record. Read from an effect rather than from the render\n // body: session storage does not exist on the server, and a value that appeared between the server\n // pass and hydration would change what renders underneath it.\n const [hopSpent, setHopSpent] = useState<boolean | null>(null);\n // `null` until the document has been read, for the same two reasons, and read from the document\n // rather than through `useSearchParams()`, which would require a `Suspense` boundary the generator\n // does not emit on a prerendered route — the reason `SignInRedirect` gives for reading it this way.\n const [search, setSearch] = useState<string | null>(null);\n\n // Deliberately on every commit rather than on mount: `usePathname()` re-renders the gate when the\n // path changes but says nothing about the query, and a shopper who pages through their orders\n // changes only the query. Setting the same string is a bail-out, so this does not loop.\n useEffect(() => {\n setSearch(globalThis.location.search);\n });\n\n // Where the shopper comes back to. `usePathname()` yields the path alone, so a gate that stopped\n // there would return someone reading `/pvt/orders?page=2` to the first page of it.\n const returnPath = pathname === null ? null : `${pathname}${search ?? ''}`;\n\n const outcome = resolveOutcome({ signingOut, unconfirmed, revalidating, loading, state, wasSignedIn, hopSpent });\n\n useEffect(() => {\n switch (outcome) {\n case 'account':\n setWasSignedIn(true);\n setUnconfirmed(false);\n clearSignInAttempt();\n return;\n case 'expired':\n case 'sign-in-incomplete':\n // Every outcome that is not the hop returns it: a shopper who signs in, browses, and comes\n // back later arrives fresh rather than carrying a spent attempt from an earlier one.\n clearSignInAttempt();\n return;\n case 'signing-in': {\n // One more frame before deciding, until the document has been read: a hop recorded against the\n // bare path is the one the shopper comes back to, and there is no second chance at it.\n if (hopSpent !== null || search === null) {\n return;\n }\n if (readSignInAttempt() !== null) {\n setHopSpent(true);\n return;\n }\n const destination = resolveSignInHref(returnPath);\n recordSignInAttempt(destination);\n setHopSpent(false);\n // Replace rather than push: back from the platform's login should reach the page the shopper\n // came from, not the account that threw them at it.\n // react-doctor-disable-next-line nextjs-no-client-side-redirect -- the session resolves on the client, so the server has nothing to decide with\n router.replace(destination);\n return;\n }\n case 'stand-down':\n case 'loading':\n return;\n default:\n assertUnreachable(outcome);\n }\n }, [outcome, hopSpent, search, returnPath, router]);\n\n useEffect(() => {\n function handlePageHide(event: PageTransitionEvent): void {\n if (!event.persisted) {\n return;\n }\n // What the browser freezes is the DOM, and a restore puts that same DOM back before any script\n // runs. Standing the account down on the way out rather than on the way back is what keeps the\n // restored document from showing it in the frames before `pageshow` can decide again.\n flushSync(() => {\n setRevalidating(true);\n });\n }\n\n function handlePageShow(event: PageTransitionEvent): void {\n // An ordinary load re-decides by mounting. Only a restore resumes a heap that already holds an\n // answer, and `persisted` is the browser's own word for it.\n if (!event.persisted) {\n return;\n }\n const generation = restoreGeneration.current + 1;\n restoreGeneration.current = generation;\n // The navigation this authorized has already happened; a restored document holding it would\n // stand down forever. Withdrawn before the re-read so the gate is deciding again by the time\n // the answer lands.\n withdrawSignOutIntent();\n setUnconfirmed(false);\n setRevalidating(true);\n void revalidate().then((result) => {\n // A later restore has already asked the same question, and its answer is the one that counts.\n // This one describes a session the gate has since discarded a second time.\n if (generation !== restoreGeneration.current) {\n return;\n }\n setRevalidating(false);\n switch (result) {\n case 'failed':\n setUnconfirmed(true);\n return;\n case 'revalidated':\n case 'unavailable':\n // Nothing left to distrust: either the session was re-read, or there was no cached\n // session to discard in the first place and the one in the tree came from a prop.\n return;\n default:\n assertUnreachable(result);\n }\n });\n }\n\n globalThis.addEventListener('pagehide', handlePageHide);\n globalThis.addEventListener('pageshow', handlePageShow);\n return () => {\n globalThis.removeEventListener('pagehide', handlePageHide);\n globalThis.removeEventListener('pageshow', handlePageShow);\n };\n }, [revalidate]);\n\n // The intent authorizes one transition and this gate is its only reader, so it must not survive the\n // gate. A sign-out that navigates client-side takes the account layout down without reloading the\n // document, and nothing else would ever take the flag back: the next account page the shopper opens\n // would mount into a standing intent and render nothing at all, with no error to explain it.\n useEffect(() => withdrawSignOutIntent, []);\n\n // Blank entry fields fall through, so clearing one in the Admin reads as unauthored.\n const entryLoadingLabel = $content?.loadingLabel?.trim() ? $content.loadingLabel : loadingLabel;\n const entryExpiredMessage = $content?.expiredMessage?.trim() ? $content.expiredMessage : expiredMessage;\n const entryIncompleteMessage = $content?.signInIncompleteMessage?.trim()\n ? $content.signInIncompleteMessage\n : signInIncompleteMessage;\n const entrySignInLabel = $content?.signInLabel?.trim() ? $content.signInLabel : signInLabel;\n\n switch (outcome) {\n case 'stand-down':\n case 'signing-in':\n return null;\n case 'loading':\n return (\n // The part carries its own hook; the component's identity travels from here, which is how a\n // store targets it by name the way every other component is targeted.\n <AccountAccessGateLoading data-fs-account-access-gate=\"\">{entryLoadingLabel}</AccountAccessGateLoading>\n );\n case 'account':\n return <>{children}</>;\n case 'expired':\n case 'sign-in-incomplete':\n return (\n <AccountAccessGateNotice\n data-fs-account-access-gate=\"\"\n reason={outcome === 'expired' ? 'expired' : 'sign-in-incomplete'}\n message={outcome === 'expired' ? entryExpiredMessage : entryIncompleteMessage}\n signInHref={resolveSignInHref(returnPath)}\n signInLabel={entrySignInLabel}\n />\n );\n default:\n return assertUnreachable(outcome);\n }\n}\n\n/**\n * The whole decision, as one ordered read of the gate's inputs.\n *\n * `signingOut` outranks everything, including a session still reading `loggedIn`: the sign-out records\n * its intent before it awaits the mutation, and the frame between the payload landing and the document\n * load starting is exactly the one this ordering protects.\n *\n * `loading` outranks the tri-state for the reason `AccountEntryPoint` gives: an unresolved session\n * reports `anonymous`, so reading the state first would bounce a shopper who is signed in. A re-read\n * in flight reads as the same wait: the session it is checking is one the gate has stopped believing.\n */\nfunction resolveOutcome({\n signingOut,\n unconfirmed,\n revalidating,\n loading,\n state,\n wasSignedIn,\n hopSpent,\n}: {\n signingOut: boolean;\n unconfirmed: boolean;\n revalidating: boolean;\n loading: boolean;\n state: SessionState;\n wasSignedIn: boolean;\n hopSpent: boolean | null;\n}): AccountAccessGateOutcome {\n if (signingOut) {\n return 'stand-down';\n }\n // A re-read that could not answer says nothing about how the shopper got here, so the notice keeps\n // the history the gate already has. Telling someone who never reached the account that their session\n // ended names an event that never happened; the incomplete sign-in is the one they actually had.\n if (unconfirmed) {\n return wasSignedIn ? 'expired' : 'sign-in-incomplete';\n }\n if (revalidating || loading) {\n return 'loading';\n }\n if (state === 'loggedIn') {\n return 'account';\n }\n if (wasSignedIn) {\n return 'expired';\n }\n return hopSpent === true ? 'sign-in-incomplete' : 'signing-in';\n}\n\nfunction assertUnreachable(outcome: never): never {\n throw new Error(`[AccountAccessGate] unhandled outcome: ${String(outcome)}`);\n}\n\n/**\n * The look of a session that has not answered yet. A real part with its own hook rather than an ad hoc\n * spinner, so a store can style it and a story can render it.\n */\nexport function AccountAccessGateLoading({ className, children, ...props }: AccountAccessGateLoadingProps) {\n return (\n <output {...props} aria-live=\"polite\" className={className} data-fs-account-access-gate-loading=\"\">\n {children}\n </output>\n );\n}\n\n/**\n * What renders in the account's place when it will not open: the message for this reason, and a link\n * the shopper may take back into sign-in.\n *\n * The link is the whole of the escape from a sign-in loop. The gate stops redirecting after one\n * automatic hop, so the next attempt is a click rather than a bounce — and a shopper who keeps landing\n * here at least lands on a page that says so.\n */\nexport function AccountAccessGateNotice({\n reason,\n message,\n signInHref,\n signInLabel,\n className,\n ...props\n}: AccountAccessGateNoticeProps) {\n return (\n <output\n {...props}\n aria-live=\"polite\"\n className={className}\n data-fs-account-access-gate-notice=\"\"\n data-fs-account-access-gate-notice-reason={reason}\n >\n {message ? <span data-fs-account-access-gate-notice-message=\"\">{message}</span> : null}\n {signInLabel?.trim() ? (\n <NavigationLink\n href={signInHref}\n // The destination is a trampoline that redirects on mount, so the default prefetch would\n // fire that GET from a page the shopper may never leave.\n prefetch={false}\n data-fs-account-access-gate-notice-action=\"\"\n >\n {signInLabel}\n </NavigationLink>\n ) : null}\n </output>\n );\n}\n\n/**\n * Session storage, guarded at every access. A browser that refuses it — a shopper blocking site data —\n * throws rather than returning null, and a gate that cannot read its own record still has a shopper to\n * get to sign-in. A refusal therefore reads as \"no record\", which spends the hop; the cost is that the\n * loop protection is absent in that browser, which is the lesser of the two failures.\n */\nfunction readSignInAttempt(): string | null {\n try {\n return globalThis.sessionStorage.getItem(SIGN_IN_ATTEMPT_KEY);\n } catch {\n return null;\n }\n}\n\nfunction recordSignInAttempt(destination: string): void {\n try {\n globalThis.sessionStorage.setItem(SIGN_IN_ATTEMPT_KEY, destination);\n } catch {\n // Nothing to fall back to: the record is the only thing that outlives the hop.\n }\n}\n\nfunction clearSignInAttempt(): void {\n try {\n globalThis.sessionStorage.removeItem(SIGN_IN_ATTEMPT_KEY);\n } catch {\n // Nothing was written either, so there is nothing to undo.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,2BAA2B,kBAAkB;CACxD,IAAI;CACJ,OAAO;CACP,aAAa;CACb,QAAQ;EACN,MAAM;EACN,sBAAsB;EACtB,YAAY;GACV,cAAc;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAuB;GAC5E,gBAAgB;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAwB;GAC/E,yBAAyB;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAmC;GACnG,aAAa;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAqB;EAC3E;CACF;AACF,CAAC;AAsCD,MAAa,8BAA8B,gBAAwC;CACjF,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,QAAQ;EAAE,OAAO;EAAuB,UAAU;CAAW;CAC7D,iBAAiB;CACjB,QAAQ;EAGN,cAAc;GAAE,MAA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WAAW,eAAe,QAAQ,qBAAqB,WAAW;CACpE,QAAQ,CAER;AACF;AAEA,SAAS,qBAA2B;CAClC,IAAI;EACF,WAAW,eAAe,WAAW,mBAAmB;CAC1D,QAAQ,CAER;AACF"}
|
|
@@ -12,7 +12,7 @@ import { usePathname } from "next/navigation";
|
|
|
12
12
|
//#region src/matter/account-entry-point/account-entry-point.tsx
|
|
13
13
|
/** The account's root. A fixed convention, never an authored value: an authored destination could
|
|
14
14
|
* misroute the entry into the account. */
|
|
15
|
-
const ACCOUNT_ROUTE = "/account";
|
|
15
|
+
const ACCOUNT_ROUTE = "/pvt/account";
|
|
16
16
|
const AccountEntryPointContent = defineContentType({
|
|
17
17
|
id: "account-entry-point",
|
|
18
18
|
title: "Account Entry Point",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account-entry-point.js","names":[],"sources":["../../../src/matter/account-entry-point/account-entry-point.tsx"],"sourcesContent":["'use client';\n\nimport { type ContentValue, defineComponent, defineContentType } from '@vtex/fs-core';\nimport { usePathname } from 'next/navigation';\nimport { type ComponentPropsWithRef, useEffect, useState } from 'react';\nimport { Icon } from '../../particles/icon/icon.js';\nimport { NavigationLink } from '../../particles/navigation-link/navigation-link.js';\nimport { resolveSignInHref } from '../../utils/safe-href.js';\nimport { useSession } from '../session/session.js';\n\n/** The account's root. A fixed convention, never an authored value: an authored destination could\n * misroute the entry into the account. */\nconst ACCOUNT_ROUTE = '/account';\n\n// Nothing is required: an entry may author any subset, and a slice missing a required property is\n// shape-invalid, which drops the whole element rather than the one field.\nexport const AccountEntryPointContent = defineContentType({\n id: 'account-entry-point',\n title: 'Account Entry Point',\n description: 'Labels and icon for the header sign-in / account control.',\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n signedOutLabel: { type: 'string', minLength: 1, title: 'Signed-out label' },\n signedInLabel: { type: 'string', minLength: 1, title: 'Signed-in label' },\n icon: { type: 'string', minLength: 1, title: 'Icon' },\n loadingLabel: { type: 'string', minLength: 1, title: 'Loading announcement' },\n },\n },\n});\n\n/** Props for {@link AccountEntryPoint}. Extends native `<a>` attributes (the rendered root). */\nexport type AccountEntryPointProps = Omit<ComponentPropsWithRef<'a'>, 'href' | 'children'> & {\n /** Label for anonymous and identified shoppers. Optional: the render gate, not the type,\n * requires a resolved value. */\n signedOutLabel?: string;\n /** Label for logged-in shoppers. Same gate. */\n signedInLabel?: string;\n /** Icon reference for the glyph. Never gated: a control with no glyph is a valid configuration. */\n icon?: string;\n /** Text the live region announces while the session resolves. */\n loadingLabel?: string;\n /** Merchant-authored fields, sliced from the page/layout content entry; win over the props field\n * by field when present. Absent in a non-CMS store — the props are the fallback. */\n $content?: ContentValue<typeof AccountEntryPointContent>;\n};\n\n/** Props for {@link AccountEntryPointLoading}. Extends native `<span>` attributes. */\nexport type AccountEntryPointLoadingProps = Omit<ComponentPropsWithRef<'span'>, 'children'>;\n\nexport const AccountEntryPointDefinition = defineComponent<AccountEntryPointProps>({\n name: 'AccountEntryPoint',\n importPath: '@vtex/faststore/components',\n component: AccountEntryPoint,\n content: AccountEntryPointContent,\n editor: { label: 'Account Entry Point', category: 'identity' },\n requiresContext: 'session',\n schema: {\n signedOutLabel: { type: 'string', label: 'Signed-out Label' },\n signedInLabel: { type: 'string', label: 'Signed-in Label' },\n icon: { type: 'icon', label: 'Icon' },\n loadingLabel: { type: 'string', label: 'Loading Announcement' },\n },\n guideline:\n 'Session-aware header control rendering one link: the signed-out label toward /login for anonymous and identified shoppers, the signed-in label toward the account route for logged-in ones, and a politely announced placeholder while the session resolves. Both destinations are fixed conventions, not props, so no authored value can misroute the auth flow. Must be inside a SessionRoot, normally the one hosted by the shared layout; a page-hosted provider also works, since the server-side session fetch forwards the shopper cookie. Author the label for a state or that state renders nothing; the labels are optional in the type only because a CMS entry may supply them, and an entry overrides all four fields at runtime. Style it through data-fs-account-entry-point and switch on data-fs-account-entry-point-state.',\n});\n\nexport function AccountEntryPoint({\n signedOutLabel,\n signedInLabel,\n icon,\n loadingLabel,\n $content,\n className,\n ref,\n ...props\n}: AccountEntryPointProps) {\n const { state, loading } = useSession();\n const pathname = usePathname();\n\n // Blank entry fields fall through, so clearing one in the Admin reads as unauthored.\n const entrySignedOutLabel = $content?.signedOutLabel?.trim() ? $content.signedOutLabel : signedOutLabel;\n const entrySignedInLabel = $content?.signedInLabel?.trim() ? $content.signedInLabel : signedInLabel;\n const entryIcon = $content?.icon?.trim() ? $content.icon : icon;\n const entryLoadingLabel = $content?.loadingLabel?.trim() ? $content.loadingLabel : loadingLabel;\n\n // Assistive technology only reports a change inside a region that was already in the tree, so a\n // region mounted together with its text announces nothing. The region therefore holds the same\n // position in both branches — React keeps it mounted across the swap — and starts empty, with the\n // label written on the pass after mount and cleared again once the session resolves.\n //\n // It trails the branch content rather than leading it so the authored swatch, which lands on\n // whichever element leads, can still reach the region through a following-sibling selector.\n const [announcement, setAnnouncement] = useState('');\n const resolvingLabel = loading ? entryLoadingLabel : undefined;\n useEffect(() => {\n setAnnouncement(resolvingLabel ?? '');\n }, [resolvingLabel]);\n\n // Gate on `loading` before `state`: an unresolved session reports `anonymous`, so reading the\n // tri-state first would flash \"Sign In\" at a shopper who is already signed in.\n if (loading) {\n return (\n <>\n <AccountEntryPointLoading {...props} className={className} />\n <AccountEntryPointAnnouncement>{announcement}</AccountEntryPointAnnouncement>\n </>\n );\n }\n\n // `identified` stays on the signed-out link: an identified but unauthenticated shopper cannot\n // reach their account yet.\n const signedIn = state === 'loggedIn';\n const label = signedIn ? entrySignedInLabel : entrySignedOutLabel;\n\n // A focusable link a screen reader announces as its bare URL is worse than no control at all.\n if (!label?.trim()) {\n return null;\n }\n\n return (\n <>\n <NavigationLink\n {...props}\n ref={ref}\n href={signedIn ? ACCOUNT_ROUTE : resolveSignInHref(pathname)}\n // The signed-out destination is a deferred auth proxy that may set a cookie or redirect, and\n // a header control is always in the viewport — the default prefetch would fire that GET on\n // every page view. The account route is an ordinary page, so it keeps the default.\n prefetch={signedIn ? undefined : false}\n className={className}\n data-fs-account-entry-point=\"\"\n data-fs-account-entry-point-state={signedIn ? 'signed-in' : 'signed-out'}\n >\n {entryIcon ? <Icon name={entryIcon} /> : null}\n <span data-fs-account-entry-point-label=\"\">{label}</span>\n </NavigationLink>\n <AccountEntryPointAnnouncement>{announcement}</AccountEntryPointAnnouncement>\n </>\n );\n}\n\n/**\n * The live region that carries the control across the wait. Separate from the visual placeholder\n * because it has to outlive it: the placeholder is only in the tree while the session resolves,\n * while the region has to be there before the text lands for the text to be announced at all.\n */\nfunction AccountEntryPointAnnouncement({ children }: { children: string }) {\n return (\n <output aria-live=\"polite\" data-fs-account-entry-point-announcement=\"\">\n {children}\n </output>\n );\n}\n\n/**\n * The visual stand-in occupying the control's slot while the session resolves. Purely visual: the\n * wait is spoken by the sibling live region, so this is hidden from assistive technology rather\n * than announced twice. Named for the state it represents, as `ShippingSimulatorLoading` is, not\n * for the bar it draws.\n */\nexport function AccountEntryPointLoading({ className, ...props }: AccountEntryPointLoadingProps) {\n return <span {...props} aria-hidden=\"true\" className={className} data-fs-account-entry-point-loading=\"\" />;\n}\n"],"mappings":";;;;;;;;;;;;;;AAYA,MAAM,gBAAgB;AAItB,MAAa,2BAA2B,kBAAkB;CACxD,IAAI;CACJ,OAAO;CACP,aAAa;CACb,QAAQ;EACN,MAAM;EACN,sBAAsB;EACtB,YAAY;GACV,gBAAgB;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAmB;GAC1E,eAAe;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAkB;GACxE,MAAM;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAO;GACpD,cAAc;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAuB;EAC9E;CACF;AACF,CAAC;AAqBD,MAAa,8BAA8B,gBAAwC;CACjF,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,QAAQ;EAAE,OAAO;EAAuB,UAAU;CAAW;CAC7D,iBAAiB;CACjB,QAAQ;EACN,g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AAY,CAAA,IAAI,MACzC,oBAAC,QAAD;GAAM,qCAAkC;GAAI,UAAA;EAAY,CAAA,CAC1C;CAChB,CAAA,GAAA,oBAAC,+BAAD,EAAA,UAAgC,aAA4C,CAAA,CAC5E,EAAA,CAAA;AAEN;;;;;;AAOA,SAAS,8BAA8B,EAAE,YAAkC;CACzE,OACE,oBAAC,UAAD;EAAQ,aAAU;EAAS,4CAAyC;EACjE;CACK,CAAA;AAEZ;;;;;;;AAQA,SAAgB,yBAAyB,EAAE,WAAW,GAAG,SAAwC;CAC/F,OAAO,oBAAC,QAAD;EAAM,GAAI;EAAO,eAAY;EAAkB;EAAW,uCAAoC;CAAI,CAAA;AAC3G"}
|
|
1
|
+
{"version":3,"file":"account-entry-point.js","names":[],"sources":["../../../src/matter/account-entry-point/account-entry-point.tsx"],"sourcesContent":["'use client';\n\nimport { type ContentValue, defineComponent, defineContentType } from '@vtex/fs-core';\nimport { usePathname } from 'next/navigation';\nimport { type ComponentPropsWithRef, useEffect, useState } from 'react';\nimport { Icon } from '../../particles/icon/icon.js';\nimport { NavigationLink } from '../../particles/navigation-link/navigation-link.js';\nimport { resolveSignInHref } from '../../utils/safe-href.js';\nimport { useSession } from '../session/session.js';\n\n/** The account's root. A fixed convention, never an authored value: an authored destination could\n * misroute the entry into the account. */\nconst ACCOUNT_ROUTE = '/pvt/account';\n\n// Nothing is required: an entry may author any subset, and a slice missing a required property is\n// shape-invalid, which drops the whole element rather than the one field.\nexport const AccountEntryPointContent = defineContentType({\n id: 'account-entry-point',\n title: 'Account Entry Point',\n description: 'Labels and icon for the header sign-in / account control.',\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n signedOutLabel: { type: 'string', minLength: 1, title: 'Signed-out label' },\n signedInLabel: { type: 'string', minLength: 1, title: 'Signed-in label' },\n icon: { type: 'string', minLength: 1, title: 'Icon' },\n loadingLabel: { type: 'string', minLength: 1, title: 'Loading announcement' },\n },\n },\n});\n\n/** Props for {@link AccountEntryPoint}. Extends native `<a>` attributes (the rendered root). */\nexport type AccountEntryPointProps = Omit<ComponentPropsWithRef<'a'>, 'href' | 'children'> & {\n /** Label for anonymous and identified shoppers. Optional: the render gate, not the type,\n * requires a resolved value. */\n signedOutLabel?: string;\n /** Label for logged-in shoppers. Same gate. */\n signedInLabel?: string;\n /** Icon reference for the glyph. Never gated: a control with no glyph is a valid configuration. */\n icon?: string;\n /** Text the live region announces while the session resolves. */\n loadingLabel?: string;\n /** Merchant-authored fields, sliced from the page/layout content entry; win over the props field\n * by field when present. Absent in a non-CMS store — the props are the fallback. */\n $content?: ContentValue<typeof AccountEntryPointContent>;\n};\n\n/** Props for {@link AccountEntryPointLoading}. Extends native `<span>` attributes. */\nexport type AccountEntryPointLoadingProps = Omit<ComponentPropsWithRef<'span'>, 'children'>;\n\nexport const AccountEntryPointDefinition = defineComponent<AccountEntryPointProps>({\n name: 'AccountEntryPoint',\n importPath: '@vtex/faststore/components',\n component: AccountEntryPoint,\n content: AccountEntryPointContent,\n editor: { label: 'Account Entry Point', category: 'identity' },\n requiresContext: 'session',\n schema: {\n signedOutLabel: { type: 'string', label: 'Signed-out Label' },\n signedInLabel: { type: 'string', label: 'Signed-in Label' },\n icon: { type: 'icon', label: 'Icon' },\n loadingLabel: { type: 'string', label: 'Loading Announcement' },\n },\n guideline:\n 'Session-aware header control rendering one link: the signed-out label toward /login for anonymous and identified shoppers, the signed-in label toward the account route for logged-in ones, and a politely announced placeholder while the session resolves. Both destinations are fixed conventions, not props, so no authored value can misroute the auth flow. Must be inside a SessionRoot, normally the one hosted by the shared layout; a page-hosted provider also works, since the server-side session fetch forwards the shopper cookie. Author the label for a state or that state renders nothing; the labels are optional in the type only because a CMS entry may supply them, and an entry overrides all four fields at runtime. Style it through data-fs-account-entry-point and switch on data-fs-account-entry-point-state.',\n});\n\nexport function AccountEntryPoint({\n signedOutLabel,\n signedInLabel,\n icon,\n loadingLabel,\n $content,\n className,\n ref,\n ...props\n}: AccountEntryPointProps) {\n const { state, loading } = useSession();\n const pathname = usePathname();\n\n // Blank entry fields fall through, so clearing one in the Admin reads as unauthored.\n const entrySignedOutLabel = $content?.signedOutLabel?.trim() ? $content.signedOutLabel : signedOutLabel;\n const entrySignedInLabel = $content?.signedInLabel?.trim() ? $content.signedInLabel : signedInLabel;\n const entryIcon = $content?.icon?.trim() ? $content.icon : icon;\n const entryLoadingLabel = $content?.loadingLabel?.trim() ? $content.loadingLabel : loadingLabel;\n\n // Assistive technology only reports a change inside a region that was already in the tree, so a\n // region mounted together with its text announces nothing. The region therefore holds the same\n // position in both branches — React keeps it mounted across the swap — and starts empty, with the\n // label written on the pass after mount and cleared again once the session resolves.\n //\n // It trails the branch content rather than leading it so the authored swatch, which lands on\n // whichever element leads, can still reach the region through a following-sibling selector.\n const [announcement, setAnnouncement] = useState('');\n const resolvingLabel = loading ? entryLoadingLabel : undefined;\n useEffect(() => {\n setAnnouncement(resolvingLabel ?? '');\n }, [resolvingLabel]);\n\n // Gate on `loading` before `state`: an unresolved session reports `anonymous`, so reading the\n // tri-state first would flash \"Sign In\" at a shopper who is already signed in.\n if (loading) {\n return (\n <>\n <AccountEntryPointLoading {...props} className={className} />\n <AccountEntryPointAnnouncement>{announcement}</AccountEntryPointAnnouncement>\n </>\n );\n }\n\n // `identified` stays on the signed-out link: an identified but unauthenticated shopper cannot\n // reach their account yet.\n const signedIn = state === 'loggedIn';\n const label = signedIn ? entrySignedInLabel : entrySignedOutLabel;\n\n // A focusable link a screen reader announces as its bare URL is worse than no control at all.\n if (!label?.trim()) {\n return null;\n }\n\n return (\n <>\n <NavigationLink\n {...props}\n ref={ref}\n href={signedIn ? ACCOUNT_ROUTE : resolveSignInHref(pathname)}\n // The signed-out destination is a deferred auth proxy that may set a cookie or redirect, and\n // a header control is always in the viewport — the default prefetch would fire that GET on\n // every page view. The account route is an ordinary page, so it keeps the default.\n prefetch={signedIn ? undefined : false}\n className={className}\n data-fs-account-entry-point=\"\"\n data-fs-account-entry-point-state={signedIn ? 'signed-in' : 'signed-out'}\n >\n {entryIcon ? <Icon name={entryIcon} /> : null}\n <span data-fs-account-entry-point-label=\"\">{label}</span>\n </NavigationLink>\n <AccountEntryPointAnnouncement>{announcement}</AccountEntryPointAnnouncement>\n </>\n );\n}\n\n/**\n * The live region that carries the control across the wait. Separate from the visual placeholder\n * because it has to outlive it: the placeholder is only in the tree while the session resolves,\n * while the region has to be there before the text lands for the text to be announced at all.\n */\nfunction AccountEntryPointAnnouncement({ children }: { children: string }) {\n return (\n <output aria-live=\"polite\" data-fs-account-entry-point-announcement=\"\">\n {children}\n </output>\n );\n}\n\n/**\n * The visual stand-in occupying the control's slot while the session resolves. Purely visual: the\n * wait is spoken by the sibling live region, so this is hidden from assistive technology rather\n * than announced twice. Named for the state it represents, as `ShippingSimulatorLoading` is, not\n * for the bar it draws.\n */\nexport function AccountEntryPointLoading({ className, ...props }: AccountEntryPointLoadingProps) {\n return <span {...props} aria-hidden=\"true\" className={className} data-fs-account-entry-point-loading=\"\" />;\n}\n"],"mappings":";;;;;;;;;;;;;;AAYA,MAAM,gBAAgB;AAItB,MAAa,2BAA2B,kBAAkB;CACxD,IAAI;CACJ,OAAO;CACP,aAAa;CACb,QAAQ;EACN,MAAM;EACN,sBAAsB;EACtB,YAAY;GACV,gBAAgB;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAmB;GAC1E,eAAe;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAkB;GACxE,MAAM;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAO;GACpD,cAAc;IAAE,MAAM;IAAU,WAAW;IAAG,OAAO;GAAuB;EAC9E;CACF;AACF,CAAC;AAqBD,MAAa,8BAA8B,gBAAwC;CACjF,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,QAAQ;EAAE,OAAO;EAAuB,UAAU;CAAW;CAC7D,iBAAiB;CACjB,QAAQ;EACN,gBAAgB;GAAE,MAAM;GAAU,OAAO;EAAmB;EAC5D,eAAe;GAAE,M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AA;EAAY,CAAA,CAC1C;CAChB,CAAA,GAAA,oBAAC,+BAAD,EAAA,UAAgC,aAA4C,CAAA,CAC5E,EAAA,CAAA;AAEN;;;;;;AAOA,SAAS,8BAA8B,EAAE,YAAkC;CACzE,OACE,oBAAC,UAAD;EAAQ,aAAU;EAAS,4CAAyC;EACjE;CACK,CAAA;AAEZ;;;;;;;AAQA,SAAgB,yBAAyB,EAAE,WAAW,GAAG,SAAwC;CAC/F,OAAO,oBAAC,QAAD;EAAM,GAAI;EAAO,eAAY;EAAkB;EAAW,uCAAoC;CAAI,CAAA;AAC3G"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ContentValue } from "../../core/dist/define-content-type.js";
|
|
2
2
|
import { ComponentDefinition } from "../../core/dist/define-component.js";
|
|
3
3
|
import "../../core/dist/index.js";
|
|
4
|
+
import { ComponentActions } from "../../sdk/actions/types.js";
|
|
4
5
|
import { ComponentPropsWithRef } from "react";
|
|
5
6
|
//#region src/matter/account-menu/account-menu.d.ts
|
|
6
7
|
export declare const AccountMenuContent: {
|
|
@@ -42,6 +43,48 @@ export declare const AccountMenuContent: {
|
|
|
42
43
|
};
|
|
43
44
|
};
|
|
44
45
|
};
|
|
46
|
+
export declare const AccountMenuIndexRedirectContent: {
|
|
47
|
+
readonly id: "account-menu-index-redirect";
|
|
48
|
+
readonly title: "Account Menu Index Redirect";
|
|
49
|
+
readonly description: "What the account's root shows while it opens the first section, and when there is none to open.";
|
|
50
|
+
readonly schema: {
|
|
51
|
+
readonly type: "object";
|
|
52
|
+
readonly additionalProperties: false;
|
|
53
|
+
readonly properties: {
|
|
54
|
+
readonly loadingLabel: {
|
|
55
|
+
readonly type: "string";
|
|
56
|
+
readonly minLength: 1;
|
|
57
|
+
readonly title: "Loading announcement";
|
|
58
|
+
};
|
|
59
|
+
readonly emptyMessage: {
|
|
60
|
+
readonly type: "string";
|
|
61
|
+
readonly minLength: 1;
|
|
62
|
+
readonly title: "No section message";
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
export declare const AccountMenuSignOutContent: {
|
|
68
|
+
readonly id: "account-menu-sign-out";
|
|
69
|
+
readonly title: "Account Menu Sign Out";
|
|
70
|
+
readonly description: "The sign-out control in the account sidebar, and what it says when signing out fails.";
|
|
71
|
+
readonly schema: {
|
|
72
|
+
readonly type: "object";
|
|
73
|
+
readonly additionalProperties: false;
|
|
74
|
+
readonly properties: {
|
|
75
|
+
readonly label: {
|
|
76
|
+
readonly type: "string";
|
|
77
|
+
readonly minLength: 1;
|
|
78
|
+
readonly title: "Sign-out label";
|
|
79
|
+
};
|
|
80
|
+
readonly errorMessage: {
|
|
81
|
+
readonly type: "string";
|
|
82
|
+
readonly minLength: 1;
|
|
83
|
+
readonly title: "Sign-out failed message";
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
};
|
|
87
|
+
};
|
|
45
88
|
type AccountMenuContentValue = ContentValue<typeof AccountMenuContent>;
|
|
46
89
|
/** One authored section. Derived from the model so the prop and content channels cannot drift. */
|
|
47
90
|
export type AccountMenuSection = NonNullable<AccountMenuContentValue['items']>[number];
|
|
@@ -74,15 +117,42 @@ export type AccountMenuListProps = Omit<ComponentPropsWithRef<'nav'>, 'children'
|
|
|
74
117
|
/** Accessible name of the navigation landmark. */
|
|
75
118
|
label?: string;
|
|
76
119
|
};
|
|
120
|
+
/** It renders the gate's loading look or a message, so it forwards no element props beyond a class. */
|
|
121
|
+
export type AccountMenuIndexRedirectProps = {
|
|
122
|
+
/** Text announced while the first section opens. */
|
|
123
|
+
loadingLabel?: string;
|
|
124
|
+
/** What the root says when the list holds no section to open. */
|
|
125
|
+
emptyMessage?: string;
|
|
126
|
+
/** Merchant-authored copy, sliced from the page content entry; wins over the props field by field. */
|
|
127
|
+
$content?: ContentValue<typeof AccountMenuIndexRedirectContent>;
|
|
128
|
+
className?: string;
|
|
129
|
+
};
|
|
130
|
+
export type AccountMenuSignOutProps = {
|
|
131
|
+
/** The control's text. */
|
|
132
|
+
label?: string;
|
|
133
|
+
/** What the shopper is told when the sign-out did not happen. */
|
|
134
|
+
errorMessage?: string;
|
|
135
|
+
/** Merchant-authored copy, sliced from the layout content entry; wins over the props field by field. */
|
|
136
|
+
$content?: ContentValue<typeof AccountMenuSignOutContent>;
|
|
137
|
+
/** Injected by the compiler from the definition's `actions`. */
|
|
138
|
+
$actions?: ComponentActions;
|
|
139
|
+
className?: string;
|
|
140
|
+
};
|
|
77
141
|
export declare const AccountMenuRootDefinition: ComponentDefinition<AccountMenuRootProps>;
|
|
78
142
|
export declare const AccountMenuListDefinition: ComponentDefinition<AccountMenuListProps>;
|
|
143
|
+
export declare const AccountMenuIndexRedirectDefinition: ComponentDefinition<AccountMenuIndexRedirectProps>;
|
|
144
|
+
export declare const AccountMenuSignOutDefinition: ComponentDefinition<AccountMenuSignOutProps>;
|
|
79
145
|
/** The resolved section list and the current section. */
|
|
80
146
|
export declare function useAccountMenu(): AccountMenuContextValue;
|
|
81
147
|
export declare function AccountMenuRoot({ items, $content, className, children, ...props }: AccountMenuRootProps): import("react/jsx-runtime").JSX.Element;
|
|
82
148
|
export declare function AccountMenuList({ label, className, ...props }: AccountMenuListProps): import("react/jsx-runtime").JSX.Element | null;
|
|
149
|
+
export declare function AccountMenuIndexRedirect({ loadingLabel, emptyMessage, $content, className }: Readonly<AccountMenuIndexRedirectProps>): import("react/jsx-runtime").JSX.Element;
|
|
150
|
+
export declare function AccountMenuSignOut({ label, errorMessage, $content, $actions: $actionsProp, className }: Readonly<AccountMenuSignOutProps>): import("react/jsx-runtime").JSX.Element;
|
|
83
151
|
export declare const AccountMenu: {
|
|
84
152
|
Root: typeof AccountMenuRoot;
|
|
85
153
|
List: typeof AccountMenuList;
|
|
154
|
+
IndexRedirect: typeof AccountMenuIndexRedirect;
|
|
155
|
+
SignOut: typeof AccountMenuSignOut;
|
|
86
156
|
};
|
|
87
157
|
//#endregion
|
|
88
158
|
//# sourceMappingURL=account-menu.d.ts.map
|
|
@@ -2,11 +2,15 @@
|
|
|
2
2
|
import { defineComponent } from "../../core/dist/define-component.js";
|
|
3
3
|
import { defineContentType } from "../../core/dist/define-content-type.js";
|
|
4
4
|
import "../../core/dist/index.js";
|
|
5
|
+
import { useActionsOverride } from "../../sdk/actions/actions-override-context.js";
|
|
5
6
|
import { resolveSafeHref, resolveSiteRelativeHref } from "../../utils/safe-href.js";
|
|
6
7
|
import { NavigationLink } from "../../particles/navigation-link/navigation-link.js";
|
|
8
|
+
import { declareSignOutIntent, useSignOutIntent, withdrawSignOutIntent } from "../account-access-gate/sign-out-intent.js";
|
|
9
|
+
import { AccountAccessGateLoading } from "../account-access-gate/account-access-gate.js";
|
|
10
|
+
import { clearSignOutFailure, reportSignOutFailure, useSignOutFailure } from "./sign-out-failure.js";
|
|
7
11
|
import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef } from "react";
|
|
8
|
-
import { jsx } from "react/jsx-runtime";
|
|
9
|
-
import { usePathname } from "next/navigation";
|
|
12
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
13
|
+
import { usePathname, useRouter } from "next/navigation";
|
|
10
14
|
//#region src/matter/account-menu/account-menu.tsx
|
|
11
15
|
const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
|
|
12
16
|
const AccountMenuContent = defineContentType({
|
|
@@ -46,6 +50,48 @@ const AccountMenuContent = defineContentType({
|
|
|
46
50
|
} }
|
|
47
51
|
}
|
|
48
52
|
});
|
|
53
|
+
const AccountMenuIndexRedirectContent = defineContentType({
|
|
54
|
+
id: "account-menu-index-redirect",
|
|
55
|
+
title: "Account Menu Index Redirect",
|
|
56
|
+
description: "What the account's root shows while it opens the first section, and when there is none to open.",
|
|
57
|
+
schema: {
|
|
58
|
+
type: "object",
|
|
59
|
+
additionalProperties: false,
|
|
60
|
+
properties: {
|
|
61
|
+
loadingLabel: {
|
|
62
|
+
type: "string",
|
|
63
|
+
minLength: 1,
|
|
64
|
+
title: "Loading announcement"
|
|
65
|
+
},
|
|
66
|
+
emptyMessage: {
|
|
67
|
+
type: "string",
|
|
68
|
+
minLength: 1,
|
|
69
|
+
title: "No section message"
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
const AccountMenuSignOutContent = defineContentType({
|
|
75
|
+
id: "account-menu-sign-out",
|
|
76
|
+
title: "Account Menu Sign Out",
|
|
77
|
+
description: "The sign-out control in the account sidebar, and what it says when signing out fails.",
|
|
78
|
+
schema: {
|
|
79
|
+
type: "object",
|
|
80
|
+
additionalProperties: false,
|
|
81
|
+
properties: {
|
|
82
|
+
label: {
|
|
83
|
+
type: "string",
|
|
84
|
+
minLength: 1,
|
|
85
|
+
title: "Sign-out label"
|
|
86
|
+
},
|
|
87
|
+
errorMessage: {
|
|
88
|
+
type: "string",
|
|
89
|
+
minLength: 1,
|
|
90
|
+
title: "Sign-out failed message"
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
});
|
|
49
95
|
const AccountMenuRootDefinition = defineComponent({
|
|
50
96
|
name: "AccountMenuRoot",
|
|
51
97
|
importPath: "@vtex/faststore/components",
|
|
@@ -78,6 +124,53 @@ const AccountMenuListDefinition = defineComponent({
|
|
|
78
124
|
} },
|
|
79
125
|
guideline: "The account menu's navigation landmark and its items, and nothing else — it surrounds the items alone so the section's own content stays outside the navigation region. Author the label: a landmark with no accessible name is one a screen-reader user cannot tell from any other. The current section carries aria-current, page for the section itself and true for a page inside it, with data-fs-account-menu-item-current beside it as a style target and never as the only signal. When the list scrolls, the current item is brought into view on mount and on every route change. Must be a descendant of AccountMenuRoot."
|
|
80
126
|
});
|
|
127
|
+
const AccountMenuIndexRedirectDefinition = defineComponent({
|
|
128
|
+
name: "AccountMenuIndexRedirect",
|
|
129
|
+
importPath: "@vtex/faststore/components",
|
|
130
|
+
component: AccountMenuIndexRedirect,
|
|
131
|
+
content: AccountMenuIndexRedirectContent,
|
|
132
|
+
requiresContext: "account-menu",
|
|
133
|
+
editor: {
|
|
134
|
+
label: "Account Menu Index Redirect",
|
|
135
|
+
category: "navigation"
|
|
136
|
+
},
|
|
137
|
+
schema: {
|
|
138
|
+
loadingLabel: {
|
|
139
|
+
type: "string",
|
|
140
|
+
label: "Loading Announcement"
|
|
141
|
+
},
|
|
142
|
+
emptyMessage: {
|
|
143
|
+
type: "string",
|
|
144
|
+
default: "No account section is configured.",
|
|
145
|
+
label: "No Section Message"
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
guideline: "The whole of the account's root page: it replaces the current history entry with the first section of the merchant's list that stays in the account, skipping one marked external, one whose destination was refused or is not site-relative, and the root itself. It shows the access gate's loading look until the section opens. A list with no such section leaves the root terminal — no navigation, and the no-section message in its place — rather than falling back to the library's defaults. Place it alone on the /pvt/account page, inside AccountMenuRoot and under AccountAccessGate, which the my-account layout provides; never on a section's own page, which it would navigate away from."
|
|
149
|
+
});
|
|
150
|
+
const AccountMenuSignOutDefinition = defineComponent({
|
|
151
|
+
name: "AccountMenuSignOut",
|
|
152
|
+
importPath: "@vtex/faststore/components",
|
|
153
|
+
component: AccountMenuSignOut,
|
|
154
|
+
content: AccountMenuSignOutContent,
|
|
155
|
+
actions: { session: ["logout"] },
|
|
156
|
+
editor: {
|
|
157
|
+
label: "Account Menu Sign Out",
|
|
158
|
+
category: "navigation"
|
|
159
|
+
},
|
|
160
|
+
schema: {
|
|
161
|
+
label: {
|
|
162
|
+
type: "string",
|
|
163
|
+
default: "Sign out",
|
|
164
|
+
label: "Label"
|
|
165
|
+
},
|
|
166
|
+
errorMessage: {
|
|
167
|
+
type: "string",
|
|
168
|
+
default: "We couldn't sign you out. Please try again.",
|
|
169
|
+
label: "Sign-out Failed Message"
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
guideline: "The account sidebar's way out: it dispatches $actions.session.logout, tells AccountAccessGate the departure is deliberate so the gate stands down instead of sending the shopper to sign in, and then loads the storefront home as a new document, which is what keeps the account out of the client router's cache. A logout that reports an error keeps the shopper on the account page with the failure message rather than landing a still-signed-in shopper on the home page. Compose it inside AccountMenuRoot beside AccountMenuList, under the gate the my-account layout provides — the back-forward cache is the gate's to revalidate, not this control's."
|
|
173
|
+
});
|
|
81
174
|
/**
|
|
82
175
|
* The library's default set, the five sections the PRD names. Labels are English as an interim, until
|
|
83
176
|
* the Localization cluster's catalog resolves them per locale. Their destinations only resolve in a
|
|
@@ -86,23 +179,23 @@ const AccountMenuListDefinition = defineComponent({
|
|
|
86
179
|
const DEFAULT_SECTIONS = [
|
|
87
180
|
{
|
|
88
181
|
label: "Profile",
|
|
89
|
-
href: "/
|
|
182
|
+
href: "/pvt/profile"
|
|
90
183
|
},
|
|
91
184
|
{
|
|
92
185
|
label: "Orders",
|
|
93
|
-
href: "/
|
|
186
|
+
href: "/pvt/orders"
|
|
94
187
|
},
|
|
95
188
|
{
|
|
96
189
|
label: "Address",
|
|
97
|
-
href: "/
|
|
190
|
+
href: "/pvt/address"
|
|
98
191
|
},
|
|
99
192
|
{
|
|
100
193
|
label: "Payments",
|
|
101
|
-
href: "/
|
|
194
|
+
href: "/pvt/payments"
|
|
102
195
|
},
|
|
103
196
|
{
|
|
104
197
|
label: "Security",
|
|
105
|
-
href: "/
|
|
198
|
+
href: "/pvt/security"
|
|
106
199
|
}
|
|
107
200
|
];
|
|
108
201
|
function resolveSections(sections) {
|
|
@@ -154,6 +247,22 @@ function findCurrent(sections, pathname) {
|
|
|
154
247
|
return current;
|
|
155
248
|
}
|
|
156
249
|
/**
|
|
250
|
+
* Where the account's root opens: the first section that stays in the account. An external entry would
|
|
251
|
+
* eject the shopper from the account they just opened, and so would an absolute one the merchant did not
|
|
252
|
+
* flag — the same site-relative reading `findCurrent` applies. The page itself is skipped too, in every
|
|
253
|
+
* spelling that matches it, since replacing it with itself would leave the loading look up for good.
|
|
254
|
+
*/
|
|
255
|
+
function findIndexDestination(sections, current) {
|
|
256
|
+
const here = current?.match === "exact" ? sections[current.index]?.href : null;
|
|
257
|
+
const herePath = here ? normalizePath(here) : null;
|
|
258
|
+
for (const section of sections) {
|
|
259
|
+
if (section.external || section.href === null || !resolveSiteRelativeHref(section.href).safe) continue;
|
|
260
|
+
if (normalizePath(section.href) === herePath) continue;
|
|
261
|
+
return section.href;
|
|
262
|
+
}
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
157
266
|
* `page` for the section itself, `true` for a page inside it. The distinction is kept rather than
|
|
158
267
|
* collapsed because the sibling breadcrumb names the deep page as the current one, and two surfaces
|
|
159
268
|
* announcing "current page" for two different things is worse than the menu claiming only its set.
|
|
@@ -236,11 +345,94 @@ function AccountMenuList({ label = "Account", className, ...props }) {
|
|
|
236
345
|
})
|
|
237
346
|
});
|
|
238
347
|
}
|
|
348
|
+
function AccountMenuIndexRedirect({ loadingLabel, emptyMessage = "No account section is configured.", $content, className }) {
|
|
349
|
+
const { items, current } = useAccountMenu();
|
|
350
|
+
const router = useRouter();
|
|
351
|
+
const replacedRef = useRef(false);
|
|
352
|
+
const destination = findIndexDestination(items, current);
|
|
353
|
+
useEffect(() => {
|
|
354
|
+
if (destination === null || replacedRef.current) return;
|
|
355
|
+
replacedRef.current = true;
|
|
356
|
+
router.replace(destination);
|
|
357
|
+
}, [destination, router]);
|
|
358
|
+
const entryLoadingLabel = $content?.loadingLabel?.trim() ? $content.loadingLabel : loadingLabel;
|
|
359
|
+
const entryEmptyMessage = $content?.emptyMessage?.trim() ? $content.emptyMessage : emptyMessage;
|
|
360
|
+
if (destination === null) return /* @__PURE__ */ jsx("p", {
|
|
361
|
+
className,
|
|
362
|
+
"data-fs-account-menu-index-redirect": "",
|
|
363
|
+
"data-fs-account-menu-index-redirect-empty": "",
|
|
364
|
+
children: entryEmptyMessage
|
|
365
|
+
});
|
|
366
|
+
return /* @__PURE__ */ jsx(AccountAccessGateLoading, {
|
|
367
|
+
className,
|
|
368
|
+
"data-fs-account-menu-index-redirect": "",
|
|
369
|
+
children: entryLoadingLabel
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
const DEFAULT_SIGN_OUT_LABEL = "Sign out";
|
|
373
|
+
const DEFAULT_SIGN_OUT_ERROR = "We couldn't sign you out. Please try again.";
|
|
374
|
+
/**
|
|
375
|
+
* The first non-blank of the given values. The models' `minLength` is enforced by neither the runtime
|
|
376
|
+
* slice nor the preflight, and a blank here is a nameless button or a silent failure.
|
|
377
|
+
*/
|
|
378
|
+
function firstAuthored(...values) {
|
|
379
|
+
return values.find((value) => value?.trim());
|
|
380
|
+
}
|
|
381
|
+
/** An absent handler or a rejection is a sign-out that did not happen, never one that did. */
|
|
382
|
+
async function logOut(logout) {
|
|
383
|
+
if (!logout) return false;
|
|
384
|
+
try {
|
|
385
|
+
return (await logout()).length === 0;
|
|
386
|
+
} catch (error) {
|
|
387
|
+
console.error("[AccountMenuSignOut] logout rejected", error);
|
|
388
|
+
return false;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
function AccountMenuSignOut({ label, errorMessage, $content, $actions: $actionsProp, className }) {
|
|
392
|
+
const $actions = useActionsOverride($actionsProp);
|
|
393
|
+
const signingOut = useSignOutIntent();
|
|
394
|
+
const failed = useSignOutFailure();
|
|
395
|
+
const attemptingRef = useRef(false);
|
|
396
|
+
async function handleClick() {
|
|
397
|
+
if (attemptingRef.current) return;
|
|
398
|
+
attemptingRef.current = true;
|
|
399
|
+
clearSignOutFailure();
|
|
400
|
+
declareSignOutIntent();
|
|
401
|
+
if (await logOut($actions?.session?.logout)) {
|
|
402
|
+
globalThis.location.assign("/");
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
attemptingRef.current = false;
|
|
406
|
+
reportSignOutFailure();
|
|
407
|
+
withdrawSignOutIntent();
|
|
408
|
+
}
|
|
409
|
+
const entryLabel = firstAuthored($content?.label, label) ?? DEFAULT_SIGN_OUT_LABEL;
|
|
410
|
+
const entryErrorMessage = firstAuthored($content?.errorMessage, errorMessage) ?? DEFAULT_SIGN_OUT_ERROR;
|
|
411
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
412
|
+
className,
|
|
413
|
+
"data-fs-account-menu-sign-out": "",
|
|
414
|
+
"data-fs-account-menu-sign-out-pending": signingOut ? "" : void 0,
|
|
415
|
+
children: [/* @__PURE__ */ jsx("button", {
|
|
416
|
+
type: "button",
|
|
417
|
+
onClick: handleClick,
|
|
418
|
+
disabled: signingOut,
|
|
419
|
+
"aria-busy": signingOut || void 0,
|
|
420
|
+
"data-fs-account-menu-sign-out-button": "",
|
|
421
|
+
children: entryLabel
|
|
422
|
+
}), failed ? /* @__PURE__ */ jsx("p", {
|
|
423
|
+
role: "alert",
|
|
424
|
+
"data-fs-account-menu-sign-out-error": "",
|
|
425
|
+
children: entryErrorMessage
|
|
426
|
+
}) : null]
|
|
427
|
+
});
|
|
428
|
+
}
|
|
239
429
|
const AccountMenu = {
|
|
240
430
|
Root: AccountMenuRoot,
|
|
241
|
-
List: AccountMenuList
|
|
431
|
+
List: AccountMenuList,
|
|
432
|
+
IndexRedirect: AccountMenuIndexRedirect,
|
|
433
|
+
SignOut: AccountMenuSignOut
|
|
242
434
|
};
|
|
243
435
|
//#endregion
|
|
244
|
-
export { AccountMenu, AccountMenuContent, AccountMenuList, AccountMenuListDefinition, AccountMenuRoot, AccountMenuRootDefinition, useAccountMenu };
|
|
436
|
+
export { AccountMenu, AccountMenuContent, AccountMenuIndexRedirect, AccountMenuIndexRedirectContent, AccountMenuIndexRedirectDefinition, AccountMenuList, AccountMenuListDefinition, AccountMenuRoot, AccountMenuRootDefinition, AccountMenuSignOut, AccountMenuSignOutContent, AccountMenuSignOutDefinition, useAccountMenu };
|
|
245
437
|
|
|
246
438
|
//# sourceMappingURL=account-menu.js.map
|