Files
supabase/apps/ui-library/components/side-navigation-item.tsx
Alaister YoungandAlaister Young d6e4089b1a feat(common): add FrameworkProvider and remove next imports (#53905)
Introduces a lightweight `FrameworkProvider` React context in
`packages/common` (`Link`, `Image`, `pathname`, `asPath`, `isReady`,
`params`, `push`), wires it up in the consuming apps, and removes the
`next` dependency from `packages/common`.

**Added:**

- `FrameworkProvider`, `useFramework`, `FrameworkLink`, and
`FrameworkImage` in `packages/common/framework.tsx`, with plain HTML
defaults (`DefaultFrameworkLink` / `DefaultFrameworkImage`).
`useFramework().push` always exists and falls back to
`window.location.assign`
- App-level framework providers wiring `next/link`, `next/image`, and
router state in `www` (App + Pages routers), `docs`, `design-system`,
`learn`, and `ui-library`, and native TanStack Router bindings in
`studio` (`StudioFrameworkProvider`)
- `StudioFrameworkProvider` reuses the common defaults (its image only
applies the basePath) and reports `isReady` once the first route load
commits, so the first page view carries the final route after any
redirect
- Unit tests for `StudioFrameworkProvider` (`useParams`,
`FrameworkLink`, `FrameworkImage`, query/hash-only navigation,
`isReady`) and for `PageTelemetry` route-change sends and the
`TelemetryTagManager` consent gate

**Changed:**

- `common/hooks/useParams.ts`: read params from `useFramework()` instead
of `next/compat/router`
- `common/telemetry.tsx`: replace `next/script` in `TelemetryTagManager`
with `useEffect` script injection, and read route state from
`useFramework()` in `PageTelemetry`
- `common/MetaFavicons/app-router.ts`: drop type-only `Metadata` import
from `next`
- Moved `MetaFaviconsPagesRouter` to
`apps/www/components/MetaFaviconsPagesRouter.tsx` (its sole consumer)
- Studio: `toRoutePattern` and `applyBasePath` now live once in
`lib/internal-url.ts`, shared by the provider and the `compat/next`
shims
- `PageTelemetry` throws outside production when no `FrameworkProvider`
is mounted, since it would otherwise send only the landing pageview.
`useFramework()` itself still falls back to the defaults
- `ui-library`: renamed its code-sample framework context to
`FrameworkPreferenceProvider` / `useFrameworkPreference` so
`FrameworkProvider` only means the `common` one

**Removed:**

- `learn`'s unused copy of that context (`useCourse` had no callers)

- `next` from `packages/common/package.json` peerDependencies

App Router adapters set `asPath` to the pathname only, same as the
`usePathname`-based telemetry on master (reading search params at the
root would opt static pages out of static rendering).

## To test

- Run `packages/common` tests and typecheck, and `apps/studio`
`StudioFrameworkProvider` / `route-render` / `telemetry` tests
- Navigate between routes in Studio, Docs, and WWW and confirm page
telemetry fires once per navigation (and does not duplicate on hash-only
changes)
- Load Studio at `/` (which redirects) and confirm the first page event
has the final route
- Verify URL params (`useParams`) continue resolving route and search
params in Studio

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-25 20:13:22 +08:00

112 lines
3.6 KiB
TypeScript

'use client'
import Link, { LinkProps } from 'next/link'
import { usePathname } from 'next/navigation'
import React from 'react'
import { Badge, cn } from 'ui'
import { useFrameworkPreference } from '@/context/framework-preference-context'
import { useMobileMenu } from '@/hooks/use-mobile-menu'
import { SidebarNavItem } from '@/types/nav'
// We extend:
// 1. LinkProps - for Next.js Link component props (prefetch, etc)
// 2. AnchorHTMLAttributes - for standard HTML anchor props (className, etc)
// We omit href from both since we compute it internally from item.href
interface NavigationItemProps
extends Omit<LinkProps, 'href'>, Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
item: SidebarNavItem
onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void
}
export const NavigationItem: React.FC<NavigationItemProps> = ({ item, onClick, ...props }) => {
const { setOpen } = useMobileMenu()
const { framework } = useFrameworkPreference()
const pathname = usePathname()
const pathParts = pathname.split('/')
const slug = pathParts[pathParts.length - 1]
// Helper function to check if a framework is supported for a navigation item
const isFrameworkSupported = (item: SidebarNavItem, framework: string) => {
const supportedFrameworks = item.supportedFrameworks || []
const hasFrameworkRestrictions = supportedFrameworks.length > 0
// An item supports the current framework if either:
// 1. It has no framework restrictions (supports all frameworks)
// 2. The current framework is in its list of supported frameworks
return (
!hasFrameworkRestrictions || supportedFrameworks.some((supported) => supported === framework)
)
}
// Build URL with priority:
// 1. item.href if available (replacing any existing framework with current one)
// 2. Computed from current path considering framework support
let href = item.href
// Only modify URLs for items that explicitly support frameworks
if (item.supportedFrameworks) {
if (href && href.startsWith('/docs/')) {
const hrefParts = href.split('/')
if (hrefParts.length >= 3) {
if (framework && isFrameworkSupported(item, framework)) {
if (hrefParts.length >= 4) {
href = `/docs/${framework}/${hrefParts[3]}`
}
}
}
}
}
// Handle component items with slug but no href
else if (!href && slug) {
// Build the URL using the current framework if it's supported
if (framework && isFrameworkSupported(item, framework)) {
href = `/docs/${framework}/${slug}`
} else {
// Fall back to framework-agnostic URL when framework not supported
href = `/docs/${slug}`
}
}
// Determine if this link represents the current page
const isActive = pathname === href
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
// Close the mobile menu when navigating
setOpen(false)
// Call the onClick prop if it exists
if (onClick) {
onClick(e)
}
}
return (
<Link
href={href || '#'}
{...props}
onClick={handleClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'relative',
'flex',
'items-center justify-between',
'min-h-8 rounded-md py-1.5',
'text-sm',
'px-3',
'transition-all',
isActive
? 'bg-selection text-foreground'
: 'text-foreground-light hover:bg-surface-200 hover:text-foreground',
props.className
)}
>
{item.title}
{item.new && <Badge variant="success">New</Badge>}
</Link>
)
}
NavigationItem.displayName = 'NavigationItem'