An open source design system that's fully customizable and agent ready
TypeScript
docs(useLinkComponent): add hook docs and an article card example block (#9901)
Parman Mohammadalizadeh7b831ae03d6c
diff --git a/.changeset/hook-doc-use-link-component.md b/.changeset/hook-doc-use-link-component.mdnew file mode 100644index 0000000000..1ee780aa19--- /dev/null+++ b/.changeset/hook-doc-use-link-component.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[docs] Hook docs for `useLinkComponent`, so `astryx hook useLinkComponent` and `astryx search` return it, and a `useLinkComponent — Article Cards` example block: custom Article cards render their title link with the component the hook resolves. Inside a LinkProvider wired to a client-side router the title navigates without a page load, `as="a"` gives a native anchor even inside the provider, and outside the provider the title falls back to the next provider up or a native anchor. Copy it with `astryx template useLinkComponentHookUsage <path>`.++@MannXodiff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex 4d99e7f0f5..d8a339bd7c 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -801,6 +801,7 @@"/templates/useImageModeHookUsage/","/templates/useInputStatusIconHookUsage/","/templates/useKeyboardHintHookUsage/",+ "/templates/useLinkComponentHookUsage/","/templates/useListFocusHookUsage/","/templates/useLocaleHookUsage/","/templates/useOutlineFromMarkdownHookUsage/",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 4f883ab381..ec7f3c10e2 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3751,6 +3751,11 @@"path": "examples/use-lightbox/gallery-grid","aliases": []},+ {+ "name": "example-use-link-component-article-cards",+ "path": "examples/use-link-component/article-cards",+ "aliases": []+ },{"name": "example-use-list-focus-recent-files","path": "examples/use-list-focus/recent-files",@@ -4031,6 +4036,11 @@"path": "hooks/use-lightbox","aliases": []},+ {+ "name": "hook-use-link-component",+ "path": "hooks/use-link-component",+ "aliases": []+ },{"name": "hook-use-list-focus","path": "hooks/use-list-focus",diff --git a/packages/cli/api/component/__fixtures__/resolutions/modules.txt b/packages/cli/api/component/__fixtures__/resolutions/modules.txtindex 80d6e95e87..f17d47be2a 100644--- a/packages/cli/api/component/__fixtures__/resolutions/modules.txt+++ b/packages/cli/api/component/__fixtures__/resolutions/modules.txt@@ -271,7 +271,7 @@ useIsHydrating useIsHydrating hooks/useAnimatedLayout.doc.mjs hooks/useIsHydratiuseIsomorphicLayoutEffect useIsomorphicLayoutEffect hooks/useAnimatedLayout.doc.mjs hooks/useIsomorphicLayoutEffect.tsuseLayerDismissal useLayerDismissal Layer/Layer.doc.mjs Layer/useLayerDismissal.tsuseLightbox useLightbox Lightbox/useLightbox.doc.mjs Lightbox/useLightbox.tsx-useLinkComponent useLinkComponent Link/Link.doc.mjs Link/useLinkComponent.ts+useLinkComponent useLinkComponent Link/useLinkComponent.doc.mjs Link/useLinkComponent.tsuseLinkify useLinkify Link/Link.doc.mjs Link/useLinkify.tsxuseListFormatter useListFormatter i18n/InternationalizationProvider.doc.mjs i18n/useListFormatter.tsuseMenuDrillIn useMenuDrillIn DropdownMenu/DropdownMenu.doc.mjs DropdownMenu/useMenuDrillIn.tsxdiff --git a/packages/cli/api/template/use-link-component-hook-usage.test.tsx b/packages/cli/api/template/use-link-component-hook-usage.test.tsxnew file mode 100644index 0000000000..a3cf16430f--- /dev/null+++ b/packages/cli/api/template/use-link-component-hook-usage.test.tsx@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @vitest-environment jsdom++/**+ * The useLinkComponent example's Article cards render their title link with+ * the component the hook resolves: the example's router link inside its+ * LinkProvider, a native anchor for as="a", and a native anchor outside any+ * provider.+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import UseLinkComponentHookUsage from '../../assets/templates/blocks/components/Link/useLinkComponentHookUsage';++(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =+ true;++let root: Root | null = null;+let container: HTMLElement;++function link(title: string): HTMLAnchorElement {+ const anchor = Array.from(container.querySelectorAll('a')).find(+ candidate => candidate.textContent === title,+ );+ if (anchor == null) {+ throw new Error(`no link titled "${title}"`);+ }+ return anchor;+}++function location(): string {+ return (+ Array.from(container.querySelectorAll('span'))+ .find(span => span.textContent?.startsWith('Router location: '))+ ?.textContent?.slice('Router location: '.length) ?? ''+ );+}++/** Clicks the link and reports whether the browser would follow it. */+function click(anchor: HTMLAnchorElement): boolean {+ const event = new MouseEvent('click', {bubbles: true, cancelable: true});+ act(() => {+ anchor.dispatchEvent(event);+ });+ return !event.defaultPrevented;+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ act(() => {+ root = createRoot(container);+ root.render(<UseLinkComponentHookUsage />);+ });+});++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ container.remove();+});++describe('useLinkComponent example', () => {+ it("renders the provider's router link, which navigates without a page load", () => {+ expect(location()).toBe('/');+ const anchor = link('Getting started');+ expect(anchor.getAttribute('href')).toBe('/articles/getting-started');+ expect(click(anchor)).toBe(false);+ expect(location()).toBe('/articles/getting-started');+ });++ it('renders a native anchor for as="a", even inside the provider', () => {+ const anchor = link('Style guide (PDF)');+ expect(anchor.getAttribute('href')).toBe('#style-guide');+ expect(click(anchor)).toBe(true);+ expect(location()).toBe('/');+ });++ it('falls back to a native anchor outside the provider', () => {+ const anchor = link('Release notes');+ expect(anchor.getAttribute('href')).toBe('#release-notes');+ expect(click(anchor)).toBe(true);+ expect(location()).toBe('/');+ });+});diff --git a/packages/cli/assets/templates/blocks/components/Link/useLinkComponentHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Link/useLinkComponentHookUsage.doc.mjsnew file mode 100644index 0000000000..9e5fb573f9--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Link/useLinkComponentHookUsage.doc.mjs@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'useLinkComponent',+ name: 'useLinkComponent — Article Cards',+ displayName: 'useLinkComponent — Article Cards',+ description:+ 'A custom Article card renders its title link with the component useLinkComponent resolves: the as prop first, then the nearest LinkProvider, then a native anchor. Inside a LinkProvider wired to a client-side router, the title navigates without a page load and updates the router location. With as="a" the title is a native anchor even inside the provider, and outside the provider it falls back to the next provider up or a native anchor.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['LinkProvider', 'Card', 'Layout', 'Text'],+};diff --git a/packages/cli/assets/templates/blocks/components/Link/useLinkComponentHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Link/useLinkComponentHookUsage.tsxnew file mode 100644index 0000000000..b909cd74c0--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Link/useLinkComponentHookUsage.tsx@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {createContext, use, useState, type AnchorHTMLAttributes} from 'react';+import {Card} from '@astryxdesign/core/Card';+import {VStack} from '@astryxdesign/core/Layout';+import {+ LinkProvider,+ useLinkComponent,+ type LinkComponentType,+} from '@astryxdesign/core/Link';+import {Text} from '@astryxdesign/core/Text';++const NavigateContext = createContext<(to: string) => void>(() => {});++function RouterLink({+ to,+ href: _href,+ ...props+}: AnchorHTMLAttributes<HTMLAnchorElement> & {to: string}) {+ const navigate = use(NavigateContext);+ return (+ <a+ {...props}+ href={to}+ onClick={event => {+ event.preventDefault();+ navigate(to);+ }}+ />+ );+}++function ArticleCard({+ title,+ href,+ resolvedBy,+ linkAs,+}: {+ title: string;+ href: string;+ resolvedBy: string;+ linkAs?: LinkComponentType;+}) {+ const LinkComponent = useLinkComponent(linkAs);+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <Text type="body" weight="bold">+ <LinkComponent href={href}>{title}</LinkComponent>+ </Text>+ <Text type="supporting" color="secondary">+ {resolvedBy}+ </Text>+ </VStack>+ </Card>+ );+}++export default function UseLinkComponentHookUsage() {+ const [route, setRoute] = useState('/');++ return (+ <VStack gap={3}>+ <Text type="body">Router location: {route}</Text>+ <NavigateContext value={setRoute}>+ <LinkProvider component={RouterLink}>+ <ArticleCard+ title="Getting started"+ href="/articles/getting-started"+ resolvedBy="LinkProvider: the router's link, no page load"+ />+ <ArticleCard+ title="Style guide (PDF)"+ href="#style-guide"+ resolvedBy='as="a": a native anchor, even inside the provider'+ linkAs="a"+ />+ </LinkProvider>+ </NavigateContext>+ <ArticleCard+ title="Release notes"+ href="#release-notes"+ resolvedBy="Outside the provider: the app's LinkProvider, or a native anchor"+ />+ </VStack>+ );+}diff --git a/packages/core/src/Link/useLinkComponent.doc.mjs b/packages/core/src/Link/useLinkComponent.doc.mjsnew file mode 100644index 0000000000..82ecad30ac--- /dev/null+++ b/packages/core/src/Link/useLinkComponent.doc.mjs@@ -0,0 +1,95 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').HookDoc} */+export const docs = {+ name: 'useLinkComponent',+ displayName: 'useLinkComponent',+ group: 'Link',+ keywords: [+ 'link',+ 'router',+ 'client-side routing',+ 'LinkProvider',+ 'as',+ 'polymorphic',+ 'anchor',+ 'nextjs',+ 'href',+ ],+ params: [+ {+ name: 'as',+ type: 'LinkComponentType',+ description:+ "Component to render the link with, such as a router's link or 'a'. When set it wins over any LinkProvider.",+ required: false,+ },+ ],+ returns: [+ {+ name: 'LinkComponent',+ type: 'LinkComponentType',+ description:+ "The resolved component: as, else the nearest LinkProvider's component, else a native 'a'. It is stable while the resolved component is the same. It checks href and to under the Link href rule before rendering; when either is rejected it renders an anchor with no destination and never invokes the router. A custom component receives to={href} unless an explicit to is passed.",+ },+ ],+ usage: {+ description:+ "Resolves which component renders a link, so a custom component's links follow the app's router the same way Astryx's own links do. The order is the as argument, then the nearest LinkProvider's component, then a native anchor. Render the returned component with href (and to, for a router that reads it). Before rendering it checks both destinations under the Link href rule: a rejected destination renders an anchor with no destination, and a custom router is never invoked with it. A custom component receives to={href} unless to is passed explicitly.",+ bestPractices: [+ {+ guidance: true,+ description:+ 'Use it for links inside a custom component, so a LinkProvider wired to the router reaches them without a prop on every link.',+ },+ {+ guidance: true,+ description:+ "Pass as='a' for a destination the router cannot handle, such as a file download or a page outside the app.",+ },+ {+ guidance: false,+ description:+ "Import the router's link directly in a shared component; the component then ignores LinkProvider and the destination check.",+ },+ ],+ },+ relatedComponents: ['Link', 'LinkProvider'],+ relatedHooks: ['useLinkify'],+ importPath: '@astryxdesign/core/Link',+ category: 'utilities',+};++/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */+export const docsDense = {+ description:+ "Resolves which component renders a link: as arg, else nearest LinkProvider's component, else native anchor. Custom components' links follow the app router like Astryx links. Checks href/to under the Link href rule: rejected => anchor with no destination, router never invoked. Custom components get to={href} unless to given.",+ paramDescriptions: {+ as: "component to render the link with (router link or 'a'); wins over LinkProvider.",+ },+ returnDescriptions: {+ LinkComponent:+ "resolved component (as, else LinkProvider, else 'a'); stable per resolved component. Checks href/to first; rejected => anchor w/o destination, no router call. Custom components get to={href} unless to given.",+ },+ usage: {+ description:+ 'Resolves the link component: as, else nearest LinkProvider, else native anchor. Render it with href (and to). Rejected destinations render an anchor w/o destination, never invoking the router. Custom components get to={href} unless to given.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Use for links inside custom components so a router LinkProvider reaches them.',+ },+ {+ guidance: true,+ description:+ "Pass as='a' for destinations the router cannot handle (downloads, pages outside the app).",+ },+ {+ guidance: false,+ description:+ 'Import the router link directly in shared components; that skips LinkProvider and the destination check.',+ },+ ],+ },+};