Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .cursorignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# Environment files
.env
.env.*
!.env.example

# Secrets directory
secrets/
Expand Down
6 changes: 6 additions & 0 deletions packages/swingset/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Copy to packages/swingset/.env.local and restart Swingset (`pnpm dev:swingset`).
# Required for /live, /sign-in, and /sign-up. The component explorer works without it.
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=

# Optional. Enables the Clerk handshake for SSO / OAuth on /sign-in and /sign-up.
CLERK_SECRET_KEY=
7 changes: 6 additions & 1 deletion packages/swingset/next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import createMDX from '@next/mdx';
import stylexPlugin from '@stylexjs/unplugin/webpack';
import { resolve } from 'path';
import { createRequire } from 'module';
import { dirname, resolve } from 'path';
import rehypeRaw from 'rehype-raw';
import remarkGfm from 'remark-gfm';
import { fileURLToPath } from 'url';

import { mosaicLightningCssTargets } from '../ui/stylex-lightningcss.config.mjs';

const require = createRequire(import.meta.url);
const __dirname = fileURLToPath(new URL('.', import.meta.url));

const withMDX = createMDX({
Expand Down Expand Up @@ -98,6 +100,9 @@ const nextConfig = {
config.resolve.alias['@clerk/headless/hooks'] = resolve(__dirname, '../headless/src/hooks');
config.resolve.alias['@clerk/headless/utils'] = resolve(__dirname, '../headless/src/utils');
config.resolve.alias['@clerk/headless'] = resolve(__dirname, '../headless/src/primitives');
// Mosaic/headless source imports this. Webpack resolves from the aliased file's
// directory, which is outside swingset, so the package has to be named here.
config.resolve.alias['@floating-ui/react'] = dirname(require.resolve('@floating-ui/react/package.json'));
return config;
},
};
Expand Down
3 changes: 3 additions & 0 deletions packages/swingset/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
"dependencies": {
"@base-ui/react": "^1.5.0",
"@clerk/headless": "workspace:*",
"@clerk/nextjs": "workspace:*",
"@clerk/shared": "workspace:*",
"@clerk/ui": "workspace:*",
"@floating-ui/react": "catalog:repo",
"@stylexjs/stylex": "0.19.0",
"@tailwindcss/typography": "^0.5.19",
"class-variance-authority": "^0.7.1",
Expand Down
63 changes: 63 additions & 0 deletions packages/swingset/src/app/(clerk)/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { ClerkProvider } from '@clerk/nextjs';
import Link from 'next/link';
import type { ReactNode } from 'react';

import { LiveUserButton } from './live-user-button';

function LiveChrome({ children, userButton }: { children: ReactNode; userButton?: ReactNode }) {
return (
<div className='flex min-h-svh flex-col'>
<header className='bg-background flex h-12 items-center justify-between gap-3 border-b px-4'>
<div className='flex items-center gap-3'>
<Link
href='/'
className='text-muted-foreground hover:text-foreground text-sm'
>
← Swingset
</Link>
<span className='text-muted-foreground text-xs'>Live</span>
</div>
{userButton}
</header>
{children}
</div>
);
}

export default function ClerkLayout({ children }: { children: ReactNode }) {
const publishableKey = process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY;

if (!publishableKey) {
return (
<LiveChrome>
<div className='mx-auto flex w-full max-w-3xl flex-col gap-2 p-3 sm:p-8'>
<h1 className='text-xl font-semibold'>Live</h1>
<p className='text-muted-foreground text-sm'>
To access sign-in, sign-up, and live pages, set up a publishable key.
</p>
<p className='text-muted-foreground text-sm'>
Copy <code className='font-mono text-xs'>packages/swingset/.env.example</code> to{' '}
<code className='font-mono text-xs'>packages/swingset/.env.local</code> and set{' '}
<code className='font-mono text-xs'>NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY</code>, then restart Swingset.
</p>
<p className='text-muted-foreground text-sm'>
<code className='font-mono text-xs'>CLERK_SECRET_KEY</code> is optional. Add it for SSO and OAuth redirects.
</p>
</div>
</LiveChrome>
);
}

return (
<ClerkProvider
publishableKey={publishableKey}
signInUrl='/sign-in'
signUpUrl='/sign-up'
signInFallbackRedirectUrl='/live/reverification'
signUpFallbackRedirectUrl='/live/reverification'
afterSignOutUrl='/live/reverification'
>
<LiveChrome userButton={<LiveUserButton />}>{children}</LiveChrome>
</ClerkProvider>
);
}
12 changes: 12 additions & 0 deletions packages/swingset/src/app/(clerk)/live-user-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use client';

import { MosaicProvider } from '@clerk/ui/mosaic/MosaicProvider';
import { UserButton } from '@clerk/ui/mosaic/user-button/user-button';

export function LiveUserButton() {
return (
<MosaicProvider>
<UserButton modePriority='user' />
</MosaicProvider>
);
}
108 changes: 108 additions & 0 deletions packages/swingset/src/app/(clerk)/live/reverification/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
'use client';

import { SignOutButton, useUser } from '@clerk/nextjs';
import { isReverificationCancelledError } from '@clerk/shared/error';
import { Button } from '@clerk/ui/mosaic/components/button';
import { Reverification, useReverificationWithState } from '@clerk/ui/mosaic/features/reverification';
import { MosaicProvider } from '@clerk/ui/mosaic/MosaicProvider';
import Link from 'next/link';
import { useState } from 'react';

async function mockDelete() {
const response = await fetch('/api/live/mock-delete', { method: 'POST' });
const body = await response.json().catch(() => ({}));

if (body?.clerk_error?.reason === 'reverification-error') {
return body;
}
if (!response.ok) {
throw new Error(typeof body.error === 'string' ? body.error : `Mock delete failed (${response.status})`);
}
return body;
}

async function resetMockDelete() {
await fetch('/api/live/mock-delete', { method: 'DELETE' });
}

function DeleteAccountHarness() {
const { user } = useUser();
const [status, setStatus] = useState<'idle' | 'success' | 'cancelled' | 'error'>('idle');
const [message, setMessage] = useState<string | null>(null);
const [deleteAccount, reverification] = useReverificationWithState(mockDelete);

if (!user) {
return null;
}

return (
<div className='flex flex-col gap-4'>
<p className='text-muted-foreground text-sm'>Signed in as {user.primaryEmailAddress?.emailAddress ?? user.id}</p>
<div className='flex flex-wrap items-center gap-2'>
<Button
color='negative'
onClick={() => {
void (async () => {
try {
setStatus('idle');
setMessage(null);
const result = await deleteAccount();
console.info('[swingset] mock delete succeeded', result);
setStatus('success');
setMessage('Mock delete completed. The account was not deleted.');
} catch (error) {
await resetMockDelete();
if (isReverificationCancelledError(error)) {
setStatus('cancelled');
setMessage('Reverification cancelled.');
return;
}
setStatus('error');
setMessage(error instanceof Error ? error.message : 'Mock delete failed.');
}
})();
}}
>
Delete account
</Button>
<SignOutButton redirectUrl='/live/reverification'>
<Button variant='outline'>Sign out</Button>
</SignOutButton>
</div>
<Reverification {...reverification} />
{message ? <p className={status === 'error' ? 'text-sm text-red-600' : 'text-sm'}>{message}</p> : null}
</div>
);
}

// Throwaway live harness. Not a story.
export default function ReverificationLivePage() {
const { isLoaded, isSignedIn } = useUser();

return (
<MosaicProvider>
<div className='mx-auto flex w-full max-w-3xl flex-col gap-6 p-3 sm:p-8'>
<div className='flex flex-col gap-1'>
<h1 className='text-xl font-semibold'>Reverification</h1>
<p className='text-muted-foreground text-sm'>
Throwaway live page. Delete account hits a mock route that returns a reverification hint, then a fake
success. The account is not deleted.
</p>
</div>
{!isLoaded ? <p className='text-muted-foreground text-sm'>Loading…</p> : null}
{isLoaded && !isSignedIn ? (
<p className='text-muted-foreground text-sm'>
<Link
href='/sign-in'
className='text-foreground underline underline-offset-4'
>
Sign in
</Link>{' '}
to use the live harness.
</p>
) : null}
{isLoaded && isSignedIn ? <DeleteAccountHarness /> : null}
</div>
</MosaicProvider>
);
}
15 changes: 15 additions & 0 deletions packages/swingset/src/app/(clerk)/sign-in/[[...sign-in]]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use client';

import { SignIn } from '@clerk/nextjs';

export default function SignInPage() {
return (
<div className='mx-auto flex w-full max-w-3xl justify-center p-3 sm:p-8'>
<SignIn
path='/sign-in'
signUpUrl='/sign-up'
fallbackRedirectUrl='/live/reverification'
/>
</div>
);
}
15 changes: 15 additions & 0 deletions packages/swingset/src/app/(clerk)/sign-up/[[...sign-up]]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use client';

import { SignUp } from '@clerk/nextjs';

export default function SignUpPage() {
return (
<div className='mx-auto flex w-full max-w-3xl justify-center p-3 sm:p-8'>
<SignUp
path='/sign-up'
signInUrl='/sign-in'
fallbackRedirectUrl='/live/reverification'
/>
</div>
);
}
7 changes: 7 additions & 0 deletions packages/swingset/src/app/(explorer)/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { ReactNode } from 'react';

import { ClientRoot } from '@/components/ClientRoot';

export default function ExplorerLayout({ children }: { children: ReactNode }) {
return <ClientRoot>{children}</ClientRoot>;
}
23 changes: 23 additions & 0 deletions packages/swingset/src/app/api/live/mock-delete/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { reverificationErrorResponse } from '@clerk/nextjs/server';
import { cookies } from 'next/headers';

const COOKIE = 'swingset-mock-delete';

export async function POST() {
const store = await cookies();

// First call: ask for step-up. After the card completes, the same fetcher is retried.
if (store.get(COOKIE)?.value !== '1') {
store.set(COOKIE, '1', { path: '/', maxAge: 120, sameSite: 'lax' });
return reverificationErrorResponse('strict');
}

store.delete(COOKIE);
return Response.json({ ok: true, at: new Date().toISOString() });
}

export async function DELETE() {
const store = await cookies();
store.delete(COOKIE);
return new Response(null, { status: 204 });
}
5 changes: 1 addition & 4 deletions packages/swingset/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { Geist } from 'next/font/google';
import Script from 'next/script';
import type React from 'react';

import { ClientRoot } from '@/components/ClientRoot';
import { ThemeProvider } from '@/components/ThemeProvider';
import { cn } from '@/lib/utils';

Expand All @@ -32,9 +31,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
)}
</head>
<body className='antialiased'>
<ThemeProvider>
<ClientRoot>{children}</ClientRoot>
</ThemeProvider>
<ThemeProvider>{children}</ThemeProvider>
</body>
</html>
);
Expand Down
22 changes: 22 additions & 0 deletions packages/swingset/src/components/app-sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/component
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
Expand Down Expand Up @@ -231,6 +232,27 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
</React.Fragment>
))}
</SidebarContent>
<SidebarFooter className='gap-0 p-0'>
<SidebarSeparator className='data-horizontal:w-auto my-1' />
<SidebarGroup className='py-1'>
<SidebarGroupLabel className='text-sidebar-foreground/50 h-auto px-2 pb-1 pt-3 text-[10px] font-semibold uppercase tracking-wider'>
Live
</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
className='h-auto py-1 text-xs'
isActive={pathname.startsWith('/live/reverification')}
render={<Link href='/live/reverification' />}
>
Reverification
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarFooter>
<SidebarRail />
</Sidebar>
);
Expand Down
13 changes: 13 additions & 0 deletions packages/swingset/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { clerkMiddleware } from '@clerk/nextjs/server';
import type { NextFetchEvent, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';

const withClerk = process.env.CLERK_SECRET_KEY ? clerkMiddleware() : null;

export default function middleware(request: NextRequest, event: NextFetchEvent) {
return withClerk ? withClerk(request, event) : NextResponse.next();
}

export const config = {
matcher: ['/sign-in(.*)', '/sign-up(.*)', '/live(.*)'],
};
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading