Files
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

193 lines
5.1 KiB
TypeScript

'use client'
import {
createContext,
forwardRef,
useContext,
useMemo,
type ComponentPropsWithoutRef,
type ComponentType,
type CSSProperties,
type ForwardedRef,
type ReactNode,
type RefAttributes,
} from 'react'
export interface StaticImageData {
src: string
height: number
width: number
blurDataURL?: string
blurWidth?: number
blurHeight?: number
}
export interface StaticRequire {
default: StaticImageData
}
export type StaticImport = StaticRequire | StaticImageData
export interface FrameworkLinkProps extends Omit<ComponentPropsWithoutRef<'a'>, 'href'> {
href: string
prefetch?: boolean | null | 'auto'
replace?: boolean
scroll?: boolean
shallow?: boolean
}
export type FrameworkLinkComponent = ComponentType<
FrameworkLinkProps & RefAttributes<HTMLAnchorElement>
>
export interface FrameworkImageProps extends Omit<
ComponentPropsWithoutRef<'img'>,
'src' | 'srcSet' | 'ref' | 'alt' | 'width' | 'height' | 'loading'
> {
src: string | StaticImport
alt: string
width?: number | `${number}`
height?: number | `${number}`
fill?: boolean
sizes?: string
priority?: boolean
preload?: boolean
loading?: 'lazy' | 'eager'
quality?: number | `${number}`
placeholder?: 'blur' | 'empty' | `data:image/${string}`
blurDataURL?: string
unoptimized?: boolean
overrideSrc?: string
}
export type FrameworkImageComponent = ComponentType<FrameworkImageProps>
export interface FrameworkContextValue {
/** Framework Link component (e.g. next/link or TanStack Link). Defaults to `<a>`. */
Link?: FrameworkLinkComponent
/** Framework Image component (e.g. next/image). Defaults to `<img>`. */
Image?: FrameworkImageComponent
/** Current route pattern or pathname (e.g. `/project/[ref]` or `/guides/auth`). */
pathname?: string
/**
* Current resolved path without basePath. Includes search and hash where the adapter can supply
* them; Next App Router adapters supply the pathname only, since reading search params at the
* root would opt static pages out of static rendering.
*/
asPath?: string
/** Whether dynamic route params are hydrated (Next Pages Router `router.isReady`). Defaults to `true`. */
isReady?: boolean
/** Current route and search params consumed by `useParams()`. */
params?: Record<string, string | string[] | undefined>
/** Programmatic client-side navigation. Falls back to `window.location.assign`. */
push?: (path: string) => void | Promise<unknown>
}
function defaultPush(path: string) {
if (typeof window !== 'undefined') {
window.location.assign(path)
}
}
const FrameworkContext = createContext<FrameworkContextValue | null>(null)
export function useFramework(): FrameworkContextValue &
Required<Pick<FrameworkContextValue, 'push'>> {
const context = useContext(FrameworkContext)
return useMemo(() => ({ ...context, push: context?.push ?? defaultPush }), [context])
}
/** Whether a `FrameworkProvider` is mounted above. `useFramework()` falls back to defaults without one. */
export function useHasFrameworkProvider(): boolean {
return useContext(FrameworkContext) !== null
}
export function FrameworkProvider({
value,
children,
}: {
value: FrameworkContextValue
children: ReactNode
}) {
return <FrameworkContext.Provider value={value}>{children}</FrameworkContext.Provider>
}
export const DefaultFrameworkLink = forwardRef(function DefaultFrameworkLink(
{
href,
prefetch: _prefetch,
replace: _replace,
scroll: _scroll,
shallow: _shallow,
children,
...rest
}: FrameworkLinkProps,
ref: ForwardedRef<HTMLAnchorElement>
) {
return (
<a ref={ref} href={href} {...rest}>
{children}
</a>
)
})
export const FrameworkLink = forwardRef(function FrameworkLink(
props: FrameworkLinkProps,
ref: ForwardedRef<HTMLAnchorElement>
) {
const { Link } = useFramework()
const LinkComponent = Link ?? DefaultFrameworkLink
return <LinkComponent ref={ref} {...props} />
})
export function resolveStaticImageSrc(src: string | StaticImport): string {
if (typeof src === 'string') return src
if ('default' in src) return src.default.src
return src.src
}
export function DefaultFrameworkImage({
src,
alt,
width,
height,
fill,
sizes,
priority,
preload: _preload,
loading,
quality: _quality,
placeholder: _placeholder,
blurDataURL: _blurDataURL,
unoptimized: _unoptimized,
overrideSrc: _overrideSrc,
style,
fetchPriority,
...rest
}: FrameworkImageProps) {
const resolvedSrc = resolveStaticImageSrc(src)
const finalStyle: CSSProperties | undefined = fill
? { position: 'absolute', inset: 0, width: '100%', height: '100%', ...style }
: style
return (
<img
{...rest}
src={resolvedSrc}
alt={alt}
width={fill ? undefined : width}
height={fill ? undefined : height}
sizes={sizes}
loading={loading ?? (priority ? 'eager' : 'lazy')}
fetchPriority={priority ? 'high' : fetchPriority}
style={finalStyle}
/>
)
}
export function FrameworkImage(props: FrameworkImageProps) {
const { Image } = useFramework()
const ImageComponent = Image ?? DefaultFrameworkImage
return <ImageComponent {...props} />
}