Files
supabase/apps/ui-library/components/block-item-code.tsx
Alaister YoungandAlaister Young fcbdda8107 chore: migrate formatter from Prettier to oxfmt (#53835)
Migrate code formatting across the monorepo from Prettier to `oxfmt`
(`0.79.0`, pinned) for much faster formatting checks locally and in CI
while keeping code churn minimal (78 files total, 0.7% of the repo).

Studio's `@ianvs/prettier-plugin-sort-imports` ordering
(`<BUILTIN_MODULES>`, `<THIRD_PARTY_MODULES>`, blank line, then `@/` and
relative imports) is preserved via `oxfmt`'s native `sortImports`
override for `apps/studio/**/*.{js,jsx,ts,tsx}`.

### Performance (before vs after, uncached)

| Benchmark | Prettier (`3.8.x`) | oxfmt (`0.79.0`) | Speedup |
| --- | ---: | ---: | ---: |
| CI formatting step (`blacksmith-4vcpu-ubuntu-2404`, full repo) | `73s`
| **`7s`** | **~10×** |
| Local `apps/studio` JS/TS (`5,157` files) | `17.74s` | **`0.36s`** |
**~49×** |
| Local full monorepo (`11,131` files) | — | **`2.39s`** | — |

**Added:**

- `.oxfmtrc.jsonc` at repo root with Prettier-matching options,
`sortPackageJson: false`, the Studio `sortImports` override, and ignore
patterns migrated from `.prettierignore`
- `oxfmt` (`0.79.0` exact pin) in `pnpm-workspace.yaml` catalog and
workspace `devDependencies` / `dependencies`
- Shared `.agents/scripts/format_and_lint.sh` hook script and
`.agents/hooks.json` (used by both Claude Code and Antigravity)

**Changed:**

- Replaced `test:prettier` with `format:check` and switched `format` in
root `package.json` to `oxfmt`
- Updated `packages/api-types` (`codegen`,
`verify-production-types.mjs`), `apps/design-system` (`build:registry`),
`apps/docs` (`CodeSample.ts`, `generate-sitemap.ts`, `next.config.mjs`,
`spec/Makefile`), `apps/www` (`generate-sitemap.mjs`), and
`packages/build-icons` (`generateIconFiles.mjs`) from Prettier to
`oxfmt`
- Updated `.github/workflows/prettier.yml` (keeping the `format` job ID
intact), `.github/workflows/autofix_linters.yml`,
`.claude/settings.json`, `AGENTS.md`, `CONTRIBUTING.md`, and
`.github/copilot-instructions.md`
- Applied one-time `oxfmt` formatting pass in a separate commit (78
files: 30 `i18n/README.*.md` trailing spaces, 19 Studio files, 17 other
TS/TSX/generated types, 8 MD/MDX, 3 `package.json`, 2 example CSS files)

**Removed:**

- `prettier`, `@ianvs/prettier-plugin-sort-imports`, and
`prettier-plugin-sql-cst` from `devDependencies` (note: `.sql` files
were not part of the CI formatting glob; `eslint-config-prettier` is
kept for ESLint)
- `prettier.config.mjs`, `.prettierignore`, and
`.claude/scripts/format_and_lint.sh`

## To test

- Run `pnpm run format:check` and confirm it passes cleanly across all
matched files
- Run `pnpm --filter api-types test`, `pnpm --filter docs exec vitest
run features/directives/CodeSample.test.ts`, and `pnpm --filter www exec
vitest run generate-sitemap.test.ts`
- Edit an `apps/studio` file with out-of-order imports and run `pnpm run
format` to confirm builtin/third-party vs `@/`/relative grouping matches
prior behavior
- Check that the `Check Code Formatting` CI workflow passes on this PR

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-24 12:51:31 +08:00

168 lines
5.0 KiB
TypeScript

'use client'
import { File } from 'lucide-react'
import dynamic from 'next/dynamic'
import { createContext, useContext, useState } from 'react'
import { cn, flattenTree, TreeView, TreeViewItem } from 'ui'
import type { CodeBlockLang } from 'ui-patterns/CodeBlock'
import { RegistryNode } from '@/lib/process-registry'
// next/dynamic passes no props to `loading`, so the fallback reads the code from context.
const PendingCodeContext = createContext('')
function PendingCode() {
const code = useContext(PendingCodeContext)
return (
<pre className="w-full min-h-0 min-w-0 flex-1 overflow-auto p-4 font-mono text-xs">{code}</pre>
)
}
const CodeBlock = dynamic(
() => import('ui-patterns/CodeBlock').then((module) => module.CodeBlock),
{ ssr: false, loading: () => <PendingCode /> }
)
interface BlockItemCodeProps {
files: RegistryNode[]
embedded?: boolean
}
interface TreeNode {
name: string
children: TreeNode[]
metadata: { path: string }
}
const flattenChildren = (files: RegistryNode[]): TreeNode[] => {
return files.map((node): TreeNode => ({
name: node.name,
children: node.children ? flattenChildren(node.children) : [],
metadata: { path: node.path },
}))
}
const LANGUAGES: Record<string, CodeBlockLang> = {
bash: 'bash',
html: 'html',
js: 'js',
json: 'json',
jsx: 'jsx',
sh: 'bash',
sql: 'sql',
toml: 'toml',
yaml: 'yaml',
yml: 'yaml',
}
const languageFor = (fileName: string | undefined): CodeBlockLang => {
const normalized = fileName?.toLowerCase() ?? ''
if (normalized.startsWith('.env')) return 'bash'
if (normalized === 'deno.lock') return 'json'
return LANGUAGES[normalized.split('.').pop() ?? ''] ?? 'ts'
}
const findFirstFile = (nodes: RegistryNode[]): RegistryNode | null => {
for (const node of nodes) {
if (node.type === 'file') {
return node
}
if (node.children) {
const foundFile = findFirstFile(node.children)
if (foundFile) {
return foundFile
}
}
}
return null
}
export function BlockItemCode({ files, embedded = false }: BlockItemCodeProps) {
// Find the first file to select by default
const [selectedFile, setSelectedFile] = useState<RegistryNode | null>(findFirstFile(files))
const flattenedData = flattenTree({ name: '', children: flattenChildren(files) })
// Handle file selection from the TreeView
const handleNodeSelect = (filePath: string) => {
const findFileByPath = (nodes: RegistryNode[], path: string): RegistryNode | null => {
for (const node of nodes) {
if (node.path === path) {
return node
}
if (node.children) {
const found = findFileByPath(node.children, path)
if (found) {
return found
}
}
}
return null
}
const foundFile = findFileByPath(files, filePath)
if (foundFile?.type === 'directory') return
setSelectedFile(foundFile || null)
}
return (
<div
className={cn(
'flex flex-col sm:flex-row overflow-hidden not-prose',
embedded ? 'h-full' : 'mt-4 border rounded-lg h-[652px]'
)}
>
{/* File browser sidebar */}
<div className="h-44 w-full shrink-0 overflow-auto border-b bg-muted/30 py-2 sm:h-full sm:w-64 sm:border-b-0 sm:border-r">
<TreeView
data={flattenedData}
aria-label="file browser"
className="w-full"
defaultExpandedIds={flattenedData.filter((n) => n.children?.length).map((n) => n.id)}
defaultSelectedIds={flattenedData
.filter((n) => n.metadata?.path === selectedFile?.path)
.map((n) => n.id)}
onNodeSelect={({ element }) => {
if (typeof element.metadata?.path === 'string') {
handleNodeSelect(element.metadata.path)
}
}}
nodeRenderer={({ element, isBranch, isExpanded, getNodeProps, level, isSelected }) => (
<TreeViewItem
{...getNodeProps()}
isExpanded={isExpanded}
isBranch={isBranch}
isSelected={isSelected}
level={level}
icon={<File strokeWidth={1.5} size={16} className="shrink-0" />}
name={element.name}
className="gap-1.5"
/>
)}
/>
</div>
{/* Code display area */}
{selectedFile?.content ? (
<PendingCodeContext.Provider value={selectedFile.content}>
<CodeBlock
wrapperClassName="w-full min-h-0 min-w-0 flex-1"
className="h-full max-w-none w-full! flex-1 font-mono text-xs rounded-none border-none"
language={languageFor(selectedFile.name)}
>
{selectedFile?.content}
</CodeBlock>
</PendingCodeContext.Provider>
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
<div className="flex flex-col items-center gap-2">
<p>No file selected or file content unavailable</p>
</div>
</div>
)}
</div>
)
}