refactor: convert forwardRef components to function components for consistency

This commit is contained in:
Dries Augustyns
2026-05-04 21:08:14 +02:00
parent ed9027b4ef
commit 361ec0b1eb
35 changed files with 869 additions and 889 deletions
+1 -1
View File
@@ -241,7 +241,7 @@ export function ActivityFeed({typeFilter, dateRangeDays = 30, contactId}: Activi
<div className="space-y-4"> <div className="space-y-4">
{upcomingActivities.map((activity, index) => ( {upcomingActivities.map((activity, index) => (
<div key={`${activity.id}-${index}`}> <div key={`${activity.id}-${index}`}>
<ActivityItem activity={activity} isUpcoming={true} /> <ActivityItem activity={activity} status="upcoming" />
{index < upcomingActivities.length - 1 && <div className="border-t border-neutral-100 my-4" />} {index < upcomingActivities.length - 1 && <div className="border-t border-neutral-100 my-4" />}
</div> </div>
))} ))}
+3 -2
View File
@@ -110,7 +110,7 @@ function isEmailActivity(type: string): boolean {
interface ActivityItemProps { interface ActivityItemProps {
activity: Activity; activity: Activity;
isUpcoming?: boolean; status?: 'upcoming' | 'completed';
} }
interface ActivityConfig { interface ActivityConfig {
@@ -342,11 +342,12 @@ function getActivityConfig(activity: Activity): ActivityConfig {
} }
} }
export const ActivityItem = memo(function ActivityItem({activity, isUpcoming = false}: ActivityItemProps) { export const ActivityItem = memo(function ActivityItem({activity, status = 'completed'}: ActivityItemProps) {
const [showPreviewModal, setShowPreviewModal] = useState(false); const [showPreviewModal, setShowPreviewModal] = useState(false);
const config = getActivityConfig(activity); const config = getActivityConfig(activity);
const Icon = config.icon; const Icon = config.icon;
const timestamp = new Date(activity.timestamp); const timestamp = new Date(activity.timestamp);
const isUpcoming = status === 'upcoming';
const relativeTime = isUpcoming ? getUpcomingTime(timestamp) : getRelativeTime(timestamp); const relativeTime = isUpcoming ? getUpcomingTime(timestamp) : getRelativeTime(timestamp);
return ( return (
+1 -3
View File
@@ -9,7 +9,6 @@ interface ApiKeyDisplayProps {
description?: string; description?: string;
isSecret?: boolean; isSecret?: boolean;
onRegenerate?: () => Promise<void>; onRegenerate?: () => Promise<void>;
showRegenerate?: boolean;
} }
export function ApiKeyDisplay({ export function ApiKeyDisplay({
@@ -18,7 +17,6 @@ export function ApiKeyDisplay({
description, description,
isSecret = false, isSecret = false,
onRegenerate, onRegenerate,
showRegenerate = false,
}: ApiKeyDisplayProps) { }: ApiKeyDisplayProps) {
const [showKey, setShowKey] = useState(!isSecret); const [showKey, setShowKey] = useState(!isSecret);
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
@@ -101,7 +99,7 @@ export function ApiKeyDisplay({
)} )}
</AnimatePresence> </AnimatePresence>
</Button> </Button>
{showRegenerate && onRegenerate && ( {onRegenerate && (
<Button <Button
type="button" type="button"
variant="outline" variant="outline"
+6 -6
View File
@@ -59,13 +59,13 @@ const formatEmailCost = (emailCount: number, currency: string | null): string =>
interface BillingLimitsProps { interface BillingLimitsProps {
projectId: string; projectId: string;
hasSubscription: boolean; tier: 'free' | 'paid';
billingEnabled: boolean; billingEnabled: boolean;
} }
type LimitsFormValues = z.infer<typeof BillingLimitSchemas.update>; type LimitsFormValues = z.infer<typeof BillingLimitSchemas.update>;
export function BillingLimits({projectId, hasSubscription, billingEnabled}: BillingLimitsProps) { export function BillingLimits({projectId, tier, billingEnabled}: BillingLimitsProps) {
const [isEditing, setIsEditing] = useState(false); const [isEditing, setIsEditing] = useState(false);
const [successMessage, setSuccessMessage] = useState<string | null>(null); const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);
@@ -132,7 +132,7 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
}; };
// Free tier projects can view their usage but can't edit limits // Free tier projects can view their usage but can't edit limits
const canEditLimits = hasSubscription; const canEditLimits = tier === 'paid';
// If billing is not enabled, don't show the component // If billing is not enabled, don't show the component
if (!billingEnabled) { if (!billingEnabled) {
@@ -160,7 +160,7 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
<CardHeader> <CardHeader>
<CardTitle>Billing Limits</CardTitle> <CardTitle>Billing Limits</CardTitle>
<CardDescription> <CardDescription>
{hasSubscription {tier === 'paid'
? 'Set monthly limits for each email category. Limits reset on the 1st of each month.' ? 'Set monthly limits for each email category. Limits reset on the 1st of each month.'
: 'Free tier projects have a total limit of 1,000 emails per month across all categories.'} : 'Free tier projects have a total limit of 1,000 emails per month across all categories.'}
</CardDescription> </CardDescription>
@@ -168,7 +168,7 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
<CardContent> <CardContent>
<div className="space-y-6"> <div className="space-y-6">
{/* Free tier info banner */} {/* Free tier info banner */}
{!hasSubscription && limitsData && ( {tier !== 'paid' && limitsData && (
<Alert> <Alert>
<AlertCircle className="h-4 w-4" /> <AlertCircle className="h-4 w-4" />
<div className="ml-2"> <div className="ml-2">
@@ -208,7 +208,7 @@ export function BillingLimits({projectId, hasSubscription, billingEnabled}: Bill
{!isEditing && limitsData && ( {!isEditing && limitsData && (
<div className="space-y-4"> <div className="space-y-4">
{/* For free tier, show total usage across all categories */} {/* For free tier, show total usage across all categories */}
{!hasSubscription ? ( {tier !== 'paid' ? (
<UsageDisplay <UsageDisplay
category="Total Emails (All Categories)" category="Total Emails (All Categories)"
usage={limitsData.workflows} usage={limitsData.workflows}
@@ -76,7 +76,6 @@ export function EmailEditor({value, onChange, placeholder, subject, from, replyT
// Fetch contacts for preview using SWR // Fetch contacts for preview using SWR
const {contacts} = useContacts({limit: 50}); const {contacts} = useContacts({limit: 50});
// Update available variables when fields change
useEffect(() => { useEffect(() => {
if (availableFields.length > 0) { if (availableFields.length > 0) {
setAvailableVariables(availableFields); setAvailableVariables(availableFields);
@@ -11,14 +11,9 @@ interface EmailSettingsProps {
fromPlaceholder?: string; fromPlaceholder?: string;
fromNamePlaceholder?: string; fromNamePlaceholder?: string;
replyToPlaceholder?: string; replyToPlaceholder?: string;
showFromNameHelpText?: boolean;
layout?: 'vertical' | 'grid'; layout?: 'vertical' | 'grid';
} }
/**
* Reusable email settings component for from, fromName, and replyTo fields
* Used in campaign and template forms
*/
export function EmailSettings({ export function EmailSettings({
from, from,
fromName, fromName,
@@ -29,7 +24,6 @@ export function EmailSettings({
fromPlaceholder = 'hello', fromPlaceholder = 'hello',
fromNamePlaceholder = 'Your Company', fromNamePlaceholder = 'Your Company',
replyToPlaceholder, replyToPlaceholder,
showFromNameHelpText = false,
layout = 'grid', layout = 'grid',
}: EmailSettingsProps) { }: EmailSettingsProps) {
// Use from email's local part as the reply-to placeholder if not provided // Use from email's local part as the reply-to placeholder if not provided
@@ -63,11 +57,9 @@ export function EmailSettings({
onChange={e => onFromNameChange(e.target.value)} onChange={e => onFromNameChange(e.target.value)}
placeholder={fromNamePlaceholder} placeholder={fromNamePlaceholder}
/> />
{showFromNameHelpText && (
<p className="text-xs text-neutral-500 mt-1"> <p className="text-xs text-neutral-500 mt-1">
The sender name that appears in the recipient&apos;s inbox. Defaults to your project name if not set. The sender name that appears in the recipient&apos;s inbox. Defaults to your project name if not set.
</p> </p>
)}
</div> </div>
</GridWrapper> </GridWrapper>
@@ -1,5 +1,5 @@
import type {Project} from '@plunk/db'; import type {Project} from '@plunk/db';
import {createContext, type ReactNode, useContext, useEffect, useState} from 'react'; import {createContext, type ReactNode, use, useEffect, useState} from 'react';
import {useSWRConfig} from 'swr'; import {useSWRConfig} from 'swr';
import {useProjects} from '../hooks/useProject'; import {useProjects} from '../hooks/useProject';
@@ -74,7 +74,7 @@ export function ActiveProjectProvider({children}: {children: ReactNode}) {
} }
export function useActiveProject() { export function useActiveProject() {
const context = useContext(ActiveProjectContext); const context = use(ActiveProjectContext);
if (context === undefined) { if (context === undefined) {
throw new Error('useActiveProject must be used within an ActiveProjectProvider'); throw new Error('useActiveProject must be used within an ActiveProjectProvider');
} }
+36 -29
View File
@@ -106,14 +106,18 @@ export default function CampaignDetailsPage() {
); );
const [editedCampaign, setEditedCampaign] = useState<Partial<Campaign>>({}); const [editedCampaign, setEditedCampaign] = useState<Partial<Campaign>>({});
const [isScheduleDialogOpen, setIsScheduleDialogOpen] = useState(false);
const [scheduledDateTime, setScheduledDateTime] = useState(''); const [scheduledDateTime, setScheduledDateTime] = useState('');
const [isTestEmailDialogOpen, setIsTestEmailDialogOpen] = useState(false);
const [testEmailAddress, setTestEmailAddress] = useState(''); const [testEmailAddress, setTestEmailAddress] = useState('');
const [sendingTestEmail, setSendingTestEmail] = useState(false);
const [showCancelDialog, setShowCancelDialog] = useState(false); type CampaignDialog =
const [showSendDialog, setShowSendDialog] = useState(false); | {type: 'none'}
const [showDeleteDialog, setShowDeleteDialog] = useState(false); | {type: 'schedule'}
| {type: 'testEmail'; sending: boolean}
| {type: 'send'}
| {type: 'cancel'}
| {type: 'delete'};
const [dialog, setDialog] = useState<CampaignDialog>({type: 'none'});
// Automatically initialize edit fields when campaign is loaded and is a draft // Automatically initialize edit fields when campaign is loaded and is a draft
const isEditMode = campaign?.data.status === CampaignStatus.DRAFT; const isEditMode = campaign?.data.status === CampaignStatus.DRAFT;
@@ -172,7 +176,7 @@ export default function CampaignDetailsPage() {
// Show confirmation with user's local time // Show confirmation with user's local time
const localTimeString = formatFullDateTime(scheduledDate); const localTimeString = formatFullDateTime(scheduledDate);
toast.success(`Campaign scheduled for ${localTimeString}`); toast.success(`Campaign scheduled for ${localTimeString}`);
setIsScheduleDialogOpen(false); setDialog({type: 'none'});
setScheduledDateTime(''); setScheduledDateTime('');
void mutate(); void mutate();
} catch (error) { } catch (error) {
@@ -186,7 +190,7 @@ export default function CampaignDetailsPage() {
return; return;
} }
setSendingTestEmail(true); setDialog({type: 'testEmail', sending: true});
try { try {
await network.fetch<{success: boolean; message: string}>('POST', `/campaigns/${id}/test`, { await network.fetch<{success: boolean; message: string}>('POST', `/campaigns/${id}/test`, {
@@ -194,12 +198,12 @@ export default function CampaignDetailsPage() {
} as any); } as any);
toast.success(`Test email sent to ${testEmailAddress}`); toast.success(`Test email sent to ${testEmailAddress}`);
setIsTestEmailDialogOpen(false); setDialog({type: 'none'});
setTestEmailAddress(''); setTestEmailAddress('');
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to send test email'); toast.error(error instanceof Error ? error.message : 'Failed to send test email');
} finally { } finally {
setSendingTestEmail(false); setDialog(d => (d.type === 'testEmail' ? {type: 'testEmail', sending: false} : d));
} }
}; };
@@ -370,7 +374,7 @@ export default function CampaignDetailsPage() {
<Button <Button
type="button" type="button"
variant="destructive" variant="destructive"
onClick={() => setShowDeleteDialog(true)} onClick={() => setDialog({type: 'delete'})}
className="flex-1 sm:flex-none" className="flex-1 sm:flex-none"
> >
<Trash2 className="h-4 w-4" /> <Trash2 className="h-4 w-4" />
@@ -395,7 +399,7 @@ export default function CampaignDetailsPage() {
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-72"> <DropdownMenuContent align="end" className="w-72">
<DropdownMenuItem onClick={() => setIsTestEmailDialogOpen(true)} className="py-3 cursor-pointer"> <DropdownMenuItem onClick={() => setDialog({type: 'testEmail', sending: false})} className="py-3 cursor-pointer">
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<TestTube className="h-4 w-4 mt-0.5 text-neutral-700" /> <TestTube className="h-4 w-4 mt-0.5 text-neutral-700" />
<div className="flex flex-col gap-0.5 flex-1"> <div className="flex flex-col gap-0.5 flex-1">
@@ -406,7 +410,7 @@ export default function CampaignDetailsPage() {
</div> </div>
</div> </div>
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => setShowSendDialog(true)} className="py-3 cursor-pointer"> <DropdownMenuItem onClick={() => setDialog({type: 'send'})} className="py-3 cursor-pointer">
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<Send className="h-4 w-4 mt-0.5 text-neutral-700" /> <Send className="h-4 w-4 mt-0.5 text-neutral-700" />
<div className="flex flex-col gap-0.5 flex-1"> <div className="flex flex-col gap-0.5 flex-1">
@@ -417,7 +421,7 @@ export default function CampaignDetailsPage() {
</div> </div>
</div> </div>
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => setIsScheduleDialogOpen(true)} className="py-3 cursor-pointer"> <DropdownMenuItem onClick={() => setDialog({type: 'schedule'})} className="py-3 cursor-pointer">
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<Calendar className="h-4 w-4 mt-0.5 text-neutral-700" /> <Calendar className="h-4 w-4 mt-0.5 text-neutral-700" />
<div className="flex flex-col gap-0.5 flex-1"> <div className="flex flex-col gap-0.5 flex-1">
@@ -531,7 +535,6 @@ export default function CampaignDetailsPage() {
onFromNameChange={value => setEditedCampaign({...editedCampaign, fromName: value})} onFromNameChange={value => setEditedCampaign({...editedCampaign, fromName: value})}
onReplyToChange={value => setEditedCampaign({...editedCampaign, replyTo: value})} onReplyToChange={value => setEditedCampaign({...editedCampaign, replyTo: value})}
fromNamePlaceholder={activeProject?.name || 'Your Company'} fromNamePlaceholder={activeProject?.name || 'Your Company'}
showFromNameHelpText
layout="vertical" layout="vertical"
/> />
</CardContent> </CardContent>
@@ -658,7 +661,7 @@ export default function CampaignDetailsPage() {
</Card> </Card>
{/* Test Email Dialog */} {/* Test Email Dialog */}
<Dialog open={isTestEmailDialogOpen} onOpenChange={setIsTestEmailDialogOpen}> <Dialog open={dialog.type === 'testEmail'} onOpenChange={open => !open && setDialog({type: 'none'})}>
<DialogContent className="sm:max-w-lg"> <DialogContent className="sm:max-w-lg">
<DialogHeader> <DialogHeader>
<DialogTitle>Send Test Email</DialogTitle> <DialogTitle>Send Test Email</DialogTitle>
@@ -695,21 +698,25 @@ export default function CampaignDetailsPage() {
type="button" type="button"
variant="outline" variant="outline"
onClick={() => { onClick={() => {
setIsTestEmailDialogOpen(false); setDialog({type: 'none'});
setTestEmailAddress(''); setTestEmailAddress('');
}} }}
> >
Cancel Cancel
</Button> </Button>
<Button type="button" onClick={handleSendTestEmail} disabled={sendingTestEmail || !testEmailAddress}> <Button
{sendingTestEmail ? 'Sending...' : 'Send Test Email'} type="button"
onClick={handleSendTestEmail}
disabled={(dialog.type === 'testEmail' && dialog.sending) || !testEmailAddress}
>
{dialog.type === 'testEmail' && dialog.sending ? 'Sending...' : 'Send Test Email'}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
{/* Schedule Dialog */} {/* Schedule Dialog */}
<Dialog open={isScheduleDialogOpen} onOpenChange={setIsScheduleDialogOpen}> <Dialog open={dialog.type === 'schedule'} onOpenChange={open => !open && setDialog({type: 'none'})}>
<DialogContent className="sm:max-w-lg"> <DialogContent className="sm:max-w-lg">
<DialogHeader> <DialogHeader>
<DialogTitle>Schedule Campaign</DialogTitle> <DialogTitle>Schedule Campaign</DialogTitle>
@@ -801,7 +808,7 @@ export default function CampaignDetailsPage() {
type="button" type="button"
variant="outline" variant="outline"
onClick={() => { onClick={() => {
setIsScheduleDialogOpen(false); setDialog({type: 'none'});
setScheduledDateTime(''); setScheduledDateTime('');
}} }}
> >
@@ -816,11 +823,11 @@ export default function CampaignDetailsPage() {
</form> </form>
{/* Sticky Save Bar */} {/* Sticky Save Bar */}
<StickySaveBar hasChanges={hasChanges} isSubmitting={isSubmitting} onSave={handleSave} /> <StickySaveBar status={isSubmitting ? 'saving' : hasChanges ? 'dirty' : 'idle'} onSave={handleSave} />
<ConfirmDialog <ConfirmDialog
open={showSendDialog} open={dialog.type === 'send'}
onOpenChange={setShowSendDialog} onOpenChange={open => !open && setDialog({type: 'none'})}
onConfirm={handleSend} onConfirm={handleSend}
title="Send Campaign" title="Send Campaign"
description="Are you sure you want to send this campaign now? This action cannot be undone." description="Are you sure you want to send this campaign now? This action cannot be undone."
@@ -829,8 +836,8 @@ export default function CampaignDetailsPage() {
/> />
<ConfirmDialog <ConfirmDialog
open={showDeleteDialog} open={dialog.type === 'delete'}
onOpenChange={setShowDeleteDialog} onOpenChange={open => !open && setDialog({type: 'none'})}
onConfirm={handleDelete} onConfirm={handleDelete}
title="Delete Campaign" title="Delete Campaign"
description="Are you sure you want to delete this draft campaign? This action cannot be undone." description="Are you sure you want to delete this draft campaign? This action cannot be undone."
@@ -864,7 +871,7 @@ export default function CampaignDetailsPage() {
{/* Actions */} {/* Actions */}
{(c.status === CampaignStatus.SCHEDULED || c.status === CampaignStatus.SENDING) && ( {(c.status === CampaignStatus.SCHEDULED || c.status === CampaignStatus.SENDING) && (
<div className="flex justify-end"> <div className="flex justify-end">
<Button variant="destructive" onClick={() => setShowCancelDialog(true)} className="w-full sm:w-auto"> <Button variant="destructive" onClick={() => setDialog({type: 'cancel'})} className="w-full sm:w-auto">
<XCircle className="h-4 w-4" /> <XCircle className="h-4 w-4" />
<span className="hidden sm:inline">Cancel Campaign</span> <span className="hidden sm:inline">Cancel Campaign</span>
<span className="sm:hidden">Cancel</span> <span className="sm:hidden">Cancel</span>
@@ -1069,8 +1076,8 @@ export default function CampaignDetailsPage() {
</div> </div>
<ConfirmDialog <ConfirmDialog
open={showCancelDialog} open={dialog.type === 'cancel'}
onOpenChange={setShowCancelDialog} onOpenChange={open => !open && setDialog({type: 'none'})}
onConfirm={handleCancel} onConfirm={handleCancel}
title="Cancel Campaign" title="Cancel Campaign"
description="Are you sure you want to cancel this campaign?" description="Are you sure you want to cancel this campaign?"
+19 -19
View File
@@ -92,11 +92,11 @@ export default function Settings() {
const {data: user} = useUser(); const {data: user} = useUser();
const [successMessage, setSuccessMessage] = useState<string | null>(null); const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [showRegenerateDialog, setShowRegenerateDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [showResetDialog, setShowResetDialog] = useState(false);
const [deleteConfirmText, setDeleteConfirmText] = useState(''); const [deleteConfirmText, setDeleteConfirmText] = useState('');
const [resetConfirmText, setResetConfirmText] = useState(''); const [resetConfirmText, setResetConfirmText] = useState('');
type SettingsDialog = {type: 'none'} | {type: 'regenerate'} | {type: 'delete'} | {type: 'reset'};
const [dialog, setDialog] = useState<SettingsDialog>({type: 'none'});
const [isLoadingBilling, setIsLoadingBilling] = useState(false); const [isLoadingBilling, setIsLoadingBilling] = useState(false);
const [selectedCurrency, setSelectedCurrency] = useState<string>('auto'); const [selectedCurrency, setSelectedCurrency] = useState<string>('auto');
const [showCurrencySelector, setShowCurrencySelector] = useState(false); const [showCurrencySelector, setShowCurrencySelector] = useState(false);
@@ -235,18 +235,18 @@ export default function Settings() {
await projectsMutate(); await projectsMutate();
setSuccessMessage('API keys regenerated successfully'); setSuccessMessage('API keys regenerated successfully');
setShowRegenerateDialog(false); setDialog({type: 'none'});
// Clear success message after 3 seconds // Clear success message after 3 seconds
setTimeout(() => setSuccessMessage(null), 3000); setTimeout(() => setSuccessMessage(null), 3000);
} catch (error) { } catch (error) {
setErrorMessage(error instanceof Error ? error.message : 'Failed to regenerate API keys'); setErrorMessage(error instanceof Error ? error.message : 'Failed to regenerate API keys');
setShowRegenerateDialog(false); setDialog({type: 'none'});
} }
}; };
const promptRegenerateKeys = () => { const promptRegenerateKeys = () => {
setShowRegenerateDialog(true); setDialog({type: 'regenerate'});
}; };
const handleStartSubscription = async (currency: string = 'auto') => { const handleStartSubscription = async (currency: string = 'auto') => {
@@ -314,7 +314,7 @@ export default function Settings() {
await network.fetch('POST', `/users/@me/projects/${activeProject.id}/reset`); await network.fetch('POST', `/users/@me/projects/${activeProject.id}/reset`);
setSuccessMessage('Project reset successfully. All data has been cleared.'); setSuccessMessage('Project reset successfully. All data has been cleared.');
setShowResetDialog(false); setDialog({type: 'none'});
setResetConfirmText(''); setResetConfirmText('');
// Refresh the page to reload data // Refresh the page to reload data
@@ -323,7 +323,7 @@ export default function Settings() {
}, 1500); }, 1500);
} catch (error) { } catch (error) {
setErrorMessage(error instanceof Error ? error.message : 'Failed to reset project'); setErrorMessage(error instanceof Error ? error.message : 'Failed to reset project');
setShowResetDialog(false); setDialog({type: 'none'});
setResetConfirmText(''); setResetConfirmText('');
} }
}; };
@@ -338,7 +338,7 @@ export default function Settings() {
await network.fetch('DELETE', `/users/@me/projects/${activeProject.id}`); await network.fetch('DELETE', `/users/@me/projects/${activeProject.id}`);
setSuccessMessage('Project deleted successfully. Redirecting...'); setSuccessMessage('Project deleted successfully. Redirecting...');
setShowDeleteDialog(false); setDialog({type: 'none'});
setDeleteConfirmText(''); setDeleteConfirmText('');
// Refresh projects list and redirect to dashboard // Refresh projects list and redirect to dashboard
@@ -350,7 +350,7 @@ export default function Settings() {
}, 1500); }, 1500);
} catch (error) { } catch (error) {
setErrorMessage(error instanceof Error ? error.message : 'Failed to delete project'); setErrorMessage(error instanceof Error ? error.message : 'Failed to delete project');
setShowDeleteDialog(false); setDialog({type: 'none'});
setDeleteConfirmText(''); setDeleteConfirmText('');
} }
}; };
@@ -587,7 +587,7 @@ export default function Settings() {
<span>API keys, domains, billing information</span> <span>API keys, domains, billing information</span>
</div> </div>
</div> </div>
<Button type="button" variant="outline" onClick={() => setShowResetDialog(true)} className="shrink-0"> <Button type="button" variant="outline" onClick={() => setDialog({type: 'reset'})} className="shrink-0">
Reset Data Reset Data
</Button> </Button>
</div> </div>
@@ -614,7 +614,7 @@ export default function Settings() {
<Button <Button
type="button" type="button"
variant="destructive" variant="destructive"
onClick={() => setShowDeleteDialog(true)} onClick={() => setDialog({type: 'delete'})}
className="shrink-0" className="shrink-0"
> >
Delete Project Delete Project
@@ -753,7 +753,7 @@ export default function Settings() {
{/* Billing Limits */} {/* Billing Limits */}
<BillingLimits <BillingLimits
projectId={activeProject.id} projectId={activeProject.id}
hasSubscription={!!activeProject.subscription} tier={activeProject.subscription ? 'paid' : 'free'}
billingEnabled={billingEnabled} billingEnabled={billingEnabled}
/> />
@@ -814,7 +814,7 @@ export default function Settings() {
</div> </div>
{/* Regenerate Keys Confirmation Dialog */} {/* Regenerate Keys Confirmation Dialog */}
<Dialog open={showRegenerateDialog} onOpenChange={setShowRegenerateDialog}> <Dialog open={dialog.type === 'regenerate'} onOpenChange={open => !open && setDialog({type: 'none'})}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
@@ -833,7 +833,7 @@ export default function Settings() {
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => setShowRegenerateDialog(false)}> <Button variant="outline" onClick={() => setDialog({type: 'none'})}>
Cancel Cancel
</Button> </Button>
<Button variant="destructive" onClick={handleRegenerateKeys}> <Button variant="destructive" onClick={handleRegenerateKeys}>
@@ -844,7 +844,7 @@ export default function Settings() {
</Dialog> </Dialog>
{/* Reset Project Confirmation Dialog */} {/* Reset Project Confirmation Dialog */}
<Dialog open={showResetDialog} onOpenChange={setShowResetDialog}> <Dialog open={dialog.type === 'reset'} onOpenChange={open => !open && setDialog({type: 'none'})}>
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader className="space-y-3"> <DialogHeader className="space-y-3">
<div className="mx-auto w-12 h-12 bg-amber-100 rounded-full flex items-center justify-center"> <div className="mx-auto w-12 h-12 bg-amber-100 rounded-full flex items-center justify-center">
@@ -876,7 +876,7 @@ export default function Settings() {
<Button <Button
variant="outline" variant="outline"
onClick={() => { onClick={() => {
setShowResetDialog(false); setDialog({type: 'none'});
setResetConfirmText(''); setResetConfirmText('');
}} }}
className="w-full" className="w-full"
@@ -896,7 +896,7 @@ export default function Settings() {
</Dialog> </Dialog>
{/* Delete Project Confirmation Dialog */} {/* Delete Project Confirmation Dialog */}
<Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}> <Dialog open={dialog.type === 'delete'} onOpenChange={open => !open && setDialog({type: 'none'})}>
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader className="space-y-3"> <DialogHeader className="space-y-3">
<div className="mx-auto w-12 h-12 bg-red-100 rounded-full flex items-center justify-center"> <div className="mx-auto w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
@@ -934,7 +934,7 @@ export default function Settings() {
<Button <Button
variant="outline" variant="outline"
onClick={() => { onClick={() => {
setShowDeleteDialog(false); setDialog({type: 'none'});
setDeleteConfirmText(''); setDeleteConfirmText('');
}} }}
className="w-full" className="w-full"
+7 -15
View File
@@ -21,7 +21,7 @@ import {ArrowLeft, Save, Trash2, TriangleAlert} from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import {NextSeo} from 'next-seo'; import {NextSeo} from 'next-seo';
import {useRouter} from 'next/router'; import {useRouter} from 'next/router';
import {useEffect, useState} from 'react'; import {useEffect, useMemo, useState} from 'react';
import {toast} from 'sonner'; import {toast} from 'sonner';
import useSWR from 'swr'; import useSWR from 'swr';
import {TemplateSchemas, detectUnsubscribeSignal} from '@plunk/shared'; import {TemplateSchemas, detectUnsubscribeSignal} from '@plunk/shared';
@@ -38,7 +38,6 @@ export default function TemplateEditorPage() {
const [editedTemplate, setEditedTemplate] = useState<Partial<Template>>({}); const [editedTemplate, setEditedTemplate] = useState<Partial<Template>>({});
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [hasChanges, setHasChanges] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false); const [showDeleteDialog, setShowDeleteDialog] = useState(false);
// Initialize edit fields when template loads // Initialize edit fields when template loads
@@ -54,16 +53,12 @@ export default function TemplateEditorPage() {
replyTo: template.replyTo || '', replyTo: template.replyTo || '',
type: template.type, type: template.type,
}); });
// Reset hasChanges when loading fresh data
setHasChanges(false);
} }
}, [template, editedTemplate]); }, [template, editedTemplate]);
// Track changes const hasChanges = useMemo(() => {
useEffect(() => { if (!template || Object.keys(editedTemplate).length === 0) return false;
if (!template || Object.keys(editedTemplate).length === 0) return; return (
const changed =
editedTemplate.name !== template.name || editedTemplate.name !== template.name ||
(editedTemplate.description || '') !== (template.description || '') || (editedTemplate.description || '') !== (template.description || '') ||
editedTemplate.subject !== template.subject || editedTemplate.subject !== template.subject ||
@@ -71,9 +66,8 @@ export default function TemplateEditorPage() {
editedTemplate.from !== template.from || editedTemplate.from !== template.from ||
(editedTemplate.fromName || '') !== (template.fromName || '') || (editedTemplate.fromName || '') !== (template.fromName || '') ||
(editedTemplate.replyTo || '') !== (template.replyTo || '') || (editedTemplate.replyTo || '') !== (template.replyTo || '') ||
editedTemplate.type !== template.type; editedTemplate.type !== template.type
);
setHasChanges(changed);
}, [editedTemplate, template]); }, [editedTemplate, template]);
// Warn before leaving page with unsaved changes // Warn before leaving page with unsaved changes
@@ -96,7 +90,6 @@ export default function TemplateEditorPage() {
}); });
// Silent save - no toast notification // Silent save - no toast notification
setHasChanges(false);
void mutate(); void mutate();
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to save template'); toast.error(error instanceof Error ? error.message : 'Failed to save template');
@@ -267,7 +260,6 @@ export default function TemplateEditorPage() {
onFromNameChange={value => setEditedTemplate({...editedTemplate, fromName: value})} onFromNameChange={value => setEditedTemplate({...editedTemplate, fromName: value})}
onReplyToChange={value => setEditedTemplate({...editedTemplate, replyTo: value})} onReplyToChange={value => setEditedTemplate({...editedTemplate, replyTo: value})}
fromNamePlaceholder={activeProject?.name || 'Your Company'} fromNamePlaceholder={activeProject?.name || 'Your Company'}
showFromNameHelpText
layout="vertical" layout="vertical"
/> />
</CardContent> </CardContent>
@@ -290,7 +282,7 @@ export default function TemplateEditorPage() {
</form> </form>
{/* Sticky Save Bar */} {/* Sticky Save Bar */}
<StickySaveBar hasChanges={hasChanges} isSubmitting={isSubmitting} onSave={handleSave} /> <StickySaveBar status={isSubmitting ? 'saving' : hasChanges ? 'dirty' : 'idle'} onSave={handleSave} />
{/* Delete Template Confirmation */} {/* Delete Template Confirmation */}
<ConfirmDialog <ConfirmDialog
+43 -40
View File
@@ -74,12 +74,16 @@ export default function WorkflowEditorPage() {
const router = useRouter(); const router = useRouter();
const {id} = router.query; const {id} = router.query;
const [activeTab, setActiveTab] = useState<'builder' | 'executions'>('builder'); const [activeTab, setActiveTab] = useState<'builder' | 'executions'>('builder');
const [showSettingsDialog, setShowSettingsDialog] = useState(false);
const [editingStep, setEditingStep] = useState<WorkflowStep | null>(null); type WorkflowDialog =
const [showCancelAllDialog, setShowCancelAllDialog] = useState(false); | {type: 'none'}
const [executionToCancel, setExecutionToCancel] = useState<string | null>(null); | {type: 'settings'}
const [isCancelling, setIsCancelling] = useState(false); | {type: 'cancelAll'; cancelling: boolean}
const [showDeleteDialog, setShowDeleteDialog] = useState(false); | {type: 'cancelOne'; executionId: string; cancelling: boolean}
| {type: 'editStep'; step: WorkflowStep}
| {type: 'delete'};
const [dialog, setDialog] = useState<WorkflowDialog>({type: 'none'});
const {data: workflow, mutate} = useSWR<WorkflowWithDetails>(id ? `/workflows/${id}` : null, { const {data: workflow, mutate} = useSWR<WorkflowWithDetails>(id ? `/workflows/${id}` : null, {
revalidateOnFocus: false, revalidateOnFocus: false,
@@ -106,31 +110,29 @@ export default function WorkflowEditorPage() {
// Handler for cancelling a single execution // Handler for cancelling a single execution
const handleCancelExecution = async (executionId: string) => { const handleCancelExecution = async (executionId: string) => {
setIsCancelling(true); setDialog({type: 'cancelOne', executionId, cancelling: true});
try { try {
await network.fetch('DELETE', `/workflows/${id}/executions/${executionId}`); await network.fetch('DELETE', `/workflows/${id}/executions/${executionId}`);
toast.success('Execution cancelled successfully'); toast.success('Execution cancelled successfully');
setDialog({type: 'none'});
void mutate(); void mutate();
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to cancel execution'); toast.error(error instanceof Error ? error.message : 'Failed to cancel execution');
} finally { setDialog({type: 'cancelOne', executionId, cancelling: false});
setIsCancelling(false);
setExecutionToCancel(null);
} }
}; };
// Handler for cancelling all executions // Handler for cancelling all executions
const handleCancelAllExecutions = async () => { const handleCancelAllExecutions = async () => {
setIsCancelling(true); setDialog(d => (d.type === 'cancelAll' ? {...d, cancelling: true} : d));
try { try {
const result = await network.fetch<{cancelled: number}>('POST', `/workflows/${id}/executions/cancel-all`); const result = await network.fetch<{cancelled: number}>('POST', `/workflows/${id}/executions/cancel-all`);
toast.success(`Successfully cancelled ${result.cancelled} execution(s)`); toast.success(`Successfully cancelled ${result.cancelled} execution(s)`);
setDialog({type: 'none'});
void mutate(); void mutate();
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to cancel executions'); toast.error(error instanceof Error ? error.message : 'Failed to cancel executions');
} finally { setDialog(d => (d.type === 'cancelAll' ? {...d, cancelling: false} : d));
setIsCancelling(false);
setShowCancelAllDialog(false);
} }
}; };
@@ -312,7 +314,7 @@ export default function WorkflowEditorPage() {
await network.fetch<Workflow, typeof WorkflowSchemas.update>('PATCH', `/workflows/${id}`, data); await network.fetch<Workflow, typeof WorkflowSchemas.update>('PATCH', `/workflows/${id}`, data);
toast.success('Workflow updated successfully'); toast.success('Workflow updated successfully');
void mutate(); void mutate();
setShowSettingsDialog(false); setDialog({type: 'none'});
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : 'Failed to update workflow'); toast.error(error instanceof Error ? error.message : 'Failed to update workflow');
} }
@@ -336,13 +338,13 @@ export default function WorkflowEditorPage() {
if (stepId && workflow) { if (stepId && workflow) {
const step = workflow.steps.find(s => s.id === stepId); const step = workflow.steps.find(s => s.id === stepId);
if (step) { if (step) {
setEditingStep(step); setDialog({type: 'editStep', step});
} }
} }
}; };
const handleOpenSettingsEvent = () => { const handleOpenSettingsEvent = () => {
setShowSettingsDialog(true); setDialog({type: 'settings'});
}; };
window.addEventListener('workflow-edit-step', handleEditStepEvent); window.addEventListener('workflow-edit-step', handleEditStepEvent);
@@ -398,13 +400,13 @@ export default function WorkflowEditorPage() {
)} )}
</div> </div>
<div className="flex items-center gap-1.5 flex-shrink-0"> <div className="flex items-center gap-1.5 flex-shrink-0">
<Button variant="ghost" size="icon" onClick={() => setShowSettingsDialog(true)} aria-label="Settings"> <Button variant="ghost" size="icon" onClick={() => setDialog({type: 'settings'})} aria-label="Settings">
<Settings className="h-4 w-4" /> <Settings className="h-4 w-4" />
</Button> </Button>
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"
onClick={() => setShowDeleteDialog(true)} onClick={() => setDialog({type: 'delete'})}
aria-label="Delete workflow" aria-label="Delete workflow"
className="text-neutral-400 hover:text-red-600 hover:bg-red-50" className="text-neutral-400 hover:text-red-600 hover:bg-red-50"
> >
@@ -542,7 +544,7 @@ export default function WorkflowEditorPage() {
<CardDescription>View and manage all executions of this workflow</CardDescription> <CardDescription>View and manage all executions of this workflow</CardDescription>
</div> </div>
{activeExecutionsCount > 0 && ( {activeExecutionsCount > 0 && (
<Button variant="outline" onClick={() => setShowCancelAllDialog(true)}> <Button variant="outline" onClick={() => setDialog({type: 'cancelAll', cancelling: false})}>
Cancel All Active ({activeExecutionsCount}) Cancel All Active ({activeExecutionsCount})
</Button> </Button>
)} )}
@@ -616,8 +618,8 @@ export default function WorkflowEditorPage() {
<Button <Button
variant="destructiveGhost" variant="destructiveGhost"
size="sm" size="sm"
onClick={() => setExecutionToCancel(execution.id)} onClick={() => setDialog({type: 'cancelOne', executionId: execution.id, cancelling: false})}
disabled={isCancelling} disabled={dialog.type === 'cancelOne' && dialog.cancelling}
> >
Cancel Cancel
</Button> </Button>
@@ -639,37 +641,38 @@ export default function WorkflowEditorPage() {
<> <>
<SettingsDialog <SettingsDialog
workflow={workflow} workflow={workflow}
open={showSettingsDialog} open={dialog.type === 'settings'}
onOpenChange={setShowSettingsDialog} onOpenChange={open => !open && setDialog({type: 'none'})}
onSave={handleUpdateSettings} onSave={handleUpdateSettings}
/> />
{editingStep && ( {dialog.type === 'editStep' && (
<EditStepDialog <EditStepDialog
step={editingStep} step={dialog.step}
workflowId={id as string} workflowId={id as string}
open={!!editingStep} open={true}
onOpenChange={open => !open && setEditingStep(null)} onOpenChange={open => !open && setDialog({type: 'none'})}
onSuccess={() => mutate()} onSuccess={() => mutate()}
/> />
)} )}
{/* Cancel Single Execution Confirmation */} {/* Cancel Single Execution Confirmation */}
<ConfirmDialog <ConfirmDialog
open={!!executionToCancel} open={dialog.type === 'cancelOne'}
onOpenChange={open => !open && setExecutionToCancel(null)} onOpenChange={open => !open && setDialog({type: 'none'})}
onConfirm={() => { onConfirm={() => {
if (executionToCancel) { if (dialog.type === 'cancelOne') {
return handleCancelExecution(executionToCancel); return handleCancelExecution(dialog.executionId);
} }
}} }}
title="Cancel Execution" title="Cancel Execution"
description={ description={
executionToCancel && executionsData?.executions ? ( dialog.type === 'cancelOne' && executionsData?.executions ? (
<div className="space-y-2"> <div className="space-y-2">
<p> <p>
Are you sure you want to cancel the workflow execution for{' '} Are you sure you want to cancel the workflow execution for{' '}
<strong> <strong>
{executionsData.executions.find(e => e.id === executionToCancel)?.contact.email || 'this contact'} {executionsData.executions.find(e => e.id === dialog.executionId)?.contact.email ||
'this contact'}
</strong> </strong>
? ?
</p> </p>
@@ -685,13 +688,13 @@ export default function WorkflowEditorPage() {
confirmText="Cancel Execution" confirmText="Cancel Execution"
cancelText="Keep Running" cancelText="Keep Running"
variant="destructive" variant="destructive"
isLoading={isCancelling} status={dialog.type === 'cancelOne' && dialog.cancelling ? 'loading' : 'idle'}
/> />
{/* Cancel All Executions Confirmation */} {/* Cancel All Executions Confirmation */}
<ConfirmDialog <ConfirmDialog
open={showCancelAllDialog} open={dialog.type === 'cancelAll'}
onOpenChange={setShowCancelAllDialog} onOpenChange={open => !open && setDialog({type: 'none'})}
onConfirm={handleCancelAllExecutions} onConfirm={handleCancelAllExecutions}
title="Cancel All Active Executions" title="Cancel All Active Executions"
description={ description={
@@ -709,13 +712,13 @@ export default function WorkflowEditorPage() {
confirmText={`Cancel ${activeExecutionsCount} Execution${activeExecutionsCount !== 1 ? 's' : ''}`} confirmText={`Cancel ${activeExecutionsCount} Execution${activeExecutionsCount !== 1 ? 's' : ''}`}
cancelText="Keep Running" cancelText="Keep Running"
variant="destructive" variant="destructive"
isLoading={isCancelling} status={dialog.type === 'cancelAll' && dialog.cancelling ? 'loading' : 'idle'}
/> />
{/* Delete Workflow Confirmation */} {/* Delete Workflow Confirmation */}
<ConfirmDialog <ConfirmDialog
open={showDeleteDialog} open={dialog.type === 'delete'}
onOpenChange={setShowDeleteDialog} onOpenChange={open => !open && setDialog({type: 'none'})}
onConfirm={handleDelete} onConfirm={handleDelete}
title="Delete Workflow" title="Delete Workflow"
description="Are you sure you want to delete this workflow? This action cannot be undone." description="Are you sure you want to delete this workflow? This action cannot be undone."
+14 -16
View File
@@ -19,26 +19,24 @@ const alertVariants = cva(
}, },
); );
const Alert = React.forwardRef< function Alert({
HTMLDivElement, className,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants> variant,
>(({className, variant, ...props}, ref) => ( ref,
<div ref={ref} role="alert" className={cn(alertVariants({variant}), className)} {...props} /> ...props
)); }: React.ComponentProps<'div'> & VariantProps<typeof alertVariants>) {
return <div ref={ref} role="alert" className={cn(alertVariants({variant}), className)} {...props} />;
}
Alert.displayName = 'Alert'; Alert.displayName = 'Alert';
const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>( function AlertTitle({className, ref, ...props}: React.ComponentProps<'h5'>) {
({className, ...props}, ref) => ( return <h5 ref={ref} className={cn('mb-1 font-medium leading-none tracking-tight', className)} {...props} />;
<h5 ref={ref} className={cn('mb-1 font-medium leading-none tracking-tight', className)} {...props} /> }
),
);
AlertTitle.displayName = 'AlertTitle'; AlertTitle.displayName = 'AlertTitle';
const AlertDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>( function AlertDescription({className, ref, ...props}: React.ComponentProps<'div'>) {
({className, ...props}, ref) => ( return <div ref={ref} className={cn('text-sm [&_p]:leading-relaxed', className)} {...props} />;
<div ref={ref} className={cn('text-sm [&_p]:leading-relaxed', className)} {...props} /> }
),
);
AlertDescription.displayName = 'AlertDescription'; AlertDescription.displayName = 'AlertDescription';
export {Alert, AlertTitle, AlertDescription}; export {Alert, AlertTitle, AlertDescription};
+3 -7
View File
@@ -31,18 +31,14 @@ const buttonVariants = cva(
}, },
); );
export interface ButtonProps export interface ButtonProps extends React.ComponentProps<'button'>, VariantProps<typeof buttonVariants> {
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean; asChild?: boolean;
} }
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( function Button({className, variant, size, asChild = false, ref, ...props}: ButtonProps) {
({className, variant, size, asChild = false, ...props}, ref) => {
const Comp = asChild ? Slot : 'button'; const Comp = asChild ? Slot : 'button';
return <Comp className={cn(buttonVariants({variant, size, className}))} ref={ref} {...props} />; return <Comp className={cn(buttonVariants({variant, size, className}))} ref={ref} {...props} />;
}, }
);
Button.displayName = 'Button'; Button.displayName = 'Button';
export {Button, buttonVariants}; export {Button, buttonVariants};
+19 -21
View File
@@ -2,42 +2,40 @@ import * as React from 'react';
import {cn} from '../../lib'; import {cn} from '../../lib';
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({className, ...props}, ref) => ( function Card({className, ref, ...props}: React.ComponentProps<'div'>) {
return (
<div <div
ref={ref} ref={ref}
className={cn('rounded-lg border border-neutral-200 bg-white text-neutral-950 shadow-sm overflow-hidden', className)} className={cn('rounded-lg border border-neutral-200 bg-white text-neutral-950 shadow-sm overflow-hidden', className)}
{...props} {...props}
/> />
)); );
}
Card.displayName = 'Card'; Card.displayName = 'Card';
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( function CardHeader({className, ref, ...props}: React.ComponentProps<'div'>) {
({className, ...props}, ref) => ( return <div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />;
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} /> }
),
);
CardHeader.displayName = 'CardHeader'; CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( function CardTitle({className, ref, ...props}: React.ComponentProps<'div'>) {
({className, ...props}, ref) => ( return <div ref={ref} className={cn('font-semibold leading-none tracking-tight', className)} {...props} />;
<div ref={ref} className={cn('font-semibold leading-none tracking-tight', className)} {...props} /> }
),
);
CardTitle.displayName = 'CardTitle'; CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( function CardDescription({className, ref, ...props}: React.ComponentProps<'div'>) {
({className, ...props}, ref) => <div ref={ref} className={cn('text-sm text-neutral-500', className)} {...props} />, return <div ref={ref} className={cn('text-sm text-neutral-500', className)} {...props} />;
); }
CardDescription.displayName = 'CardDescription'; CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( function CardContent({className, ref, ...props}: React.ComponentProps<'div'>) {
({className, ...props}, ref) => <div ref={ref} className={cn('p-6 pt-0', className)} {...props} />, return <div ref={ref} className={cn('p-6 pt-0', className)} {...props} />;
); }
CardContent.displayName = 'CardContent'; CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( function CardFooter({className, ref, ...props}: React.ComponentProps<'div'>) {
({className, ...props}, ref) => <div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />, return <div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />;
); }
CardFooter.displayName = 'CardFooter'; CardFooter.displayName = 'CardFooter';
export {Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle}; export {Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle};
+15 -16
View File
@@ -29,7 +29,7 @@ interface ChartContextProps {
const ChartContext = React.createContext<ChartContextProps | null>(null); const ChartContext = React.createContext<ChartContextProps | null>(null);
function useChart() { function useChart() {
const context = React.useContext(ChartContext); const context = React.use(ChartContext);
if (!context) { if (!context) {
throw new Error('useChart must be used within a <ChartContainer />'); throw new Error('useChart must be used within a <ChartContainer />');
@@ -47,8 +47,7 @@ interface ChartContainerProps extends React.ComponentProps<'div'> {
children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>['children']; children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>['children'];
} }
const ChartContainer = React.forwardRef<HTMLDivElement, ChartContainerProps>( function ChartContainer({id, className, children, config, ref, ...props}: ChartContainerProps) {
({id, className, children, config, ...props}, ref) => {
const uniqueId = React.useId(); const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`; const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`;
@@ -65,8 +64,7 @@ const ChartContainer = React.forwardRef<HTMLDivElement, ChartContainerProps>(
</div> </div>
</ChartContext.Provider> </ChartContext.Provider>
); );
}, }
);
ChartContainer.displayName = 'ChartContainer'; ChartContainer.displayName = 'ChartContainer';
// ============================================ // ============================================
@@ -119,9 +117,7 @@ interface ChartTooltipContentProps
const ChartTooltip = RechartsPrimitive.Tooltip; const ChartTooltip = RechartsPrimitive.Tooltip;
const ChartTooltipContent = React.forwardRef<HTMLDivElement, ChartTooltipContentProps>( function ChartTooltipContent({
(
{
active, active,
payload, payload,
className, className,
@@ -135,9 +131,8 @@ const ChartTooltipContent = React.forwardRef<HTMLDivElement, ChartTooltipContent
color, color,
nameKey, nameKey,
labelKey, labelKey,
},
ref, ref,
) => { }: ChartTooltipContentProps & {ref?: React.Ref<HTMLDivElement>}) {
const {config} = useChart(); const {config} = useChart();
const tooltipLabel = React.useMemo(() => { const tooltipLabel = React.useMemo(() => {
@@ -235,8 +230,7 @@ const ChartTooltipContent = React.forwardRef<HTMLDivElement, ChartTooltipContent
</div> </div>
</div> </div>
); );
}, }
);
ChartTooltipContent.displayName = 'ChartTooltipContent'; ChartTooltipContent.displayName = 'ChartTooltipContent';
// ============================================ // ============================================
@@ -252,8 +246,14 @@ interface ChartLegendContentProps extends Omit<React.ComponentProps<'div'>, 'pay
const ChartLegend = RechartsPrimitive.Legend; const ChartLegend = RechartsPrimitive.Legend;
const ChartLegendContent = React.forwardRef<HTMLDivElement, ChartLegendContentProps>( function ChartLegendContent({
({className, hideIcon = false, payload, verticalAlign = 'bottom', nameKey}, ref) => { className,
hideIcon = false,
payload,
verticalAlign = 'bottom',
nameKey,
ref,
}: ChartLegendContentProps & {ref?: React.Ref<HTMLDivElement>}) {
const {config} = useChart(); const {config} = useChart();
if (!payload?.length) { if (!payload?.length) {
@@ -290,8 +290,7 @@ const ChartLegendContent = React.forwardRef<HTMLDivElement, ChartLegendContentPr
})} })}
</div> </div>
); );
}, }
);
ChartLegendContent.displayName = 'ChartLegendContent'; ChartLegendContent.displayName = 'ChartLegendContent';
export {ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle}; export {ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle};
@@ -6,10 +6,8 @@ import * as React from 'react';
import {cn} from '../../lib'; import {cn} from '../../lib';
const Checkbox = React.forwardRef< function Checkbox({className, ref, ...props}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
React.ElementRef<typeof CheckboxPrimitive.Root>, return (
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({className, ...props}, ref) => (
<CheckboxPrimitive.Root <CheckboxPrimitive.Root
ref={ref} ref={ref}
className={cn( className={cn(
@@ -22,7 +20,8 @@ const Checkbox = React.forwardRef<
<Check className="h-4 w-4" /> <Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator> </CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root> </CheckboxPrimitive.Root>
)); );
}
Checkbox.displayName = CheckboxPrimitive.Root.displayName; Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export {Checkbox}; export {Checkbox};
+27 -41
View File
@@ -7,16 +7,15 @@ import {Search} from 'lucide-react';
import {cn} from '../../lib'; import {cn} from '../../lib';
const Command = React.forwardRef< function Command({className, ref, ...props}: React.ComponentProps<typeof CommandPrimitive>) {
React.ElementRef<typeof CommandPrimitive>, return (
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({className, ...props}, ref) => (
<CommandPrimitive <CommandPrimitive
ref={ref} ref={ref}
className={cn('flex h-full w-full flex-col overflow-hidden rounded-md bg-white text-neutral-950', className)} className={cn('flex h-full w-full flex-col overflow-hidden rounded-md bg-white text-neutral-950', className)}
{...props} {...props}
/> />
)); );
}
Command.displayName = CommandPrimitive.displayName; Command.displayName = CommandPrimitive.displayName;
const CommandDialog = ({children, ...props}: React.ComponentProps<typeof DialogPrimitive.Root>) => { const CommandDialog = ({children, ...props}: React.ComponentProps<typeof DialogPrimitive.Root>) => {
@@ -44,10 +43,8 @@ const CommandDialog = ({children, ...props}: React.ComponentProps<typeof DialogP
); );
}; };
const CommandInput = React.forwardRef< function CommandInput({className, ref, ...props}: React.ComponentProps<typeof CommandPrimitive.Input>) {
React.ElementRef<typeof CommandPrimitive.Input>, return (
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({className, ...props}, ref) => (
<div className="flex items-center border-b border-neutral-200 px-4 focus-within:border-neutral-200" cmdk-input-wrapper=""> <div className="flex items-center border-b border-neutral-200 px-4 focus-within:border-neutral-200" cmdk-input-wrapper="">
<Search className="mr-3 h-5 w-5 shrink-0 text-neutral-400" /> <Search className="mr-3 h-5 w-5 shrink-0 text-neutral-400" />
<CommandPrimitive.Input <CommandPrimitive.Input
@@ -59,36 +56,28 @@ const CommandInput = React.forwardRef<
{...props} {...props}
/> />
</div> </div>
)); );
}
CommandInput.displayName = CommandPrimitive.Input.displayName; CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef< function CommandList({className, ref, ...props}: React.ComponentProps<typeof CommandPrimitive.List>) {
React.ElementRef<typeof CommandPrimitive.List>, return (
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({className, ...props}, ref) => (
<CommandPrimitive.List <CommandPrimitive.List
ref={ref} ref={ref}
className={cn('max-h-[440px] overflow-y-auto overflow-x-hidden', className)} className={cn('max-h-[440px] overflow-y-auto overflow-x-hidden', className)}
{...props} {...props}
/> />
)); );
}
CommandList.displayName = CommandPrimitive.List.displayName; CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef< function CommandEmpty({ref, ...props}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
React.ElementRef<typeof CommandPrimitive.Empty>, return <CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm text-neutral-500" {...props} />;
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty> }
>((props, ref) => (
<CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm text-neutral-500" {...props} />
));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName; CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef< function CommandGroup({className, ref, ...props}: React.ComponentProps<typeof CommandPrimitive.Group>) {
React.ElementRef<typeof CommandPrimitive.Group>, return (
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({className, ...props}, ref) => (
<CommandPrimitive.Group <CommandPrimitive.Group
ref={ref} ref={ref}
className={cn( className={cn(
@@ -97,22 +86,19 @@ const CommandGroup = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
CommandGroup.displayName = CommandPrimitive.Group.displayName; CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef< function CommandSeparator({className, ref, ...props}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
React.ElementRef<typeof CommandPrimitive.Separator>, return (
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({className, ...props}, ref) => (
<CommandPrimitive.Separator ref={ref} className={cn('-mx-1 h-px bg-neutral-200', className)} {...props} /> <CommandPrimitive.Separator ref={ref} className={cn('-mx-1 h-px bg-neutral-200', className)} {...props} />
)); );
}
CommandSeparator.displayName = CommandPrimitive.Separator.displayName; CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef< function CommandItem({className, ref, ...props}: React.ComponentProps<typeof CommandPrimitive.Item>) {
React.ElementRef<typeof CommandPrimitive.Item>, return (
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({className, ...props}, ref) => (
<CommandPrimitive.Item <CommandPrimitive.Item
ref={ref} ref={ref}
className={cn( className={cn(
@@ -121,8 +107,8 @@ const CommandItem = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
CommandItem.displayName = CommandPrimitive.Item.displayName; CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({className, ...props}: React.HTMLAttributes<HTMLSpanElement>) => { const CommandShortcut = ({className, ...props}: React.HTMLAttributes<HTMLSpanElement>) => {
+16 -20
View File
@@ -12,10 +12,8 @@ const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close; const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef< function DialogOverlay({className, ref, ...props}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
React.ElementRef<typeof DialogPrimitive.Overlay>, return (
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({className, ...props}, ref) => (
<DialogPrimitive.Overlay <DialogPrimitive.Overlay
ref={ref} ref={ref}
className={cn( className={cn(
@@ -24,13 +22,12 @@ const DialogOverlay = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName; DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef< function DialogContent({className, children, ref, ...props}: React.ComponentProps<typeof DialogPrimitive.Content>) {
React.ElementRef<typeof DialogPrimitive.Content>, return (
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({className, children, ...props}, ref) => (
<DialogPortal> <DialogPortal>
<DialogOverlay /> <DialogOverlay />
<DialogPrimitive.Content <DialogPrimitive.Content
@@ -48,7 +45,8 @@ const DialogContent = React.forwardRef<
</DialogPrimitive.Close> </DialogPrimitive.Close>
</DialogPrimitive.Content> </DialogPrimitive.Content>
</DialogPortal> </DialogPortal>
)); );
}
DialogContent.displayName = DialogPrimitive.Content.displayName; DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({className, ...props}: React.HTMLAttributes<HTMLDivElement>) => ( const DialogHeader = ({className, ...props}: React.HTMLAttributes<HTMLDivElement>) => (
@@ -61,24 +59,22 @@ const DialogFooter = ({className, ...props}: React.HTMLAttributes<HTMLDivElement
); );
DialogFooter.displayName = 'DialogFooter'; DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef< function DialogTitle({className, ref, ...props}: React.ComponentProps<typeof DialogPrimitive.Title>) {
React.ElementRef<typeof DialogPrimitive.Title>, return (
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({className, ...props}, ref) => (
<DialogPrimitive.Title <DialogPrimitive.Title
ref={ref} ref={ref}
className={cn('text-lg font-semibold leading-none tracking-tight', className)} className={cn('text-lg font-semibold leading-none tracking-tight', className)}
{...props} {...props}
/> />
)); );
}
DialogTitle.displayName = DialogPrimitive.Title.displayName; DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef< function DialogDescription({className, ref, ...props}: React.ComponentProps<typeof DialogPrimitive.Description>) {
React.ElementRef<typeof DialogPrimitive.Description>, return (
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({className, ...props}, ref) => (
<DialogPrimitive.Description ref={ref} className={cn('text-sm text-neutral-500', className)} {...props} /> <DialogPrimitive.Description ref={ref} className={cn('text-sm text-neutral-500', className)} {...props} />
)); );
}
DialogDescription.displayName = DialogPrimitive.Description.displayName; DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger}; export {Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger};
@@ -18,12 +18,14 @@ const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup; const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef< function DropdownMenuSubTrigger({
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>, className,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & { inset,
inset?: boolean; children,
} ref,
>(({className, inset, children, ...props}, ref) => ( ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {inset?: boolean}) {
return (
<DropdownMenuPrimitive.SubTrigger <DropdownMenuPrimitive.SubTrigger
ref={ref} ref={ref}
className={cn( className={cn(
@@ -36,13 +38,16 @@ const DropdownMenuSubTrigger = React.forwardRef<
{children} {children}
<ChevronRight className="ml-auto h-4 w-4" /> <ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger> </DropdownMenuPrimitive.SubTrigger>
)); );
}
DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName; DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef< function DropdownMenuSubContent({
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>, className,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent> ref,
>(({className, ...props}, ref) => ( ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent <DropdownMenuPrimitive.SubContent
ref={ref} ref={ref}
className={cn( className={cn(
@@ -51,13 +56,17 @@ const DropdownMenuSubContent = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName; DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef< function DropdownMenuContent({
React.ElementRef<typeof DropdownMenuPrimitive.Content>, className,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content> sideOffset = 4,
>(({className, sideOffset = 4, ...props}, ref) => ( ref,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal> <DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content <DropdownMenuPrimitive.Content
ref={ref} ref={ref}
@@ -69,15 +78,17 @@ const DropdownMenuContent = React.forwardRef<
{...props} {...props}
/> />
</DropdownMenuPrimitive.Portal> </DropdownMenuPrimitive.Portal>
)); );
}
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName; DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef< function DropdownMenuItem({
React.ElementRef<typeof DropdownMenuPrimitive.Item>, className,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & { inset,
inset?: boolean; ref,
} ...props
>(({className, inset, ...props}, ref) => ( }: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {inset?: boolean}) {
return (
<DropdownMenuPrimitive.Item <DropdownMenuPrimitive.Item
ref={ref} ref={ref}
className={cn( className={cn(
@@ -87,13 +98,18 @@ const DropdownMenuItem = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName; DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef< function DropdownMenuCheckboxItem({
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>, className,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem> children,
>(({className, children, checked, ...props}, ref) => ( checked,
ref,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem <DropdownMenuPrimitive.CheckboxItem
ref={ref} ref={ref}
className={cn( className={cn(
@@ -110,13 +126,17 @@ const DropdownMenuCheckboxItem = React.forwardRef<
</span> </span>
{children} {children}
</DropdownMenuPrimitive.CheckboxItem> </DropdownMenuPrimitive.CheckboxItem>
)); );
}
DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName; DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef< function DropdownMenuRadioItem({
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>, className,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem> children,
>(({className, children, ...props}, ref) => ( ref,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem <DropdownMenuPrimitive.RadioItem
ref={ref} ref={ref}
className={cn( className={cn(
@@ -132,29 +152,35 @@ const DropdownMenuRadioItem = React.forwardRef<
</span> </span>
{children} {children}
</DropdownMenuPrimitive.RadioItem> </DropdownMenuPrimitive.RadioItem>
)); );
}
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName; DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef< function DropdownMenuLabel({
React.ElementRef<typeof DropdownMenuPrimitive.Label>, className,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & { inset,
inset?: boolean; ref,
} ...props
>(({className, inset, ...props}, ref) => ( }: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {inset?: boolean}) {
return (
<DropdownMenuPrimitive.Label <DropdownMenuPrimitive.Label
ref={ref} ref={ref}
className={cn('px-2 py-1.5 text-sm font-semibold', inset && 'pl-8', className)} className={cn('px-2 py-1.5 text-sm font-semibold', inset && 'pl-8', className)}
{...props} {...props}
/> />
)); );
}
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName; DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef< function DropdownMenuSeparator({
React.ElementRef<typeof DropdownMenuPrimitive.Separator>, className,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator> ref,
>(({className, ...props}, ref) => ( ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator ref={ref} className={cn('-mx-1 my-1 h-px bg-neutral-200', className)} {...props} /> <DropdownMenuPrimitive.Separator ref={ref} className={cn('-mx-1 my-1 h-px bg-neutral-200', className)} {...props} />
)); );
}
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName; DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({className, ...props}: React.HTMLAttributes<HTMLSpanElement>) => { const DropdownMenuShortcut = ({className, ...props}: React.HTMLAttributes<HTMLSpanElement>) => {
+16 -23
View File
@@ -39,8 +39,8 @@ const FormField = <
}; };
const useFormField = () => { const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext); const fieldContext = React.use(FormFieldContext);
const itemContext = React.useContext(FormItemContext); const itemContext = React.use(FormItemContext);
const {getFieldState, formState} = useFormContext(); const {getFieldState, formState} = useFormContext();
if (!fieldContext) { if (!fieldContext) {
@@ -67,8 +67,7 @@ interface FormItemContextValue {
const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue); const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue);
const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>( function FormItem({className, ref, ...props}: React.ComponentProps<'div'>) {
({className, ...props}, ref) => {
const id = React.useId(); const id = React.useId();
return ( return (
@@ -76,44 +75,39 @@ const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivEl
<div ref={ref} className={cn('space-y-2', className)} {...props} /> <div ref={ref} className={cn('space-y-2', className)} {...props} />
</FormItemContext.Provider> </FormItemContext.Provider>
); );
}, }
);
FormItem.displayName = 'FormItem'; FormItem.displayName = 'FormItem';
const FormLabel = React.forwardRef< function FormLabel({
React.ElementRef<typeof LabelPrimitive.Root>, className,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> ref,
>(({className, ...props}, ref) => { ...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const {formItemId} = useFormField(); const {formItemId} = useFormField();
return <Label ref={ref} className={cn(className)} htmlFor={formItemId} {...props} />; return <Label ref={ref} className={cn(className)} htmlFor={formItemId} {...props} />;
}); }
FormLabel.displayName = 'FormLabel'; FormLabel.displayName = 'FormLabel';
const FormControl = React.forwardRef<React.ElementRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot>>( function FormControl({ref, ...props}: React.ComponentProps<typeof Slot>) {
({...props}, ref) => {
const {formItemId, formDescriptionId, formMessageId} = useFormField(); const {formItemId, formDescriptionId, formMessageId} = useFormField();
return ( return (
<Slot ref={ref} id={formItemId} aria-describedby={formDescriptionId} aria-invalid={!!formMessageId} {...props} /> <Slot ref={ref} id={formItemId} aria-describedby={formDescriptionId} aria-invalid={!!formMessageId} {...props} />
); );
}, }
);
FormControl.displayName = 'FormControl'; FormControl.displayName = 'FormControl';
const FormDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>( function FormDescription({className, ref, ...props}: React.ComponentProps<'p'>) {
({className, ...props}, ref) => {
const {formDescriptionId} = useFormField(); const {formDescriptionId} = useFormField();
return ( return (
<p ref={ref} id={formDescriptionId} className={cn('text-[0.8rem] text-neutral-500', className)} {...props} /> <p ref={ref} id={formDescriptionId} className={cn('text-[0.8rem] text-neutral-500', className)} {...props} />
); );
}, }
);
FormDescription.displayName = 'FormDescription'; FormDescription.displayName = 'FormDescription';
const FormMessage = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>( function FormMessage({className, children, ref, ...props}: React.ComponentProps<'p'>) {
({className, children, ...props}, ref) => {
const {error, formMessageId} = useFormField(); const {error, formMessageId} = useFormField();
const body = error ? String(error?.message) : children; const body = error ? String(error?.message) : children;
@@ -126,8 +120,7 @@ const FormMessage = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<
{body} {body}
</p> </p>
); );
}, }
);
FormMessage.displayName = 'FormMessage'; FormMessage.displayName = 'FormMessage';
export {Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useFormField}; export {Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useFormField};
+2 -2
View File
@@ -2,7 +2,7 @@ import * as React from 'react';
import {cn} from '../../lib'; import {cn} from '../../lib';
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(({className, type, ...props}, ref) => { function Input({className, type, ref, ...props}: React.ComponentProps<'input'>) {
return ( return (
<input <input
type={type} type={type}
@@ -14,7 +14,7 @@ const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
{...props} {...props}
/> />
); );
}); }
Input.displayName = 'Input'; Input.displayName = 'Input';
export {Input}; export {Input};
+3 -3
View File
@@ -1,8 +1,8 @@
import * as React from 'react'; import * as React from 'react';
import {cn} from '../../lib'; import {cn} from '../../lib';
export const Kbd = React.forwardRef<HTMLElement, React.HTMLAttributes<HTMLElement>>( export function Kbd({className, ref, ...props}: React.ComponentProps<'kbd'>) {
({className, ...props}, ref) => ( return (
<kbd <kbd
ref={ref} ref={ref}
className={cn( className={cn(
@@ -11,6 +11,6 @@ export const Kbd = React.forwardRef<HTMLElement, React.HTMLAttributes<HTMLElemen
)} )}
{...props} {...props}
/> />
),
); );
}
Kbd.displayName = 'Kbd'; Kbd.displayName = 'Kbd';
+7 -6
View File
@@ -6,12 +6,13 @@ import {cn} from '../../lib';
const labelVariants = cva('text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'); const labelVariants = cva('text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70');
const Label = React.forwardRef< function Label({
React.ElementRef<typeof LabelPrimitive.Root>, className,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants> ref,
>(({className, ...props}, ref) => ( ...props
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} /> }: React.ComponentProps<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>) {
)); return <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />;
}
Label.displayName = LabelPrimitive.Root.displayName; Label.displayName = LabelPrimitive.Root.displayName;
export {Label}; export {Label};
+10 -5
View File
@@ -9,10 +9,14 @@ const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger; const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverContent = React.forwardRef< function PopoverContent({
React.ElementRef<typeof PopoverPrimitive.Content>, className,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> align = 'center',
>(({className, align = 'center', sideOffset = 4, ...props}, ref) => ( sideOffset = 4,
ref,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal> <PopoverPrimitive.Portal>
<PopoverPrimitive.Content <PopoverPrimitive.Content
ref={ref} ref={ref}
@@ -25,7 +29,8 @@ const PopoverContent = React.forwardRef<
{...props} {...props}
/> />
</PopoverPrimitive.Portal> </PopoverPrimitive.Portal>
)); );
}
PopoverContent.displayName = PopoverPrimitive.Content.displayName; PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export {Popover, PopoverTrigger, PopoverContent}; export {Popover, PopoverTrigger, PopoverContent};
@@ -3,12 +3,12 @@ import * as ProgressPrimitive from '@radix-ui/react-progress';
import {cn} from '../../lib'; import {cn} from '../../lib';
interface ProgressProps extends React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> { interface ProgressProps extends React.ComponentProps<typeof ProgressPrimitive.Root> {
indicatorClassName?: string; indicatorClassName?: string;
} }
const Progress = React.forwardRef<React.ElementRef<typeof ProgressPrimitive.Root>, ProgressProps>( function Progress({className, value, indicatorClassName, ref, ...props}: ProgressProps) {
({className, value, indicatorClassName, ...props}, ref) => ( return (
<ProgressPrimitive.Root <ProgressPrimitive.Root
ref={ref} ref={ref}
className={cn('relative h-4 w-full overflow-hidden rounded-full bg-neutral-100', className)} className={cn('relative h-4 w-full overflow-hidden rounded-full bg-neutral-100', className)}
@@ -19,8 +19,8 @@ const Progress = React.forwardRef<React.ElementRef<typeof ProgressPrimitive.Root
style={{transform: `translateX(-${100 - (value || 0)}%)`}} style={{transform: `translateX(-${100 - (value || 0)}%)`}}
/> />
</ProgressPrimitive.Root> </ProgressPrimitive.Root>
),
); );
}
Progress.displayName = ProgressPrimitive.Root.displayName; Progress.displayName = ProgressPrimitive.Root.displayName;
export {Progress}; export {Progress};
@@ -6,18 +6,12 @@ import * as React from 'react';
import {cn} from '../../lib'; import {cn} from '../../lib';
const RadioGroup = React.forwardRef< function RadioGroup({className, ref, ...props}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({className, ...props}, ref) => {
return <RadioGroupPrimitive.Root className={cn('grid gap-2', className)} {...props} ref={ref} />; return <RadioGroupPrimitive.Root className={cn('grid gap-2', className)} {...props} ref={ref} />;
}); }
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName; RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = React.forwardRef< function RadioGroupItem({className, ref, ...props}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({className, ...props}, ref) => {
return ( return (
<RadioGroupPrimitive.Item <RadioGroupPrimitive.Item
ref={ref} ref={ref}
@@ -32,7 +26,7 @@ const RadioGroupItem = React.forwardRef<
</RadioGroupPrimitive.Indicator> </RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item> </RadioGroupPrimitive.Item>
); );
}); }
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName; RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export {RadioGroup, RadioGroupItem}; export {RadioGroup, RadioGroupItem};
+53 -41
View File
@@ -10,10 +10,8 @@ const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value; const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef< function SelectTrigger({className, children, ref, ...props}: React.ComponentProps<typeof SelectPrimitive.Trigger>) {
React.ElementRef<typeof SelectPrimitive.Trigger>, return (
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({className, children, ...props}, ref) => (
<SelectPrimitive.Trigger <SelectPrimitive.Trigger
ref={ref} ref={ref}
className={cn( className={cn(
@@ -27,13 +25,16 @@ const SelectTrigger = React.forwardRef<
<ChevronDown className="h-4 w-4 opacity-50" /> <ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon> </SelectPrimitive.Icon>
</SelectPrimitive.Trigger> </SelectPrimitive.Trigger>
)); );
}
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName; SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef< function SelectScrollUpButton({
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>, className,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton> ref,
>(({className, ...props}, ref) => ( ...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton <SelectPrimitive.ScrollUpButton
ref={ref} ref={ref}
className={cn('flex cursor-default items-center justify-center py-1', className)} className={cn('flex cursor-default items-center justify-center py-1', className)}
@@ -41,13 +42,16 @@ const SelectScrollUpButton = React.forwardRef<
> >
<ChevronUp className="h-4 w-4" /> <ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton> </SelectPrimitive.ScrollUpButton>
)); );
}
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName; SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef< function SelectScrollDownButton({
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>, className,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton> ref,
>(({className, ...props}, ref) => ( ...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton <SelectPrimitive.ScrollDownButton
ref={ref} ref={ref}
className={cn('flex cursor-default items-center justify-center py-1', className)} className={cn('flex cursor-default items-center justify-center py-1', className)}
@@ -55,13 +59,18 @@ const SelectScrollDownButton = React.forwardRef<
> >
<ChevronDown className="h-4 w-4" /> <ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton> </SelectPrimitive.ScrollDownButton>
)); );
}
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName; SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef< function SelectContent({
React.ElementRef<typeof SelectPrimitive.Content>, className,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> children,
>(({className, children, position = 'popper', ...props}, ref) => ( position = 'popper',
ref,
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal> <SelectPrimitive.Portal>
<SelectPrimitive.Content <SelectPrimitive.Content
ref={ref} ref={ref}
@@ -88,21 +97,19 @@ const SelectContent = React.forwardRef<
<SelectScrollDownButton /> <SelectScrollDownButton />
</SelectPrimitive.Content> </SelectPrimitive.Content>
</SelectPrimitive.Portal> </SelectPrimitive.Portal>
)); );
}
SelectContent.displayName = SelectPrimitive.Content.displayName; SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef< function SelectLabel({className, ref, ...props}: React.ComponentProps<typeof SelectPrimitive.Label>) {
React.ElementRef<typeof SelectPrimitive.Label>, return (
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({className, ...props}, ref) => (
<SelectPrimitive.Label ref={ref} className={cn('py-1.5 pl-8 pr-2 text-sm font-semibold', className)} {...props} /> <SelectPrimitive.Label ref={ref} className={cn('py-1.5 pl-8 pr-2 text-sm font-semibold', className)} {...props} />
)); );
}
SelectLabel.displayName = SelectPrimitive.Label.displayName; SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef< function SelectItem({className, children, ref, ...props}: React.ComponentProps<typeof SelectPrimitive.Item>) {
React.ElementRef<typeof SelectPrimitive.Item>, return (
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({className, children, ...props}, ref) => (
<SelectPrimitive.Item <SelectPrimitive.Item
ref={ref} ref={ref}
className={cn( className={cn(
@@ -119,18 +126,23 @@ const SelectItem = React.forwardRef<
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item> </SelectPrimitive.Item>
)); );
}
SelectItem.displayName = SelectPrimitive.Item.displayName; SelectItem.displayName = SelectPrimitive.Item.displayName;
interface SelectItemWithDescriptionProps extends React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> { interface SelectItemWithDescriptionProps extends React.ComponentProps<typeof SelectPrimitive.Item> {
title: string; title: string;
description?: string; description?: string;
} }
const SelectItemWithDescription = React.forwardRef< function SelectItemWithDescription({
React.ElementRef<typeof SelectPrimitive.Item>, className,
SelectItemWithDescriptionProps title,
>(({className, title, description, ...props}, ref) => ( description,
ref,
...props
}: SelectItemWithDescriptionProps) {
return (
<SelectPrimitive.Item <SelectPrimitive.Item
ref={ref} ref={ref}
className={cn( className={cn(
@@ -150,15 +162,15 @@ const SelectItemWithDescription = React.forwardRef<
{description && <span className="text-xs text-neutral-500 leading-tight">{description}</span>} {description && <span className="text-xs text-neutral-500 leading-tight">{description}</span>}
</div> </div>
</SelectPrimitive.Item> </SelectPrimitive.Item>
)); );
}
SelectItemWithDescription.displayName = 'SelectItemWithDescription'; SelectItemWithDescription.displayName = 'SelectItemWithDescription';
const SelectSeparator = React.forwardRef< function SelectSeparator({className, ref, ...props}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
React.ElementRef<typeof SelectPrimitive.Separator>, return (
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({className, ...props}, ref) => (
<SelectPrimitive.Separator ref={ref} className={cn('-mx-1 my-1 h-px bg-neutral-100', className)} {...props} /> <SelectPrimitive.Separator ref={ref} className={cn('-mx-1 my-1 h-px bg-neutral-100', className)} {...props} />
)); );
}
SelectSeparator.displayName = SelectPrimitive.Separator.displayName; SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export { export {
+10 -5
View File
@@ -5,10 +5,14 @@ import * as React from 'react';
import {cn} from '../../lib'; import {cn} from '../../lib';
const Separator = React.forwardRef< function Separator({
React.ElementRef<typeof SeparatorPrimitive.Root>, className,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root> orientation = 'horizontal',
>(({className, orientation = 'horizontal', decorative = true, ...props}, ref) => ( decorative = true,
ref,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root <SeparatorPrimitive.Root
ref={ref} ref={ref}
decorative={decorative} decorative={decorative}
@@ -20,7 +24,8 @@ const Separator = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
Separator.displayName = SeparatorPrimitive.Root.displayName; Separator.displayName = SeparatorPrimitive.Root.displayName;
export {Separator}; export {Separator};
+4 -5
View File
@@ -2,10 +2,8 @@ import * as React from 'react';
import * as SwitchPrimitives from '@radix-ui/react-switch'; import * as SwitchPrimitives from '@radix-ui/react-switch';
import {cn} from '../../lib'; import {cn} from '../../lib';
const Switch = React.forwardRef< function Switch({className, ref, ...props}: React.ComponentProps<typeof SwitchPrimitives.Root>) {
React.ElementRef<typeof SwitchPrimitives.Root>, return (
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({className, ...props}, ref) => (
<SwitchPrimitives.Root <SwitchPrimitives.Root
className={cn( className={cn(
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-white disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-neutral-900 data-[state=unchecked]:bg-neutral-200', 'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-white disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-neutral-900 data-[state=unchecked]:bg-neutral-200',
@@ -20,7 +18,8 @@ const Switch = React.forwardRef<
)} )}
/> />
</SwitchPrimitives.Root> </SwitchPrimitives.Root>
)); );
}
Switch.displayName = SwitchPrimitives.Root.displayName; Switch.displayName = SwitchPrimitives.Root.displayName;
export {Switch}; export {Switch};
+24 -30
View File
@@ -2,51 +2,49 @@ import * as React from 'react';
import {cn} from '../../lib'; import {cn} from '../../lib';
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>( function Table({className, ref, ...props}: React.ComponentProps<'table'>) {
({className, ...props}, ref) => ( return (
<div className="relative w-full overflow-auto"> <div className="relative w-full overflow-auto">
<table ref={ref} className={cn('w-full caption-bottom text-sm', className)} {...props} /> <table ref={ref} className={cn('w-full caption-bottom text-sm', className)} {...props} />
</div> </div>
),
); );
}
Table.displayName = 'Table'; Table.displayName = 'Table';
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>( function TableHeader({className, ref, ...props}: React.ComponentProps<'thead'>) {
({className, ...props}, ref) => <thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />, return <thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />;
); }
TableHeader.displayName = 'TableHeader'; TableHeader.displayName = 'TableHeader';
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>( function TableBody({className, ref, ...props}: React.ComponentProps<'tbody'>) {
({className, ...props}, ref) => ( return <tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} />;
<tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} /> }
),
);
TableBody.displayName = 'TableBody'; TableBody.displayName = 'TableBody';
const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>( function TableFooter({className, ref, ...props}: React.ComponentProps<'tfoot'>) {
({className, ...props}, ref) => ( return (
<tfoot <tfoot
ref={ref} ref={ref}
className={cn('border-t bg-neutral-50 font-medium [&>tr]:last:border-b-0', className)} className={cn('border-t bg-neutral-50 font-medium [&>tr]:last:border-b-0', className)}
{...props} {...props}
/> />
),
); );
}
TableFooter.displayName = 'TableFooter'; TableFooter.displayName = 'TableFooter';
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>( function TableRow({className, ref, ...props}: React.ComponentProps<'tr'>) {
({className, ...props}, ref) => ( return (
<tr <tr
ref={ref} ref={ref}
className={cn('border-b transition-colors hover:bg-neutral-50 data-[state=selected]:bg-neutral-100', className)} className={cn('border-b transition-colors hover:bg-neutral-50 data-[state=selected]:bg-neutral-100', className)}
{...props} {...props}
/> />
),
); );
}
TableRow.displayName = 'TableRow'; TableRow.displayName = 'TableRow';
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>( function TableHead({className, ref, ...props}: React.ComponentProps<'th'>) {
({className, ...props}, ref) => ( return (
<th <th
ref={ref} ref={ref}
className={cn( className={cn(
@@ -55,22 +53,18 @@ const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<
)} )}
{...props} {...props}
/> />
),
); );
}
TableHead.displayName = 'TableHead'; TableHead.displayName = 'TableHead';
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>( function TableCell({className, ref, ...props}: React.ComponentProps<'td'>) {
({className, ...props}, ref) => ( return <td ref={ref} className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)} {...props} />;
<td ref={ref} className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)} {...props} /> }
),
);
TableCell.displayName = 'TableCell'; TableCell.displayName = 'TableCell';
const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>( function TableCaption({className, ref, ...props}: React.ComponentProps<'caption'>) {
({className, ...props}, ref) => ( return <caption ref={ref} className={cn('mt-4 text-sm text-neutral-500', className)} {...props} />;
<caption ref={ref} className={cn('mt-4 text-sm text-neutral-500', className)} {...props} /> }
),
);
TableCaption.displayName = 'TableCaption'; TableCaption.displayName = 'TableCaption';
export {Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow}; export {Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow};
+12 -15
View File
@@ -7,10 +7,8 @@ import {cn} from '../../lib';
const Tabs = TabsPrimitive.Root; const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef< function TabsList({className, ref, ...props}: React.ComponentProps<typeof TabsPrimitive.List>) {
React.ElementRef<typeof TabsPrimitive.List>, return (
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({className, ...props}, ref) => (
<TabsPrimitive.List <TabsPrimitive.List
ref={ref} ref={ref}
className={cn( className={cn(
@@ -19,13 +17,12 @@ const TabsList = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
TabsList.displayName = TabsPrimitive.List.displayName; TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef< function TabsTrigger({className, ref, ...props}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
React.ElementRef<typeof TabsPrimitive.Trigger>, return (
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({className, ...props}, ref) => (
<TabsPrimitive.Trigger <TabsPrimitive.Trigger
ref={ref} ref={ref}
className={cn( className={cn(
@@ -34,13 +31,12 @@ const TabsTrigger = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName; TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef< function TabsContent({className, ref, ...props}: React.ComponentProps<typeof TabsPrimitive.Content>) {
React.ElementRef<typeof TabsPrimitive.Content>, return (
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({className, ...props}, ref) => (
<TabsPrimitive.Content <TabsPrimitive.Content
ref={ref} ref={ref}
className={cn( className={cn(
@@ -49,7 +45,8 @@ const TabsContent = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
TabsContent.displayName = TabsPrimitive.Content.displayName; TabsContent.displayName = TabsPrimitive.Content.displayName;
export {Tabs, TabsList, TabsTrigger, TabsContent}; export {Tabs, TabsList, TabsTrigger, TabsContent};
@@ -2,9 +2,7 @@ import * as React from 'react';
import {cn} from '../../lib'; import {cn} from '../../lib';
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {} function Textarea({className, ref, ...props}: React.ComponentProps<'textarea'>) {
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(({className, ...props}, ref) => {
return ( return (
<textarea <textarea
className={cn( className={cn(
@@ -15,7 +13,7 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(({classNam
{...props} {...props}
/> />
); );
}); }
Textarea.displayName = 'Textarea'; Textarea.displayName = 'Textarea';
export {Textarea}; export {Textarea};
+9 -5
View File
@@ -11,10 +11,13 @@ const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger; const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef< function TooltipContent({
React.ElementRef<typeof TooltipPrimitive.Content>, className,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> sideOffset = 4,
>(({className, sideOffset = 4, ...props}, ref) => ( ref,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Content <TooltipPrimitive.Content
ref={ref} ref={ref}
sideOffset={sideOffset} sideOffset={sideOffset}
@@ -24,7 +27,8 @@ const TooltipContent = React.forwardRef<
)} )}
{...props} {...props}
/> />
)); );
}
TooltipContent.displayName = TooltipPrimitive.Content.displayName; TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export {Tooltip, TooltipTrigger, TooltipContent, TooltipProvider}; export {Tooltip, TooltipTrigger, TooltipContent, TooltipProvider};
@@ -12,7 +12,7 @@ export interface ConfirmDialogProps {
confirmText?: string; confirmText?: string;
cancelText?: string; cancelText?: string;
variant?: 'default' | 'destructive'; variant?: 'default' | 'destructive';
isLoading?: boolean; status?: 'idle' | 'loading';
} }
export function ConfirmDialog({ export function ConfirmDialog({
@@ -24,8 +24,10 @@ export function ConfirmDialog({
confirmText = 'Confirm', confirmText = 'Confirm',
cancelText = 'Cancel', cancelText = 'Cancel',
variant = 'default', variant = 'default',
isLoading = false, status = 'idle',
}: ConfirmDialogProps) { }: ConfirmDialogProps) {
const isLoading = status === 'loading';
const handleConfirm = async () => { const handleConfirm = async () => {
await onConfirm(); await onConfirm();
onOpenChange(false); onOpenChange(false);
@@ -6,32 +6,21 @@ import {Button} from '../atoms/Button';
import {cn} from '../../lib'; import {cn} from '../../lib';
export interface StickySaveBarProps { export interface StickySaveBarProps {
hasChanges: boolean; status: 'idle' | 'dirty' | 'saving';
isSubmitting: boolean;
onSave: (e: React.FormEvent) => void | Promise<void>; onSave: (e: React.FormEvent) => void | Promise<void>;
className?: string; className?: string;
} }
export const StickySaveBar = React.forwardRef<HTMLDivElement, StickySaveBarProps>( export function StickySaveBar({status, onSave, className}: StickySaveBarProps) {
({hasChanges, isSubmitting, onSave, className}, ref) => { const [dismissedForStatus, setDismissedForStatus] = React.useState<string | null>(null);
const [isDismissed, setIsDismissed] = React.useState(false);
// Reset dismissed state when hasChanges becomes true const isVisible = status !== 'idle' && dismissedForStatus !== status;
React.useEffect(() => { const isSaving = status === 'saving';
if (hasChanges) {
setIsDismissed(false);
}
}, [hasChanges]);
const handleSave = (e: React.FormEvent) => {
onSave(e);
};
return ( return (
<AnimatePresence> <AnimatePresence>
{hasChanges && !isDismissed && ( {isVisible && (
<motion.div <motion.div
ref={ref}
initial={{opacity: 0, y: 20, scale: 0.95}} initial={{opacity: 0, y: 20, scale: 0.95}}
animate={{opacity: 1, y: 0, scale: 1}} animate={{opacity: 1, y: 0, scale: 1}}
exit={{opacity: 0, y: 20, scale: 0.95}} exit={{opacity: 0, y: 20, scale: 0.95}}
@@ -48,7 +37,7 @@ export const StickySaveBar = React.forwardRef<HTMLDivElement, StickySaveBarProps
</div> </div>
<button <button
type="button" type="button"
onClick={() => setIsDismissed(true)} onClick={() => setDismissedForStatus(status)}
className="text-neutral-400 hover:text-neutral-600 transition-colors -mr-1" className="text-neutral-400 hover:text-neutral-600 transition-colors -mr-1"
aria-label="Dismiss" aria-label="Dismiss"
> >
@@ -58,12 +47,12 @@ export const StickySaveBar = React.forwardRef<HTMLDivElement, StickySaveBarProps
<div className="border-t border-neutral-100 px-4 py-3"> <div className="border-t border-neutral-100 px-4 py-3">
<Button <Button
type="button" type="button"
onClick={handleSave} onClick={onSave}
disabled={isSubmitting} disabled={isSaving}
size="sm" size="sm"
className="w-full" className="w-full"
> >
{isSubmitting ? ( {isSaving ? (
<> <>
<motion.div <motion.div
animate={{rotate: 360}} animate={{rotate: 360}}
@@ -85,7 +74,4 @@ export const StickySaveBar = React.forwardRef<HTMLDivElement, StickySaveBarProps
)} )}
</AnimatePresence> </AnimatePresence>
); );
}, }
);
StickySaveBar.displayName = 'StickySaveBar';