### Install Form Builder Dependencies Source: https://github.com/hasanharman/form-builder/blob/main/README.md Installs the necessary Node.js dependencies for the Form Builder project. This command should be run after cloning the repository and navigating into the project directory. ```bash npm install ``` -------------------------------- ### Install Credit Card Component with shadcn-ui Source: https://github.com/hasanharman/form-builder/blob/main/components/ui/credit-card.md This command installs the Credit Card component using the shadcn-ui CLI. Ensure you have shadcn-ui set up in your project before running this command. It manages dependencies and component files. ```bash npx shadcn-ui@latest add credit-card ``` -------------------------------- ### Start Form Builder Development Server Source: https://github.com/hasanharman/form-builder/blob/main/README.md Starts the development server for the Form Builder application. This allows you to view and interact with the form builder in your local environment, typically accessible at http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### GET /api/file/:filename Source: https://context7.com/hasanharman/form-builder/llms.txt Securely retrieves the content of a specified template file. Includes validation to prevent directory traversal attacks. ```APIDOC ## GET /api/file/:filename ### Description Securely retrieves template file contents with validation to prevent directory traversal attacks. ### Method GET ### Endpoint /api/file/:filename ### Parameters #### Path Parameters - **filename** (string) - Required - The name of the template file to retrieve. Must contain only alphanumeric characters and hyphens. #### Query Parameters None ### Request Example ```javascript fetch('/api/file/login') .then(res => { if (!res.ok) throw new Error('File not found'); return res.json(); }) .then(data => { console.log('Template content:', data.content); // Use the content in code editor or preview }) .catch(error => { console.error('Error loading template:', error); }); ``` ### Response #### Success Response (200) - **content** (string) - The content of the requested template file. #### Response Example ```json { "content": "..." } ``` ### Error Handling - **404 Not Found**: If the specified file does not exist or is not accessible. - **400 Bad Request**: If the filename is invalid (e.g., contains malicious path characters). ``` -------------------------------- ### GET /api/sponsors Source: https://context7.com/hasanharman/form-builder/llms.txt Retrieves GitHub sponsors data including active sponsors categorized by support tiers (header, project, community) and historical sponsor information. ```APIDOC ## GET /api/sponsors ### Description Retrieves GitHub sponsors data with tiered support levels (header, project, community) and historical sponsor information. ### Method GET ### Endpoint /api/sponsors ### Parameters #### Query Parameters None ### Request Example ```javascript fetch('/api/sponsors') .then(res => res.json()) .then(data => { console.log('Header sponsors:', data.active.header); console.log('Project supporters:', data.active.project); console.log('Community supporters:', data.active.community); console.log('Past sponsors:', data.past); }) .catch(error => { console.error('Failed to fetch sponsors:', error); }); ``` ### Response #### Success Response (200) - **active** (object) - Contains active sponsors categorized into header, project, and community. - **past** (array) - Contains a list of past sponsors. #### Response Example ```json { "active": { "header": [ { "id": "sponsor-id-123", "name": "Example Company", "image": "https://avatars.githubusercontent.com/u/123456", "url": "https://example.com", "tierName": "Header Sponsor", "monthly": 100, "isActive": true } ], "project": [], "community": [] }, "past": [] } ``` ``` -------------------------------- ### Basic Credit Card Component Usage in React (TSX) Source: https://github.com/hasanharman/form-builder/blob/main/components/ui/credit-card.md This example demonstrates the basic integration of the CreditCard component in a React application using TypeScript. It utilizes the useState hook to manage the credit card data and passes it along with an onChange handler to the CreditCard component. ```tsx import { useState } from 'react' import { CreditCard } from '@/components/ui/credit-card' export default function PaymentPage() { const [cardData, setCardData] = useState({ cardholderName: '', cardNumber: '', expiryMonth: '', expiryYear: '', cvv: '', cvvLabel: 'CVC' as const }) return (

Payment Information

) } ``` -------------------------------- ### Secure File Content API Endpoint (TypeScript) Source: https://context7.com/hasanharman/form-builder/llms.txt Securely retrieves template file contents using a GET request to '/api/file/{filename}'. It includes validation to prevent directory traversal attacks, ensuring only intended files are accessed. Valid filenames consist of alphanumeric characters and hyphens. ```typescript fetch('/api/file/login') .then(res => { if (!res.ok) throw new Error('File not found'); return res.json(); }) .then(data => { console.log('Template content:', data.content); // Use the content in code editor or preview }) .catch(error => { console.error('Error loading template:', error); }); ``` -------------------------------- ### Credit Card Component Usage with Form Validation in React (TSX) Source: https://github.com/hasanharman/form-builder/blob/main/components/ui/credit-card.md This example shows how to use the CreditCard component within a form and implement basic client-side validation. It checks if all required fields are filled before enabling a 'Process Payment' button. The state management and validation logic are handled using React hooks. ```tsx import { useState } from 'react' import { CreditCard } from '@/components/ui/credit-card' import { Button } from '@/components/ui/button' export default function CheckoutForm() { const [cardData, setCardData] = useState({ cardholderName: '', cardNumber: '', expiryMonth: '', expiryYear: '', cvv: '', cvvLabel: 'CVC' as const }) const isValid = cardData.cardholderName.trim() && cardData.cardNumber.trim() && cardData.expiryMonth.trim() && cardData.expiryYear.trim() && cardData.cvv.trim() const handleSubmit = () => { if (isValid) { console.log('Processing payment...', cardData) } } return (
) } ``` -------------------------------- ### Fetch GitHub Sponsors Data API (TypeScript) Source: https://context7.com/hasanharman/form-builder/llms.txt Retrieves GitHub sponsors data including tiered support levels (header, project, community) and historical sponsor information. This API endpoint is designed for fetching and displaying sponsor contributions. ```typescript fetch('/api/sponsors') .then(res => res.json()) .then(data => { console.log('Header sponsors:', data.active.header); console.log('Project supporters:', data.active.project); console.log('Community supporters:', data.active.community); console.log('Past sponsors:', data.past); }) .catch(error => { console.error('Failed to fetch sponsors:', error); }); ``` -------------------------------- ### JSON Schema Generation Utilities Source: https://context7.com/hasanharman/form-builder/llms.txt Utilities for converting Zod schemas into JSON Schema format. Supports generation from Zod objects and arrays of form fields, and includes functionality to download the generated schema. ```APIDOC ## JSON Schema Generation Utilities ### Description Converts Zod schemas to JSON Schema format for API documentation, validation, and integration with external tools. Includes functions to generate schema from Zod objects or form field definitions, and to download the schema as a JSON file. ### Method Utility Functions (Not API Endpoints) ### Functions - **`generateJsonSchema(schema, config)`**: Generates JSON Schema from a Zod schema. - **`generateFormJsonSchema(fields, config)`**: Generates JSON Schema from an array of form field definitions. - **`downloadJsonSchema(schema, filename)`**: Downloads the generated schema as a JSON file. ### Usage Example ```typescript import { z } from 'zod'; import { generateJsonSchema, generateFormJsonSchema, downloadJsonSchema } from '@/lib/json-schema-generator'; // Generate from Zod schema const userSchema = z.object({ name: z.string().min(2), email: z.string().email(), age: z.number().min(18), newsletter: z.boolean().optional() }); const jsonSchema = generateJsonSchema(userSchema, { title: 'User Registration Schema', description: 'Schema for user registration form' }); // Generate from form fields array const formFields = [ { name: 'email', variant: 'Input', type: 'email', required: true }, { name: 'age', variant: 'Number', required: true }, { name: 'subscribe', variant: 'Checkbox', required: false } ]; const formJsonSchema = generateFormJsonSchema(formFields, { title: 'Dynamic Form Schema' }); // Download schema as JSON file downloadJsonSchema(jsonSchema, 'user-registration-schema.json'); console.log('Generated JSON Schema:', jsonSchema); console.log('Generated Form JSON Schema:', formJsonSchema); ``` ### Parameters - **`schema`** (ZodSchema): The Zod schema object to convert. - **`fields`** (Array): An array of form field definitions, each with properties like `name`, `variant`, `type`, `required`. - **`config`** (Object): Optional configuration object for `title` and `description`. - **`filename`** (string): The desired name for the downloaded JSON file. ### Response Example (for `jsonSchema`) ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "User Registration Schema", "description": "Schema for user registration form", "type": "object", "properties": { "name": { "type": "string", "minLength": 2 }, "email": { "type": "string", "format": "email" }, "age": { "type": "number", "minimum": 18 }, "newsletter": { "type": "boolean" } }, "required": ["name", "email", "age"] } ``` ``` -------------------------------- ### Media Query Hook for Responsive Design in React Source: https://context7.com/hasanharman/form-builder/llms.txt A React hook for managing responsive design by monitoring media queries. It provides SSR-safe implementation and automatically updates when the window resizes. The hook returns a boolean indicating whether the current viewport matches the specified media query. ```typescript import { useMediaQuery } from '@/hooks/use-media-query'; function ResponsiveComponent() { const isMobile = useMediaQuery('(max-width: 768px)'); const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)'); const isDesktop = useMediaQuery('(min-width: 1025px)'); const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)'); const isLandscape = useMediaQuery('(orientation: landscape)'); return (
{isMobile && ( )} {isTablet && ( )} {isDesktop && ( )} {isDarkMode && (

Dark mode is active

)}
); } // Common breakpoints const breakpoints = { sm: useMediaQuery('(min-width: 640px)'), md: useMediaQuery('(min-width: 768px)'), lg: useMediaQuery('(min-width: 1024px)'), xl: useMediaQuery('(min-width: 1280px)'), '2xl': useMediaQuery('(min-width: 1536px)') }; // Hook automatically updates on window resize // Returns boolean indicating current match status ``` -------------------------------- ### Build Zod Validation Schemas with TypeScript Source: https://context7.com/hasanharman/form-builder/llms.txt Helper functions for creating complex Zod validation schemas with reusable patterns. These functions include creating form schemas, adding optional fields, creating array schemas with minimum item constraints, and custom refinement schemas. They leverage the Zod library and are written in TypeScript. ```typescript import { z } from 'zod'; import { createFormSchema, addOptionalField, createArraySchema, createRefineSchema } from '@/lib/validation-utils'; // Create form schema from fields const schema = createFormSchema({ username: z.string().min(3), email: z.string().email(), age: z.number().min(18) }); // Make a field optional const optionalEmail = addOptionalField(z.string().email()); // Create array validation with minimum items const tagsSchema = createArraySchema(z.string(), 3); const result = tagsSchema.parse(['tag1', 'tag2', 'tag3']); // Valid try { tagsSchema.parse(['tag1']); // Throws error } catch (error) { console.error(error.message); // "Please select at least 3 items" } // Custom refinement with error message const passwordSchema = createRefineSchema( z.string().min(8), (password) => /[A-Z]/.test(password) && /[0-9]/.test(password), 'Password must contain at least one uppercase letter and one number' ); // Usage in form validation const formSchema = createFormSchema({ password: passwordSchema, confirmPassword: z.string() }).refine((data) => data.password === data.confirmPassword, { path: ['confirmPassword'], message: 'Passwords do not match' }); ``` -------------------------------- ### Use Pre-built Zod Validation Schemas in TypeScript Source: https://context7.com/hasanharman/form-builder/llms.txt Ready-to-use Zod schemas for common form validation scenarios, including individual fields like email and password, as well as complete form schemas for login, registration, and contact. These schemas simplify form validation logic by providing pre-defined structures and rules. ```typescript import { emailSchema, passwordSchema, contactFormSchema, loginFormSchema, registerFormSchema } from '@/lib/validation-schemas'; // Individual field validation const email = emailSchema.parse('user@example.com'); // Valid try { emailSchema.parse('invalid-email'); // Throws ZodError } catch (error) { console.error(error.errors[0].message); // "Invalid email address" } // Login form validation const loginData = { email: 'user@example.com', password: 'secure123' }; try { const validated = loginFormSchema.parse(loginData); // Submit to API await fetch('/api/login', { method: 'POST', body: JSON.stringify(validated), headers: { 'Content-Type': 'application/json' } }); } catch (error) { console.error('Validation failed:', error.errors); } // Registration with password confirmation const registerData = { name: 'John Doe', email: 'john@example.com', phone: '1234567890', password: 'secure123', confirmPassword: 'secure123' }; const validatedRegistration = registerFormSchema.parse(registerData); // Contact form validation const contactData = { name: 'Jane Smith', email: 'jane@example.com', message: 'This is my inquiry about your product features.' }; contactFormSchema.parse(contactData); // Valid with error messages on failure ``` -------------------------------- ### Toast Notification Hook with Queue Management (TypeScript) Source: https://context7.com/hasanharman/form-builder/llms.txt Implements an imperative toast notification system using a custom hook. It supports queue management, auto-dismissal, customizable variants (default, destructive), and actions like buttons within toasts. Dependencies include the '@/hooks/use-toast' module. Input is a toast configuration object, and output is toast control functions. ```typescript import { useToast } from '@/hooks/use-toast'; function NotificationExample() { const { toast, dismiss } = useToast(); const showSuccess = () => { toast({ title: 'Success!', description: 'Your form has been submitted successfully.', variant: 'default' }); }; const showError = () => { const { id, dismiss: dismissToast } = toast({ title: 'Error', description: 'Failed to submit form. Please try again.', variant: 'destructive' }); // Auto-dismiss after 5 seconds setTimeout(() => dismissToast(), 5000); }; const showWithAction = () => { toast({ title: 'File uploaded', description: 'Your document has been uploaded.', action: ( ) }); }; const handleFormSubmit = async (data) => { const { id, update } = toast({ title: 'Uploading...', description: 'Please wait while we process your request.' }); try { await fetch('/api/submit', { method: 'POST', body: JSON.stringify(data) }); // Update existing toast update({ id, title: 'Success!', description: 'Your data has been saved.' }); } catch (error) { update({ id, title: 'Error', description: error.message, variant: 'destructive' }); } }; return (
); } // Toast limit is set to 1 by default (TOAST_LIMIT) // Auto-remove delay is configurable (TOAST_REMOVE_DELAY) ``` -------------------------------- ### Create Git Branch for Contribution Source: https://github.com/hasanharman/form-builder/blob/main/README.md Creates a new Git branch for implementing a feature or fix. This is a standard step in contributing to a project, allowing for isolated development before merging changes. ```bash git checkout -b feature/YourFeatureName ``` -------------------------------- ### Class Name Utility (cn) Source: https://context7.com/hasanharman/form-builder/llms.txt A utility function for merging and deduplicating Tailwind CSS class names using `clsx` and `tailwind-merge`. It handles conditional classes, overrides, and supports array/object syntax. ```APIDOC ## Class Name Utility (cn) ### Description Merges and deduplicates Tailwind CSS class names with `clsx` and `tailwind-merge` for conflict resolution. Supports conditional classes and array/object syntax. ### Method Utility Function (Not an API Endpoint) ### Usage Example ```typescript import { cn } from '@/lib/utils'; // Conditional classes with proper merging const buttonClasses = cn( 'px-4 py-2 rounded', isActive && 'bg-blue-500 text-white', !isActive && 'bg-gray-200 text-gray-700', isDisabled && 'opacity-50 cursor-not-allowed' ); // Override Tailwind classes (tailwind-merge prevents conflicts) const overrideExample = cn( 'p-4 bg-red-500', 'p-6 bg-blue-500' // Results in: "p-6 bg-blue-500" ); // Array and object syntax support const dynamicClasses = cn( 'base-class', ['additional', 'classes'], { 'conditional-class': someCondition }, someValue && 'value-based-class' ); console.log(buttonClasses); console.log(overrideExample); console.log(dynamicClasses); ``` ### Parameters - Accepts a variable number of string arguments, arrays, or objects representing CSS class names. ### Returns - A single string containing the merged and deduplicated CSS class names. ``` -------------------------------- ### Format JSX/JavaScript Code with TypeScript Source: https://context7.com/hasanharman/form-builder/llms.txt Beautifies JSX/JavaScript code using consistent indentation and formatting rules. This utility helps in maintaining code readability and standardization, especially when generating or manipulating code snippets programmatically. It takes a string of code as input and returns a formatted string. ```typescript import { formatJSXCode } from '@/lib/utils'; // Format messy JSX code const messyCode = ` function Component(){return

Title

Content

} `; const formatted = formatJSXCode(messyCode); console.log(formatted); // Output: // function Component() { // return
//

Title

//

Content

//
// } // Format generated code for display const generateComponent = (name, props) => { const code = ` export default function ${name}(${JSON.stringify(props)}){ const [state,setState]=useState(null); return

{state}

}`; return formatJSXCode(code); }; const prettified = generateComponent('MyComponent', { title: 'Hello' }); // Use in code editor or preview function CodeEditor({ code }) { const [formattedCode, setFormattedCode] = useState(''); const handleFormat = () => { try { const result = formatJSXCode(code); setFormattedCode(result); } catch (error) { console.error('Formatting failed:', error); } }; return (
{formattedCode || code}
); } // Configuration: 2-space indentation, preserves newlines, // max 2 blank lines, no line wrapping ``` -------------------------------- ### Signature Input Component for React Source: https://context7.com/hasanharman/form-builder/llms.txt A React component for capturing signatures using an HTML canvas. It supports touch and mouse input, automatically adjusts stroke color based on the theme, and exports the signature as a data URL. It includes touch event handling to prevent scroll interference and a clear button for corrections. ```typescript import SignatureInput from '@/components/ui/signature-input'; import { useRef, useState } from 'react'; function SignatureForm() { const canvasRef = useRef(null); const [signatureData, setSignatureData] = useState(null); const handleSubmit = async () => { if (!signatureData) { alert('Please provide a signature'); return; } // signatureData is a base64 data URL of the signature const formData = { name: 'John Doe', signature: signatureData // "data:image/png;base64,iVBORw0KG..." }; try { const response = await fetch('/api/submit-signature', { method: 'POST', body: JSON.stringify(formData), headers: { 'Content-Type': 'application/json' } }); if (response.ok) { console.log('Signature submitted successfully'); } } catch (error) { console.error('Submission failed:', error); } }; return (
{ setSignatureData(dataUrl); if (dataUrl) { console.log('Signature captured:', dataUrl.substring(0, 50) + '...'); } else { console.log('Signature cleared'); } }} /> {signatureData && (

Signature preview:

Signature
)}
); } // Canvas automatically adjusts stroke color based on theme (dark/light) // Touch events prevent scroll interference during drawing // Clear button included for user corrections ``` -------------------------------- ### String Case Transformation Utilities in TypeScript Source: https://context7.com/hasanharman/form-builder/llms.txt Provides utilities for transforming strings into different cases, such as sentence case and lowercase. It also includes a utility to check if a string is not empty after trimming whitespace. These functions are useful for standardizing text in UI elements and data processing. ```typescript import { sentenceCase, lowerCase, isNotEmpty } from '@/lib/utils'; // Convert to sentence case const title = sentenceCase('HELLO WORLD'); console.log(title); // "Hello world" const label = sentenceCase('user_name'); console.log(label); // "User_name" // Convert to lowercase with first character lowercased const varName = lowerCase('UserProfile'); console.log(varName); // "userprofile" const apiEndpoint = lowerCase('API_KEY'); console.log(apiEndpoint); // "api_key" // Validate non-empty strings const userInput = ' hello '; if (isNotEmpty(userInput)) { console.log('Input is valid'); // Executes - trims whitespace } const emptyInput = ' '; if (!isNotEmpty(emptyInput)) { console.error('Input is empty'); // Executes } // Practical usage in forms function FormField({ label, value, onChange }) { const [error, setError] = useState(''); const handleChange = (e) => { const input = e.target.value; if (!isNotEmpty(input)) { setError('This field is required'); } else { setError(''); onChange(input); } }; return (
{error && {error}}
); } // Generate labels from field names const fields = ['firstName', 'lastName', 'emailAddress']; const labels = fields.map(field => sentenceCase(field.replace(/([A-Z])/g, ' $1')) ); console.log(labels); // ["First name", "Last name", "Email address"] ``` -------------------------------- ### Handle Form Submission with Fetch API Source: https://github.com/hasanharman/form-builder/blob/main/README.md An asynchronous function to handle form submissions. It sends the form data to a '/api/form-submit' endpoint using a POST request with JSON payload. Includes basic error handling for network requests. ```javascript const handleSubmit = async (data) => { try { const response = await fetch('/api/form-submit', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json', }, }); const result = await response.json(); console.log('Form submitted successfully:', result); } catch (error) { console.error('Error submitting form:', error); } }; ``` -------------------------------- ### Push Git Changes to Remote Repository Source: https://github.com/hasanharman/form-builder/blob/main/README.md Pushes the committed changes from the local feature branch to the remote repository. This makes the changes available for review and merging. ```bash git push origin feature/YourFeatureName ``` -------------------------------- ### Generate JSON Schema from Zod Schemas (TypeScript) Source: https://context7.com/hasanharman/form-builder/llms.txt Converts Zod schemas into JSON Schema format using provided utility functions. This is useful for API documentation, data validation, and integration with external tools. It supports generation from both Zod objects and arrays of form fields. ```typescript import { z } from 'zod'; import { generateJsonSchema, generateFormJsonSchema, downloadJsonSchema } from '@/lib/json-schema-generator'; // Generate from Zod schema const userSchema = z.object({ name: z.string().min(2), email: z.string().email(), age: z.number().min(18), newsletter: z.boolean().optional() }); const jsonSchema = generateJsonSchema(userSchema, { title: 'User Registration Schema', description: 'Schema for user registration form' }); // Generate from form fields array const formFields = [ { name: 'email', variant: 'Input', type: 'email', required: true }, { name: 'age', variant: 'Number', required: true }, { name: 'subscribe', variant: 'Checkbox', required: false } ]; const formJsonSchema = generateFormJsonSchema(formFields, { title: 'Dynamic Form Schema' }); // Download schema as JSON file downloadJsonSchema(jsonSchema, 'user-registration-schema.json'); console.log(jsonSchema); // Output structure: // { // "$schema": "http://json-schema.org/draft-07/schema#", // "type": "object", // "properties": { // "name": { "type": "string", "minLength": 2 }, // "email": { "type": "string", "format": "email" }, // "age": { "type": "number", "minimum": 18 } // }, // "required": ["name", "email", "age"] // } ``` -------------------------------- ### Implement Location Selector Component in React Source: https://context7.com/hasanharman/form-builder/llms.txt An interactive country and state selector component for React applications. It features searchable dropdowns for countries and states, displays emoji flags for countries, and provides relevant data upon selection. This component is useful for forms requiring location input. ```typescript import LocationSelector from '@/components/ui/location-input'; import { useState } from 'react'; function RegistrationForm() { const [country, setCountry] = useState(null); const [state, setState] = useState(null); return (
{ setCountry(selectedCountry); console.log('Selected:', selectedCountry.name, selectedCountry.emoji); console.log('Phone code:', selectedCountry.phone_code); console.log('Currency:', selectedCountry.currency); }} onStateChange={(selectedState) => { setState(selectedState); console.log('State:', selectedState.name); console.log('State code:', selectedState.state_code); }} /> {country && (

You selected: {country.emoji} {country.name}

)} {state && (

State/Province: {state.name}

)} ); } // Country data structure includes: // { // id: 1, name: "United States", emoji: "🇺🇸", // phone_code: "+1", currency: "USD", currency_symbol: "$", // latitude: "38.00000000", longitude: "-97.00000000", // timezones: [{ zoneName: "America/New_York", ... }] // } // State data structure includes: // { // id: 1, name: "California", country_code: "US", // state_code: "CA", latitude: "36.77826100", longitude: "-119.41793240" // } ``` -------------------------------- ### Define Form Validation Schema with Zod Source: https://github.com/hasanharman/form-builder/blob/main/README.md Defines a validation schema for a form using the Zod library. This schema specifies the expected data types and validation rules for each form field, such as 'name', 'email', and 'age'. ```javascript import { z } from 'zod'; const formSchema = z.object({ name: z.string().min(1, "Name is required"), email: z.string().email("Invalid email address"), age: z.number().min(18, "You must be at least 18 years old"), }); ``` -------------------------------- ### Commit Changes in Git Source: https://github.com/hasanharman/form-builder/blob/main/README.md Commits staged changes to the current Git branch with a descriptive message. This is part of the standard Git workflow for tracking changes and preparing for pull requests. ```bash git commit -m "Add a feature" ``` -------------------------------- ### Merge Tailwind CSS Class Names Utility (TypeScript) Source: https://context7.com/hasanharman/form-builder/llms.txt A utility function `cn` that merges and deduplicates Tailwind CSS class names using `clsx` and `tailwind-merge`. It supports conditional classes, array/object syntax, and proper conflict resolution for styling. ```typescript import { cn } from '@/lib/utils'; // Conditional classes with proper merging const buttonClasses = cn( 'px-4 py-2 rounded', isActive && 'bg-blue-500 text-white', !isActive && 'bg-gray-200 text-gray-700', isDisabled && 'opacity-50 cursor-not-allowed' ); // Override Tailwind classes (tailwind-merge prevents conflicts) const overrideExample = cn( 'p-4 bg-red-500', // These will be properly merged 'p-6 bg-blue-500' // Results in: "p-6 bg-blue-500" ); // Array and object syntax support const dynamicClasses = cn( 'base-class', ['additional', 'classes'], { 'conditional-class': someCondition }, someValue && 'value-based-class' ); ``` -------------------------------- ### Define Credit Card Component Props in TypeScript Source: https://github.com/hasanharman/form-builder/blob/main/components/ui/credit-card.md This TypeScript interface outlines the props accepted by the CreditCard component. It includes optional 'value' and 'onChange' handlers for managing the credit card data, and an optional 'className' for custom styling. ```typescript interface CreditCardProps { value?: CreditCardValue onChange?: (value: CreditCardValue) => void className?: string } ``` -------------------------------- ### Immutable Array Utility Functions (TypeScript) Source: https://context7.com/hasanharman/form-builder/llms.txt Provides immutable utility functions for array manipulation, including removing items and finding the closest item in a list. These functions ensure the original array remains unchanged. Useful for state management and UI interactions where immutability is crucial. Dependencies include '@/constants/array-utils'. ```typescript import { removeItem, closestItem } from '@/constants/array-utils'; // Remove item from array immutably const colors = ['red', 'blue', 'green', 'yellow']; const withoutBlue = removeItem(colors, 'blue'); console.log(withoutBlue); // ['red', 'green', 'yellow'] console.log(colors); // ['red', 'blue', 'green', 'yellow'] - original unchanged // Find closest item (useful for keyboard navigation or selection) const tabs = ['home', 'profile', 'settings', 'logout']; const currentTab = 'settings'; const nextTab = closestItem(tabs, currentTab); console.log(nextTab); // 'logout' // At the end, returns second-to-last const lastTab = 'logout'; const fallbackTab = closestItem(tabs, lastTab); console.log(fallbackTab); // 'settings' // Not found, returns first item const missingTab = 'admin'; const defaultTab = closestItem(tabs, missingTab); console.log(defaultTab); // 'home' // Practical usage in UI component function TabNavigation({ tabs, activeTab, onTabChange }) { const handleTabClose = (tabToClose) => { const updatedTabs = removeItem(tabs, tabToClose); if (activeTab === tabToClose) { // Switch to closest tab when closing active tab const newActiveTab = closestItem(tabs, tabToClose); onTabChange(newActiveTab); } return updatedTabs; }; return (
{tabs.map(tab => ( ))}
); } ``` -------------------------------- ### Define Credit Card Value Interface in TypeScript Source: https://github.com/hasanharman/form-builder/blob/main/components/ui/credit-card.md This TypeScript interface defines the structure for the credit card data. It includes fields for cardholder name, card number, expiry date, CVV, and a label for the CVV field, which can be either 'CCV' or 'CVC'. ```typescript interface CreditCardValue { cardholderName: string cardNumber: string expiryMonth: string expiryYear: string cvv: string cvvLabel: 'CCV' | 'CVC' } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.