### Install @cyca/utils Package Source: https://github.com/cvpcasada/utils/blob/main/readme.md Instructions for installing the @cyca/utils package using npm, pnpm, or bun. ```bash npm install @cyca/utils # or pnpm add @cyca/utils # or bun add @cyca/utils ``` -------------------------------- ### Prepend Protocol to URL with prependHttp Source: https://github.com/cvpcasada/utils/blob/main/readme.md Ensures a URL string starts with 'http://' or 'https://'. If no protocol is present, it prepends 'http://' by default, or 'https://' if specified. ```typescript import { prependHttp } from '@cyca/utils' prependHttp('example.com') // 'http://example.com' prependHttp('example.com', { https: true }) // 'https://example.com' ``` -------------------------------- ### Jotai Atom Initialization Outside React Source: https://context7.com/cvpcasada/utils/llms.txt Initializes Jotai atoms outside React components, providing access to get, set, and store functions. The `init` utility allows setting initial values, subscribing to external events, and performing periodic updates. It returns a cleanup function to unregister listeners and clear intervals. ```typescript import { atom } from 'jotai'; import { init } from '@cyca/utils/jotai'; const countAtom = atom(0); const userAtom = atom(null); // Initialize state on app start const cleanup = init((get, set, store) => { // Set initial values set(countAtom, 100); // Subscribe to external events const unsubscribe = externalAPI.subscribe((user) => { set(userAtom, user); }); // Periodic updates const interval = setInterval(() => { const current = get(countAtom); set(countAtom, current + 1); }, 60000); // Return cleanup function return () => { unsubscribe(); clearInterval(interval); }; }); // Later, when app unmounts cleanup?.(); ``` -------------------------------- ### Get Image Dimensions from URL with getUrlImageSize Source: https://github.com/cvpcasada/utils/blob/main/readme.md Fetches an image from a given URL and returns its dimensions (width and height). This is an asynchronous operation. ```typescript import { getUrlImageSize } from '@cyca/utils' const { width, height } = await getUrlImageSize('https://example.com/image.jpg') ``` -------------------------------- ### Get Image Dimensions from URL in TypeScript Source: https://context7.com/cvpcasada/utils/llms.txt Asynchronously loads an image from a given URL and returns its natural width and height. This function is useful for validating image sizes or aspect ratios before displaying them. ```typescript import { getUrlImageSize } from '@cyca/utils'; async function validateImageSize(url: string) { try { const { width, height } = await getUrlImageSize(url); if (width > 1920 || height > 1080) { console.log('Image is too large!'); return false; } const aspectRatio = width / height; console.log(`Image: ${width}x${height}, ratio: ${aspectRatio.toFixed(2)}`); return true; } catch (error) { console.error('Failed to load image:', error); return false; } } ``` -------------------------------- ### Use Effect Once - React Hook Source: https://github.com/cvpcasada/utils/blob/main/readme.md Ensures a React effect function runs only a single time, even when React's Strict Mode would normally cause it to run twice during development. This hook is ideal for setup or initialization logic that should only occur once per component lifecycle. ```typescript import { useEffectOnce } from '@cyca/utils/react' useEffectOnce(() => { console.log('Runs only once') }) ``` -------------------------------- ### Mitt: mitt for event emitter creation Source: https://github.com/cvpcasada/utils/blob/main/readme.md Creates a lightweight event emitter instance. It allows defining typed events and subscribing to them using `on`, emitting them with `emit`, and unsubscribing with `off`. ```typescript import { mitt } from '@cyca/utils/mitt' type Events = { 'user:login': { id: string } 'user:logout': void } const emitter = mitt() emitter.on('user:login', (data) => { console.log('User logged in:', data.id) }) emitter.emit('user:login', { id: '123' }) ``` -------------------------------- ### Jotai: init for store initialization Source: https://github.com/cvpcasada/utils/blob/main/readme.md Initializes state or side effects when a Jotai store is created. It takes an initialization function that can set atom values and return a cleanup function. An optional store can be provided. ```typescript import { init } from '@cyca/utils/jotai' const cleanup = init((get, set, store) => { // Initialize something set(someAtom, initialValue) // Return cleanup function return () => { // Cleanup } }) ``` -------------------------------- ### Prepend HTTP/HTTPS to URLs with TypeScript Source: https://context7.com/cvpcasada/utils/llms.txt Automatically prepends 'http://' or 'https://' to URLs lacking a protocol. It handles localhost and paths appropriately, with an option to force HTTP. Existing protocols and relative paths are preserved. ```typescript import { prependHttp } from '@cyca/utils'; // Default behavior (HTTPS) console.log(prependHttp('example.com')); // 'https://example.com' console.log(prependHttp('google.com/search')); // 'https://google.com/search' // Use HTTP instead console.log(prependHttp('example.com', { https: false })); // 'http://example.com' // Preserves existing protocols and paths console.log(prependHttp('https://example.com')); // 'https://example.com' console.log(prependHttp('/relative/path')); // '/relative/path' console.log(prependHttp('./local/file')); // './local/file' console.log(prependHttp('localhost:3000')); // 'localhost:3000' ``` -------------------------------- ### Subscribe to Media Queries with useMediaQuery Hook (TypeScript) Source: https://context7.com/cvpcasada/utils/llms.txt The `useMediaQuery` hook from '@cyca/utils/react' allows components to subscribe to the matching status of CSS media queries. It returns a boolean indicating whether the query is currently active, enabling responsive UI adjustments based on screen size, orientation, or other media features. ```typescript import { useMediaQuery } from '@cyca/utils/react'; function ResponsiveComponent() { const isMobile = useMediaQuery('(max-width: 768px)'); const isDark = useMediaQuery('(prefers-color-scheme: dark)'); const isPortrait = useMediaQuery('(orientation: portrait)'); return (

Device: {isMobile ? 'Mobile' : 'Desktop'}

Theme: {isDark ? 'Dark' : 'Light'}

Orientation: {isPortrait ? 'Portrait' : 'Landscape'}

); } ``` -------------------------------- ### useAtomCallback: Stable Callbacks for Jotai Atom Interactions Source: https://context7.com/cvpcasada/utils/llms.txt useAtomCallback provides a way to create stable callback functions that can safely read and write Jotai atoms. These callbacks have a consistent identity across re-renders, making them ideal for use in effects, event handlers, or when passing callbacks to child components. ```typescript import { atom } from 'jotai'; import { useAtomCallback } from '@cyca/utils/jotai'; const countAtom = atom(0); const userAtom = atom({ name: 'Alice', points: 0 }); function GameComponent() { const awardPoints = useAtomCallback((get, set, amount: number) => { const currentCount = get(countAtom); const user = get(userAtom); set(countAtom, currentCount + amount); set(userAtom, { ...user, points: user.points + amount }); console.log(`Awarded ${amount} points to ${user.name}`); }); // Stable reference - won't cause effect to re-run useEffect(() => { const interval = setInterval(() => { awardPoints(10); }, 5000); return () => clearInterval(interval); }, [awardPoints]); return ; } ``` -------------------------------- ### Jotai: useAtomCallback with stable identity Source: https://github.com/cvpcasada/utils/blob/main/readme.md A custom hook for Jotai that provides a stable callback identity, preventing unnecessary re-renders. It takes a callback function and optional Jotai store options as arguments. ```typescript import { useAtomCallback } from '@cyca/utils/jotai' const handleClick = useAtomCallback((get, set) => { const value = get(someAtom) set(anotherAtom, value + 1) }) ``` -------------------------------- ### Track Async Callback State with useAsyncCallback (TypeScript) Source: https://context7.com/cvpcasada/utils/llms.txt The `useAsyncCallback` hook from '@cyca/utils/react' simplifies the management of asynchronous operations by providing state tracking for pending, success, and error conditions. It returns a `wrapCallback` function to wrap any async function, making it easy to display loading states and handle results or errors. ```typescript import { useAsyncCallback } from '@cyca/utils/react'; function UserProfile({ userId }: { userId: string }) { const [{ pending, success, error }, wrapCallback] = useAsyncCallback(); const fetchUser = wrapCallback(async (id: string) => { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error('Failed to fetch user'); return response.json(); }); return (
{success &&

User loaded successfully!

} {error &&

Error: {error.message}

}
); } ``` -------------------------------- ### Delay Execution with Promise in TypeScript Source: https://context7.com/cvpcasada/utils/llms.txt Provides a promise-based wrapper around setTimeout for easy integration with async/await syntax. It allows for delays with an optional return value, useful for implementing retry logic or scheduled operations. ```typescript import { delay } from '@cyca/utils'; async function fetchWithRetry(url: string) { try { return await fetch(url); } catch (error) { console.log('Retrying in 2 seconds...'); await delay(2000); return await fetch(url); } } // With return value async function delayedValue() { const result = await delay(1000, { data: 'loaded' }); console.log(result); // { data: 'loaded' } } ``` -------------------------------- ### React: useClientLayoutEffect for SSR compatibility Source: https://github.com/cvpcasada/utils/blob/main/readme.md A hook that uses `useEffect` during SSR and `useLayoutEffect` in the browser. This pattern helps avoid console warnings related to inconsistent rendering between server and client. ```typescript import { useClientLayoutEffect } from '@cyca/utils/react' useClientLayoutEffect(() => { // Safe to use in SSR }, []) ``` -------------------------------- ### React: useConstant for single initialization Source: https://github.com/cvpcasada/utils/blob/main/readme.md Creates a value exactly once during the component's lifecycle. Unlike `useMemo`, its initialization is guaranteed, making it suitable for expensive object creation that should not be recomputed. ```typescript import { useConstant } from '@cyca/utils/react' const expensiveObject = useConstant(() => createExpensiveObject()) ``` -------------------------------- ### Jotai: withSnapshotHistory for undo/redo Source: https://github.com/cvpcasada/utils/blob/main/readme.md Wraps a Jotai atom to provide undo and redo functionality. It allows committing, undoing, redoing, and resetting the history of the atom's state. An optional limit can be set for the history size. ```typescript import { withSnapshotHistory, COMMIT, UNDO, REDO, RESET } from '@cyca/utils/jotai' const countAtom = atom(0) const historyAtom = withSnapshotHistory(countAtom, 10) // In a component: const [{ value, previous, canUndo, canRedo }, dispatch] = useAtom(historyAtom) // Update the value (doesn't create history entry) dispatch(5) // Commit to history dispatch(COMMIT) // Undo/redo dispatch(UNDO) dispatch(REDO) // Reset history dispatch(RESET) ``` -------------------------------- ### React: useMediaQuery for media query matching Source: https://github.com/cvpcasada/utils/blob/main/readme.md A React hook that matches media queries. It returns a boolean indicating whether the query is currently matched. Returns `undefined` during Server-Side Rendering (SSR). ```typescript import { useMediaQuery } from '@cyca/utils/react' const isMobile = useMediaQuery('(max-width: 768px)') ``` -------------------------------- ### Base64 Encode Strings in TypeScript Source: https://context7.com/cvpcasada/utils/llms.txt Offers cross-environment base64 encoding that functions seamlessly in both Node.js and browser environments. This utility is helpful for encoding data, such as credentials for authentication headers. ```typescript import { toBase64 } from '@cyca/utils'; // Works in both browser and Node.js const encoded = toBase64('Hello, World!'); console.log(encoded); // 'SGVsbG8sIFdvcmxkIQ==' // Useful for encoding credentials const credentials = toBase64('username:password'); const headers = { Authorization: `Basic ${credentials}` }; ``` -------------------------------- ### Server-Side Validation with invariantResponse Source: https://github.com/cvpcasada/utils/blob/main/readme.md Throws a 400 Response if a condition is falsey, making it suitable for server-side validation logic. Allows for custom messages and response init options. ```typescript import { invariantResponse } from '@cyca/utils' invariantResponse(typeof value === 'string', 'value must be a string') ``` -------------------------------- ### Bind Multiple Event Listeners to Mitt Emitter (TypeScript) Source: https://context7.com/cvpcasada/utils/llms.txt Binds multiple event listeners to a 'mitt' emitter instance simultaneously. It returns a single function that, when executed, will unbind all the listeners that were bound. This simplifies the management of multiple event subscriptions. It takes the emitter instance and an object mapping event names to their respective callbacks. ```typescript import { mitt, bindAll } from '@cyca/utils/mitt'; type Events = { connect: void; disconnect: void; message: { text: string; from: string }; error: Error; }; const emitter = mitt(); // Bind multiple events const unbindAll = bindAll(emitter, { connect: () => console.log('Connected'), disconnect: () => console.log('Disconnected'), message: (msg) => console.log(`${msg.from}: ${msg.text}`), error: (err) => console.error('Error:', err.message) }); // Use the emitteremitter.emit('connect'); emitter.emit('message', { text: 'Hello!', from: 'Alice' }); // Clean up all listeners at once unbindAll(); ``` -------------------------------- ### Highlight Words in Text (TypeScript) Source: https://context7.com/cvpcasada/utils/llms.txt Highlights specified words within a text string. Supports default HTML mark tags, case-insensitive matching, and custom rendering functions for frameworks like React. It takes the text, words to highlight, and an optional options object. ```typescript import { higlightWords } from '@cyca/utils'; // Default behavior (HTML marks) const text = 'The quick brown fox jumps over the lazy dog'; const highlighted = higlightWords(text, 'quick lazy'); console.log(highlighted); // 'The quick brown fox jumps over the lazy dog' // Case insensitive const result = higlightWords(text, 'QUICK', { caseSensitive: false }); // Custom highlighting for React import type { ReactNode } from 'react'; const reactHighlight = higlightWords( text, 'fox', { mark: (part, matched) => matched ? {part} : part, append: (acc, part) => [...acc, part] } ); // Returns: ['The quick brown ', fox, ' jumps over the lazy dog'] ``` -------------------------------- ### String to Base64 Encoding with toBase64 Source: https://github.com/cvpcasada/utils/blob/main/readme.md Converts a given string into its Base64 encoded representation. ```typescript import { toBase64 } from '@cyca/utils' const encoded = toBase64('hello world') ``` -------------------------------- ### Highlight Search Terms in Text with higlightWords Source: https://github.com/cvpcasada/utils/blob/main/readme.md Highlights occurrences of a search term within a larger text. Supports case-insensitive matching and custom rendering of matched parts. ```typescript import { higlightWords } from '@cyca/utils' const result = higlightWords('Hello world', 'world', { caseSensitive: false, mark: (part, matched) => matched ? `${part}` : part }) ``` -------------------------------- ### useSelectAtom: Efficiently Select Derived State from Jotai Atoms Source: https://context7.com/cvpcasada/utils/llms.txt useSelectAtom optimizes Jotai state selection by allowing components to subscribe only to specific derived values from an atom. This prevents unnecessary re-renders when other parts of the atom's state change, improving performance. ```typescript import { atom } from 'jotai'; import { useSelectAtom } from '@cyca/utils/jotai'; const userAtom = atom({ id: '123', name: 'Alice', email: 'alice@example.com', preferences: { theme: 'dark', language: 'en' } }); function UserName() { // Only re-renders when name changes, not other fields const name = useSelectAtom(userAtom, (user) => user.name); return {name}; } function ThemeDisplay() { // Only re-renders when theme changes const theme = useSelectAtom(userAtom, (user) => user.preferences.theme); return
Theme: {theme}
; } ``` -------------------------------- ### Jotai Atom Undo/Redo with Snapshot History Source: https://context7.com/cvpcasada/utils/llms.txt Wraps a Jotai atom with undo/redo functionality and manual commit-based history tracking. It allows controlling history through dispatch actions like COMMIT, UNDO, REDO, and RESET. The maximum history entries can be configured, and it's useful for managing form states or canvas drawings. ```typescript import { atom } from 'jotai'; import { useAtom } from 'jotai'; import { withSnapshotHistory, UNDO, REDO, COMMIT, RESET } from '@cyca/utils/jotai'; const textAtom = atom(''); const textHistoryAtom = withSnapshotHistory(textAtom, 10); // Max 10 history entries function TextEditor() { const [text, setText] = useAtom(textAtom); const [history, dispatch] = useAtom(textHistoryAtom); const handleSave = () => { dispatch(COMMIT); // Save current state to history }; return (