niafix-ui-foundation
v1.0.3
Published
Core utilities for client-side UI, including image handling, offline support, and interactive features to simplify front-end development.
Downloads
321
Maintainers
Readme
Niafix UI Foundation
Niafix UI Foundation is an enterprise-grade React library engineered to simplify complex image operations in modern web applications. It abstracts away the challenges of IndexedDB storage, memory management, image processing, and format conversions, providing a robust foundation for handling media.
🎯 Solved Problems
- Persistence: Prevents data loss on page refreshes by automatically persisting images to IndexedDB.
- Memory Safety: Eliminates memory leaks through automated
ObjectURLlifecycle management. - UX Consistency: Provides a unified, accessible, and touch-responsive cropping interface.
- Performance: Minimizes main-thread blocking and network usage via smart caching and optimization.
📦 Installation
npm install niafix-ui-foundation
# or
yarn add niafix-ui-foundationRequirements: React 18+
⚙️ Configuration
Initialize the library at your application's root to set global policies.
import { Niafix } from 'niafix-ui-foundation';
Niafix.init({
logLevel: process.env.NODE_ENV === 'production' ? 'error' : 'warn',
defaultOptimization: {
quality: 0.85,
outputFormat: 'image/webp',
},
});📖 Usage Scenarios
Here are 20+ common scenarios demonstrating how to leverage the library.
1. Basic Avatar Upload
Allow users to upload and crop a profile picture in a circular frame.
<ImageCropDialog isOpen={true} subject="avatars" aspectRatio={1} circularCrop={true} onClose={closeModal} />2. Product Photo Upload (Fixed Ratio)
Enforce a 4:3 aspect ratio for e-commerce product listings.
<ImageCropDialog isOpen={true} subject="products" aspectRatio={4 / 3} onClose={closeModal} />3. Free-Form Cropping
Let users decide the dimensions of their image (e.g., for blog posts).
<ImageCropDialog disableAspectRatio={true} subject="blog_assets" isOpen={true} onClose={closeModal} />4. Memory-Only Processing
Process an image for immediate use (e.g., sending to API) without saving to IndexedDB.
<ImageCropDialog
disableStorage={true}
subject="temp"
onCropCompleteBlob={(data) => uploadToApi(data.blob)}
isOpen={true}
onClose={closeModal}
/>5. High-Resolution Output
Configure the cropper to output maximum quality PNGs for print or archival.
<ImageCropDialog
subject="archive"
cropOptions={{ quality: 1, outputFormat: 'image/png' }}
isOpen={true}
onClose={closeModal}
/>6. Restricting File Size & Type
Validate inputs to prevent users from uploading unsupported or massive files.
<ImageCropDialog
validationOptions={{
maxSizeMB: 5,
allowedTypes: ['image/jpeg', 'image/webp'],
}}
subject="restricted"
isOpen={true}
onClose={closeModal}
/>7. Customizing Button Text
Translate or adapt the UI text to match your brand voice.
<ImageCropDialog
saveText="Upload Photo"
cancelText="Discard"
uploadText="Drop your photo here"
subject="ui_custom"
isOpen={true}
onClose={closeModal}
/>8. Custom Footer UI
Replace the default buttons with your own component layout.
<ImageCropDialog
renderFooter={({ onSave, onCancel }) => <MyCustomToolbar save={onSave} cancel={onCancel} />}
subject="ui_custom"
isOpen={true}
onClose={closeModal}
/>9. Displaying a Stored Image
Render an image directly from IndexedDB using its ID.
<ImageFromStore storeId="user-123" subject="avatars" />10. Handling Broken Images
Provide a fallback image if the stored file is missing or corrupted.
<ImageFromStore storeId="unknown" subject="avatars" fallbackSrc="/defaults/avatar.png" />11. Listing All Uploaded Images
retrieve a list of all images currently stored in a specific bucket.
const manager = new ImageManager('products');
const allProducts = await manager.getAll();12. Deleting an Image
Remove a specific image from IndexedDB programmatically.
await manager.delete('product-id-555');13. Custom ID & Updates
Save an image with a specific ID or update an existing one.
await manager.processAndStore(file, {
customId: 'my-custom-id',
crop: { quality: 0.9 },
});14. Find by Filename
Locate an image entry using its original filename.
const entry = await manager.getByFileName('photo.jpg');15. Clearing a Storage Bucket
Wipe all data from a specific store (e.g., clearing temporary uploads).
await manager.clear();16. Convert URL to Base64
Prepare an external image for a JSON payload.
const response = await fetch('https://example.com/image.jpg');
const blob = await response.blob();
const base64 = await ConvertToBase64(blob);17. Convert Blob to Base64
Prepare a local user upload for a JSON payload.
const base64 = await ConvertToBase64(fileData);18. Convert Blob to File
Add a filename to a raw Blob for compatibility with FormData.
const file = BlobToFile(blobData, 'upload.jpg');19. Convert URL to File
Fetch a remote resource and wrap it as a standard File object.
const file = await ObjectUrlToFile('https://cdn.site.com/asset.png');20. Batch Validation
Check multiple files against a set of rules before processing.
const report = await ValidateMultipleImages(fileList, { maxSizeMB: 2 });
const validFiles = report.filter((r) => r.isValid);21. Initializing with a File
Open the crop dialog with a file already pre-selected (e.g., from a paste event).
<ImageCropDialog initialFile={pastedFile} isOpen={true} subject="paste" onClose={closeModal} />22. Debugging
Enable detailed logs to troubleshoot image processing pipelines.
Niafix.init({ logLevel: 'debug' });23. General Data Storage with Filtering
Store any JSON data, filter it easily, and let the library manage IDs.
import { ClientStorage } from 'niafix-ui-foundation';
// Create a reusable storage instance
const settingsStore = new ClientStorage('app-db', 'settings');
// Add item (ID is optional, auto-generated if missing)
await settingsStore.add({ theme: 'dark', verified: true });
// Query with filters and sorting
const results = await settingsStore.getAll({
where: { verified: true },
sort: { key: 'createdAt', order: 'desc' },
limit: 5
});🔬 API Reference
ImageCropDialog Output (onCropComplete)
| Field | Type | Description |
| :---------- | :------- | :--------------------------------------- |
| storeId | string | The persistent ID in IndexedDB. |
| objectUrl | string | A temporary URL for immediate rendering. |
ImageCropDialog Output (onCropCompleteBlob)
| Field | Type | Description |
| :------- | :------- | :----------------------------------- |
| blob | Blob | The raw processed image data. |
| file | File | A File object wrapper with metadata. |
| width | number | Final image width in pixels. |
| height | number | Final image height in pixels. |
| size | number | Size in bytes. |
Configuration Options (Niafix.init)
| Option | Type | Default | Description |
| :-------------------- | :-------------------------------------- | :-------- | :--------------------------------------- |
| logLevel | 'none' \| 'error' \| 'warn' \| 'info' | 'error' | Controls console output verbosity. |
| defaultOptimization | CropOptions | {} | Global defaults for crop quality/format. |
| defaultValidation | ValidationOptions | {} | Global defaults for file constraints. |
📄 License
MIT © Niafix
