Files
supabase/apps/ui-library/components/command-menu.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

136 lines
5.0 KiB
TypeScript

'use client'
import { LaptopIcon, MoonIcon, SunIcon } from 'lucide-react'
import { useTheme } from 'next-themes'
import { useRouter } from 'next/navigation'
import * as React from 'react'
import {
Button,
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
DialogDescription,
DialogProps,
DialogTitle,
} from 'ui'
import { gettingStarted } from '@/config/docs'
import { getLibraryBlockHref, libraryBlocks, libraryCategories } from '@/config/library'
import { useFrameworkPreference } from '@/context/framework-preference-context'
import { cn } from '@/lib/utils'
export function CommandMenu({ ...props }: DialogProps) {
const router = useRouter()
const { framework } = useFrameworkPreference()
const [open, setOpen] = React.useState(false)
const { setTheme } = useTheme()
React.useEffect(() => {
const down = (e: KeyboardEvent) => {
if ((e.key === 'k' && (e.metaKey || e.ctrlKey)) || e.key === '/') {
if (
(e.target instanceof HTMLElement && e.target.isContentEditable) ||
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement ||
e.target instanceof HTMLSelectElement
) {
return
}
e.preventDefault()
setOpen((open) => !open)
}
}
document.addEventListener('keydown', down)
return () => document.removeEventListener('keydown', down)
}, [])
const runCommand = React.useCallback((command: () => unknown) => {
setOpen(false)
command()
}, [])
return (
<>
<Button
variant="outline"
className={cn(
`@container relative h-8 w-full justify-start rounded-[0.5rem] bg-background text-sm font-normal text-foreground-muted shadow-none sm:pr-12 md:pr-2.5 lg:pr-12
hover:border-foreground-muted hover:bg-surface-100 hover:text-foreground-lighter
`
)}
onClick={() => setOpen(true)}
{...props}
>
<span className="hidden @min-[7.5rem]:inline-flex">Search library...</span>
<span className="inline-flex @min-[7.5rem]:hidden">Search...</span>
<kbd className="pointer-events-none absolute right-[0.3rem] top-[0.3rem] hidden h-5 select-none items-center gap-1 rounded-sm border bg-surface-200 px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex md:hidden lg:flex text-foreground-light">
<span className="text-sm">⌘</span>K
</kbd>
</Button>
<CommandDialog open={open} onOpenChange={setOpen}>
<DialogTitle className="sr-only">Search the library</DialogTitle>
<DialogDescription className="sr-only">
Find guides, blocks, starter apps, and theme settings.
</DialogDescription>
<CommandInput placeholder="Type a command or search..." />
<CommandList className="min-h-0 max-h-[min(400px,calc(100dvh-8rem))] overscroll-contain [&_[cmdk-group]]:p-2! [&_[cmdk-item]]:rounded-md [&_[cmdk-item]]:p-2!">
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup key="pages" heading="Pages">
{gettingStarted.items.map((navItem) => (
<CommandItem
key={navItem.href}
value={navItem.title}
onSelect={() => runCommand(() => router.push(navItem.href as string))}
>
{navItem.title}
</CommandItem>
))}
</CommandGroup>
{libraryCategories.map((category) => (
<CommandGroup key={category.slug} heading={category.name}>
{libraryBlocks
.filter((block) => block.category === category.name)
.map((block) => (
<CommandItem
key={block.slug}
value={`${block.title} ${block.category} ${block.tags.join(' ')}`}
onSelect={() =>
runCommand(() => {
const href = getLibraryBlockHref(block, framework)
if (block.external) window.location.assign(href)
else router.push(href)
})
}
>
{block.title}
</CommandItem>
))}
</CommandGroup>
))}
<CommandSeparator />
<CommandGroup heading="Theme">
<CommandItem onSelect={() => runCommand(() => setTheme('light'))}>
<SunIcon className="mr-2 h-4 w-4" strokeWidth={1} />
Light
</CommandItem>
<CommandItem onSelect={() => runCommand(() => setTheme('dark'))}>
<MoonIcon className="mr-2 h-4 w-4" strokeWidth={1} />
Dark
</CommandItem>
<CommandItem onSelect={() => runCommand(() => setTheme('system'))}>
<LaptopIcon className="mr-2 h-4 w-4" strokeWidth={1} />
System
</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
</>
)
}