Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UI update #69

Merged
merged 20 commits into from
Mar 25, 2025
Merged

UI update #69

merged 20 commits into from
Mar 25, 2025

Conversation

Akshay-Vs
Copy link
Owner

@Akshay-Vs Akshay-Vs commented Mar 25, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new file deletion capability within the file management system.
    • Added new components for image upload and preview, enhancing the product editor experience.
    • Implemented a modal interface for managing variant items, improving user interaction.
  • Refactor

    • Streamlined layout and rendering flows for faster, smoother interactions.
    • Standardized terminology and UI consistency across variant-related components.

Copy link

vercel bot commented Mar 25, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
hwei ❌ Failed (Inspect) Mar 25, 2025 3:19pm

Copy link
Contributor

coderabbitai bot commented Mar 25, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request implements multiple new features and enhancements across the web application. New API endpoints and utilities for file deletion and image uploads are introduced through the UploadThing integration. Several server-side rendering improvements have been added via an asynchronous UTSSR function. The changes also include extensive updates to the product editor components and variant modals—with standardized naming, new form validation using Zod, and dedicated modal stores—along with corrections to imports, configuration files, and type definitions.

Changes

Files Change Summary
apps/web/actions/UTApi.ts
apps/web/app/api/uploadthing/route.ts
apps/web/utils/uploadthing/core.ts
apps/web/utils/uploadthing/uploadthing.ts
Introduced new API functionality: file deletion utility using UploadThing, new route handler with GET/POST methods, upload router configuration, and generated upload components.
apps/web/app/(pages)/layout.tsx
apps/web/app/layout.tsx
Added asynchronous UTSSR function for server-side rendering integration and updated layout rendering structure (e.g. added Suspense wrapper and minor formatting adjustments).
apps/web/components/specific/product-editor/components/editor-preview/preview-category.tsx
apps/web/components/specific/product-editor/components/product-varient/add-variant-item.tsx
apps/web/components/specific/product-editor/components/product-varient/add-variant.tsx
apps/web/components/specific/product-editor/components/product-varient/product-variants.tsx
apps/web/components/specific/product-editor/components/product-varient/variant-items.tsx
apps/web/components/specific/product-editor/product-editor.tsx
Updated product editor components: added new components and interfaces; standardized naming from “varient” to “variant”; revised import paths and included error handling in the preview component.
apps/web/components/specific/product-editor/modals/varient-item-model/form-actions.tsx
apps/web/components/specific/product-editor/modals/varient-item-model/image-input.tsx
apps/web/components/specific/product-editor/modals/varient-item-model/name-input.tsx
apps/web/components/specific/product-editor/modals/varient-item-model/stock-available-input.tsx
apps/web/components/specific/product-editor/modals/varient-item-model/variant-item-modal.tsx
apps/web/stores/modal-store/variant-item-modal-store.ts
apps/web/components/specific/product-editor/hooks/use-varient-form.tsx
apps/web/components/specific/product-editor/schemas/varient-item-schema.ts
Added modal components and form management for variant items, including new Zod schema validation, a custom hook for variant forms, and a dedicated modal store; naming corrections applied.
apps/web/components/shared/image-upload/image-upload-dropzone.tsx
apps/web/components/shared/image-upload/upload-preview.tsx
apps/web/hooks/use-image-upload.ts
Added image upload UI components (dropzone and preview) and introduced a custom hook to manage image upload processes, deletion, and error handling.
apps/web/components/shared/modal/modal-provider.tsx
apps/web/components/shared/modal/variant-modal.tsx
apps/web/types/base-props.ts
apps/web/tailwind.config.ts
apps/web/tsconfig.json
apps/web/package.json
Made shared modal corrections (typo fixes and new modal imports), updated tailwind configuration and tsconfig includes, introduced a new type TBaseLoading, and added new UploadThing dependencies.
apps/web/components/specific/product-editor/components/product-varient/add-varient-item.tsx Removed the redundant component file for adding variant items.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant UTApi
    participant Server
    Caller->>UTApi: call deleteFile(fileUrl)
    UTApi->>UTApi: Validate fileUrl and extract file key
    alt Invalid file key
        UTApi-->>Caller: Return error response ("file URL required" / "invalid file key")
    else Valid file key
        UTApi->>Server: Call deleteFiles(fileKey)
        Server-->>UTApi: Return deletion result
        UTApi->>Caller: Return success or failure response
    end
Loading
sequenceDiagram
    participant User
    participant Dropzone
    participant useImageUpload
    participant UTApi
    User->>Dropzone: Drop image to upload
    Dropzone->>useImageUpload: Trigger upload process
    useImageUpload->>User: onClientUploadComplete(image URL)
    User->>useImageUpload: Request image deletion
    useImageUpload->>UTApi: Call deleteFile(image URL)
    UTApi-->>useImageUpload: Return deletion result
    useImageUpload->>User: Update form state (image removed)
Loading

Poem

I'm a rabbit with a cheerful beat,
Hopping through code with nimble feet.
Uploads, deletions, and variants align,
Each change a carrot so fresh and fine.
With every fix and feature so new,
I nibble on bugs—bye-bye, adieu!
🐰 Happy coding in our garden of view!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a0fe61a and c1e4f46.

📒 Files selected for processing (2)
  • apps/web/components/specific/product-editor/hooks/use-varient-form.tsx (1 hunks)
  • apps/web/stores/modal-store/variant-item-modal-store.ts (1 hunks)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🔭 Outside diff range comments (1)
apps/web/components/specific/product-editor/modals/varient-item-model/variant-item-modal.tsx (1)

1-52: 💡 Verification agent

🧩 Analysis chain

Fix folder path mismatch with filename.

The file is in a folder named "varient-item-model" but the file itself is named "variant-item-modal.tsx", leading to inconsistency. Consider renaming the folder to match the file naming convention.


🏁 Script executed:

#!/bin/bash
# Check folder structure inconsistencies
echo "Current folder structure:"
find apps/web/components/specific/product-editor/modals -type d -name "*varient*" -o -name "*variant*"

Length of output: 328


Folder Naming Inconsistency Detected

The folder name "varient-item-model" is inconsistent with the file name "variant-item-modal.tsx." To maintain consistency and avoid confusion, please rename the folder to "variant-item-modal."

  • Affected Location:
    apps/web/components/specific/product-editor/modals/varient-item-model
🧹 Nitpick comments (26)
apps/web/components/specific/product-editor/modals/varient-item-model/name-input.tsx (1)

1-12: Consider using absolute imports consistently

While the component itself is well-structured, consider using absolute imports (with @/ prefix) for internal project dependencies to improve maintainability.

-import TextInput from '../../../../shared/input/text-input';
+import TextInput from '@/components/shared/input/text-input';
apps/web/components/specific/product-editor/hooks/use-varient-form.tsx (1)

1-17: Typo in naming: "varient" should be "variant"

The hook name useVarientForm and related variables contain a spelling error. "Varient" should be "variant" for correct English spelling and consistency with industry terminology.

-export const useVarientForm = () => {
-	const varientItemModelForm = useForm<z.infer<typeof varientItemSchema>>({
+export const useVariantForm = () => {
+	const variantItemModelForm = useForm<z.infer<typeof varientItemSchema>>({
		resolver: zodResolver(varientItemSchema),
		defaultValues: {
			label: '',
			stock: 0,
			image: undefined,
		},
	});

-	return { varientItemModelForm };
+	return { variantItemModelForm };
};
apps/web/components/specific/product-editor/schemas/varient-item-schema.ts (1)

3-7: Typo in naming: "varient" should be "variant"

The schema name varientItemSchema contains a spelling error. "Varient" should be "variant" for correct English spelling and consistency with industry terminology.

-export const varientItemSchema = z.object({
+export const variantItemSchema = z.object({
	label: z.string().min(1, { message: 'Name is required' }),
	stock: z.number().min(1, { message: 'Stock is required' }),
	image: z.string({ message: 'Image is required in this variant' }),
});
apps/web/components/specific/product-editor/modals/varient-item-model/image-input.tsx (2)

11-11: Consider using absolute imports for better maintainability

Using relative imports with multiple parent directories (../../../../../) is fragile and can break if files are reorganized. Consider using absolute imports for better maintainability.

- import { useImageUpload } from '../../../../../hooks/use-image-upload';
+ import { useImageUpload } from '@/hooks/use-image-upload';

35-35: Avoid spreading the entire form object to components

Spreading the entire form object ({...form}) to the ImageUploadDropzone component may pass unnecessary props and could lead to prop pollution. Consider passing only the required props.

Identify which specific form properties are needed by ImageUploadDropzone and pass only those explicitly:

- {...form}
+ setValue={form.setValue}
+ formState={form.formState}

Or if you need to maintain the current behavior, document why the spread is necessary.

apps/web/utils/uploadthing/uploadting.ts (2)

1-9: Filename typo: "uploadting.ts" should be "uploadthing.ts"

The filename contains a typo. It should be "uploadthing.ts" to match the library name and maintain consistency.

Rename the file from uploadting.ts to uploadthing.ts to correct the spelling.


8-9: Consider adding JSDoc comments for better code documentation

The exported components lack documentation. Adding JSDoc comments would improve code readability and provide better type hints for developers using these components.

+ /**
+  * A button component for file uploads using UploadThing
+  * @see https://docs.uploadthing.com/react/components/upload-button
+  */
export const UploadButton: ReturnType<typeof generateUploadButton<uploadFileRouter>> = generateUploadButton<uploadFileRouter>();
+ /**
+  * A dropzone component for file uploads using UploadThing
+  * @see https://docs.uploadthing.com/react/components/upload-dropzone
+  */
export const UploadDropzone = generateUploadDropzone<uploadFileRouter>();
apps/web/components/specific/product-editor/components/product-varient/add-variant-item.tsx (1)

1-25: Well-structured implementation of the variant item addition button

The implementation of the AddVariantItem component is clean and follows React best practices with proper event handling.

However, I noticed that while the component correctly uses the term "variant" throughout the code, the directory path contains "product-varient" (misspelled). This inconsistency in naming could cause confusion for other developers.

Consider addressing the file path inconsistency by renaming the directory from "product-varient" to "product-variant" to match the component naming convention.

apps/web/components/specific/product-editor/modals/varient-item-model/stock-available-input.tsx (3)

12-34: Missing FormLabel component in the stock input

The component works correctly but doesn't use the FormLabel component from the shadcn/ui library for the label, which might be inconsistent with other form components.

Consider using the FormLabel component for consistency with other form elements:

-				<FormItem>
-					<label>Stock available</label>
+				<FormItem>
+					<FormLabel>Stock available</FormLabel>

Additionally, you would need to import FormLabel from '@hwei/ui/shadcn/form'.


22-27: Consider adding validation for stock input

The stock input allows any number value without validation. For inventory management, it would be helpful to ensure positive values.

If your form schema uses Zod (based on the AI summary about "new form validation using Zod"), ensure your schema includes validation for stock to be a positive number:

// In your schema definition
stock: z.number().min(0, "Stock cannot be negative")

1-36: File path inconsistency with component name

While the component itself correctly uses "stock-available-input", the directory path contains "varient-item-model" (misspelled) instead of "variant-item-modal".

Consider renaming the directory path for consistency with the correct spelling of "variant".

apps/web/tailwind.config.ts (1)

18-20: Proper integration with UploadThing via withUt

The integration of UploadThing with Tailwind configuration is implemented correctly. The withUt wrapper allows UploadThing's styles to be incorporated into the Tailwind configuration.

Consider adding an empty line at the end of the file to follow common file formatting conventions:

 import { withUt } from "uploadthing/tw";

 export default withUt(config)
+
apps/web/components/specific/product-editor/modals/varient-item-model/form-actions.tsx (3)

8-15: Missing semicolon and extra whitespace

There are a few minor syntax and formatting issues in this code block.

Fix the missing semicolon and remove the extra whitespace:

 const FormActions = ({loading}:TBaseLoading) => {
 	const store = useVariantItemModal();
-	const form = useFormContext()
+	const form = useFormContext();
 
 	const handleClose = () => {
 		store.onClose();
 		form.reset()
 	}
-	
+

27-29: Generic button text might not be suitable for all use cases

The "Create Variant" button text may not be appropriate if this modal is reused for editing existing variants.

Consider making the button text dynamic to support both create and edit scenarios:

-			<Button type="submit" disabled={loading} className="h-12 px-4">
-				Create Variant
+			<Button type="submit" disabled={loading} className="h-12 px-4">
+				{isEditing ? 'Update Variant' : 'Create Variant'}
 			</Button>

This would require adding an isEditing prop to the component to determine which text to display.


1-34: File path inconsistency with component functionalities

The directory path contains "varient-item-model" (misspelled) instead of "variant-item-modal", which doesn't align with the correct spelling used in component code.

Consider renaming the directory path to use the correct spelling "variant-item-modal" for consistency with component naming.

apps/web/components/shared/modal/modal-provider.tsx (1)

4-5: Fixed typo in component name and added new variant item modal.

The typo in the import statement has been corrected from 'VarientModal' to 'VariantModal', which improves code consistency. A new import for 'VariantItemModal' has been added to support additional product variant functionality.

However, there appears to be an inconsistency in the import path for VariantItemModal.

The import path contains 'varient-item-model' (with 'varient' spelled incorrectly and using 'model' instead of 'modal') while the imported component is 'VariantItemModal'. Consider updating the folder name to match:

-import VariantItemModal from '@/components/specific/product-editor/modals/varient-item-model/variant-item-modal';
+import VariantItemModal from '@/components/specific/product-editor/modals/variant-item-modal/variant-item-modal';
apps/web/utils/uploadthing/core.ts (1)

17-21: Improve type safety and remove console logs before production.

The upload complete handler has two issues that should be addressed:

  1. Type casting using as any should be avoided
  2. Console logs should be removed in production code

Consider the following improvements:

-.onUploadComplete(async ({ metadata, file }) => {
-  const userId = (metadata as any).userId;
-  console.log("Upload complete for userId:", userId);
-  console.log("file url", file.ufsUrl);
+.onUploadComplete(async ({ metadata, file }) => {
+  // Define a proper type for metadata
+  const { userId } = metadata;
+  // Consider using a logging service or removing logs in production
+  return { success: true, userId, fileUrl: file.ufsUrl };
apps/web/components/shared/image-upload/image-upload-dropzone.tsx (2)

14-28: Fix inconsistent indentation.

The component uses tabs for indentation instead of spaces. It's important to maintain consistent indentation throughout the codebase.

 const ImageUploadDropzone = ({loading, endpoint="productImage", onClientUploadComplete, onUploadError}: ImageUploadDropzoneProps) => {
-	return (
-		<UploadDropzone
-			disabled={loading}
-			endpoint={endpoint}
-			onClientUploadComplete={onClientUploadComplete}
-			onUploadError={onUploadError}
-			appearance={{
-				button:
-					'bg-primary text-primary-foreground hover:bg-primary/90 data-[state=disabled]:bg-primary/70 data-[state=ready]:bg-primary data-[state=readying]:bg-primary/70 data-[state=uploading]:bg-secondary/80 after:bg-secondary focus-within:ring-primary rounded-base',
-				container: 'rounded-[1rem] h-64 w-full',
-			}}
-		/>
-	);
+  return (
+    <UploadDropzone
+      disabled={loading}
+      endpoint={endpoint}
+      onClientUploadComplete={onClientUploadComplete}
+      onUploadError={onUploadError}
+      appearance={{
+        button:
+          'bg-primary text-primary-foreground hover:bg-primary/90 data-[state=disabled]:bg-primary/70 data-[state=ready]:bg-primary data-[state=readying]:bg-primary/70 data-[state=uploading]:bg-secondary/80 after:bg-secondary focus-within:ring-primary rounded-base',
+        container: 'rounded-[1rem] h-64 w-full',
+      }}
+    />
+  );
 };

7-12: Consider adding callback types and additional configuration options.

The interface could benefit from more specific callback type definitions and additional configuration options for the UploadDropzone component.

 interface ImageUploadDropzoneProps {
   loading: boolean;
   endpoint?: string;
-  onClientUploadComplete: (res: ClientUploadedFileData<unknown>[]) => void;
+  onClientUploadComplete: (res: ClientUploadedFileData<{ url: string }>[]) => void;
   onUploadError: (error: UploadThingError) => void;
+  maxFiles?: number;
+  maxSize?: number;
 }
apps/web/components/shared/image-upload/upload-preview.tsx (1)

35-42: Improve accessibility with aria-label.

The delete button uses only an icon without text, which creates an accessibility issue for screen reader users.

 <Button
   variant="destructive"
   size="icon"
   onClick={() => startPending(handleDeleteImage)}
+  aria-label="Delete image"
 >
   <Trash2 size={20} />
 </Button>
apps/web/hooks/use-image-upload.ts (2)

24-39: Image deletion logic needs improvement.

The error handling is good, but there are unnecessary console logs that should be removed in production code.

 const handleDeleteImage = async () => {
   try {
     if (!image) return;
     const res = await deleteFile(image);

     if (res.success)
       return form.setValue(field, '' as PathValue<T, FieldPath<T>>);

-    console.log(res);
+    // Handle failed deletion more gracefully

     return setImageError('Failed to delete image');
   } catch (error) {
-    console.log(error);
     return setImageError('Failed to delete image');
   }
 };

49-52: Memoization dependency array issue.

The dependency array includes the handlers themselves, which could potentially lead to unnecessary rerenders or infinite loops.

 return useMemo(
   () => ({ image, handleDeleteImage, onClientUploadComplete, onUploadError }),
-  [image, handleDeleteImage, onClientUploadComplete, onUploadError]
+  [image] // Only include external dependencies
 );
apps/web/components/specific/product-editor/components/editor-preview/preview-category.tsx (1)

25-32: Enhanced display with title attribute.

The component now includes a title attribute for improved tooltips, but consider using ARIA attributes for better accessibility.

 return (
   <p 
     className="text-lg text-secondary/60 cursor-pointer"
     title={`${displayBrand} / ${displayCategory}`}
+    aria-label={`Product belongs to ${displayBrand} brand and ${displayCategory} category`}
   >
     {displayBrand} / {displayCategory}
   </p>
 );
apps/web/actions/UTApi.ts (3)

23-31: File key extraction using string manipulation.

Your method of extracting the file key from the URL using split().pop() might be brittle if the URL format changes. Consider using a more robust approach with URL parsing.

-    // Extract the file key from the URL
-    const fileKey = fileUrl.split('/').pop();
+    // Extract the file key from the URL using URL parsing
+    let fileKey: string | null = null;
+    try {
+      const url = new URL(fileUrl);
+      fileKey = url.pathname.split('/').pop();
+    } catch (e) {
+      // If URL parsing fails, fall back to simple string split
+      fileKey = fileUrl.split('/').pop();
+    }

33-36: Remove or configure console logging for production.

The console logging statements are useful for development but should be removed or configured to only run in development environments before deploying to production.

-    console.log('Deleting file with key:', fileKey);
-    const res = await utapi.deleteFiles([fileKey]);
-    console.log('Delete response:', res);
+    // Use environment-aware logging
+    if (process.env.NODE_ENV === 'development') {
+      console.log('Deleting file with key:', fileKey);
+    }
+    const res = await utapi.deleteFiles([fileKey]);
+    if (process.env.NODE_ENV === 'development') {
+      console.log('Delete response:', res);
+    }

40-46: Improve error handling and ensure proper cleanup.

The error handling is good, but consider adding more detailed error logging and ensuring proper cleanup of any resources.

  } catch (error) {
-    console.error('Delete error:', error);
+    // Log detailed error information
+    console.error('Failed to delete file:', {
+      fileUrl,
+      fileKey,
+      error: error instanceof Error ? { 
+        message: error.message, 
+        stack: error.stack 
+      } : error
+    });
+    
     return {
       success: false,
       error: error instanceof Error ? error.message : 'Failed to delete file'
     };
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f983a4b and a0fe61a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (32)
  • apps/web/actions/UTApi.ts (1 hunks)
  • apps/web/app/(pages)/layout.tsx (2 hunks)
  • apps/web/app/api/uploadthing/route.ts (1 hunks)
  • apps/web/app/layout.tsx (1 hunks)
  • apps/web/components/shared/image-upload/image-upload-dropzone.tsx (1 hunks)
  • apps/web/components/shared/image-upload/upload-preview.tsx (1 hunks)
  • apps/web/components/shared/modal/modal-provider.tsx (1 hunks)
  • apps/web/components/shared/modal/variant-modal.tsx (2 hunks)
  • apps/web/components/specific/product-editor/components/editor-preview/preview-category.tsx (1 hunks)
  • apps/web/components/specific/product-editor/components/product-varient/add-variant-item.tsx (1 hunks)
  • apps/web/components/specific/product-editor/components/product-varient/add-variant.tsx (2 hunks)
  • apps/web/components/specific/product-editor/components/product-varient/add-varient-item.tsx (0 hunks)
  • apps/web/components/specific/product-editor/components/product-varient/product-variants.tsx (2 hunks)
  • apps/web/components/specific/product-editor/components/product-varient/variant-items.tsx (3 hunks)
  • apps/web/components/specific/product-editor/hooks/use-product-form.tsx (1 hunks)
  • apps/web/components/specific/product-editor/hooks/use-varient-form.tsx (1 hunks)
  • apps/web/components/specific/product-editor/modals/varient-item-model/form-actions.tsx (1 hunks)
  • apps/web/components/specific/product-editor/modals/varient-item-model/image-input.tsx (1 hunks)
  • apps/web/components/specific/product-editor/modals/varient-item-model/name-input.tsx (1 hunks)
  • apps/web/components/specific/product-editor/modals/varient-item-model/stock-available-input.tsx (1 hunks)
  • apps/web/components/specific/product-editor/modals/varient-item-model/variant-item-modal.tsx (1 hunks)
  • apps/web/components/specific/product-editor/product-editor.tsx (1 hunks)
  • apps/web/components/specific/product-editor/schemas/varient-item-schema.ts (1 hunks)
  • apps/web/hooks/use-image-upload.ts (1 hunks)
  • apps/web/next.config.js (1 hunks)
  • apps/web/package.json (2 hunks)
  • apps/web/stores/modal-store/variant-item-modal-store.ts (1 hunks)
  • apps/web/tailwind.config.ts (1 hunks)
  • apps/web/tsconfig.json (0 hunks)
  • apps/web/types/base-props.ts (1 hunks)
  • apps/web/utils/uploadthing/core.ts (1 hunks)
  • apps/web/utils/uploadthing/uploadting.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • apps/web/tsconfig.json
  • apps/web/components/specific/product-editor/components/product-varient/add-varient-item.tsx
🧰 Additional context used
🧬 Code Definitions (4)
apps/web/components/specific/product-editor/modals/varient-item-model/image-input.tsx (1)
apps/web/hooks/use-image-upload.ts (1)
  • useImageUpload (11-53)
apps/web/components/specific/product-editor/components/product-varient/add-variant.tsx (1)
apps/web/stores/modal-store/variant-modal-store.ts (1)
  • useVariantModal (5-5)
apps/web/components/specific/product-editor/components/product-varient/add-variant-item.tsx (1)
apps/web/stores/modal-store/variant-item-modal-store.ts (1)
  • useVariantItemModal (5-5)
apps/web/components/specific/product-editor/modals/varient-item-model/variant-item-modal.tsx (1)
apps/web/components/specific/product-editor/hooks/use-varient-form.tsx (1)
  • useVarientForm (6-17)
🔇 Additional comments (39)
apps/web/components/specific/product-editor/hooks/use-product-form.tsx (1)

17-17: LGTM - Added brand field to product form defaults

The addition of the brand field with an empty string default value is consistent with the pattern used for other string fields in the form.

apps/web/app/layout.tsx (1)

42-42: LGTM - Formatting improvement

This whitespace change slightly improves readability of the component structure.

apps/web/app/api/uploadthing/route.ts (1)

1-7: LGTM - Well-implemented UploadThing route handler

The implementation correctly sets up both GET and POST handlers using the UploadThing integration pattern. This provides the necessary API endpoints for file uploads.

apps/web/types/base-props.ts (2)

5-5: LGTM - Code formatting improvement

Moving the closing brace to a new line improves readability and is consistent with standard formatting practices.


7-9: LGTM - Useful loading state type

The new TBaseLoading type provides better type safety for components that need to manage loading states, which is important for components like upload interfaces mentioned in this PR.

apps/web/stores/modal-store/variant-item-modal-store.ts (1)

3-5: LGTM: Good implementation of modal store

The modal store implementation follows the project's pattern for creating reusable modal stores using Zustand, which promotes consistency across the application.

apps/web/components/shared/modal/variant-modal.tsx (2)

4-4: LGTM: Path spelling correction

Fixed import path from "varient-modal-store" to "variant-modal-store", ensuring consistent naming across the project.


36-43: LGTM: Added form reset on submission

Adding form.reset() after form submission is a good practice that improves user experience by clearing the form when the modal is closed.

apps/web/package.json (1)

17-17: LGTM: Addition of UploadThing dependencies

The addition of UploadThing dependencies is appropriate for implementing the file upload functionality described in the PR summary.

Also applies to: 29-29

apps/web/components/specific/product-editor/modals/varient-item-model/name-input.tsx (2)

13-36: LGTM: Well-structured form component

The component is well-implemented with proper form control integration, loading state handling, and validation messages.


1-39:

❌ Incorrect review comment

Directory naming inconsistency

This file is located in a directory named "varient-item-model" (with "varient" instead of "variant"), which is inconsistent with the spelling used elsewhere in the project. Consider renaming the directory to maintain consistency.


🏁 Script executed:

#!/bin/bash
# Check for inconsistencies in directory naming between "variant" and "varient"
echo "Checking directory naming inconsistencies..."
find . -type d -name "*varient*" | sort
find . -type d -name "*variant*" | sort

Length of output: 327


Directory Naming is Consistent Across the Project

After running the verification, we found that both directories in question use “varient” (e.g., ./apps/web/components/specific/product-editor/components/product-varient and ./apps/web/components/specific/product-editor/modals/varient-item-model). No directories or other project references are using the spelling “variant.” Therefore, the naming is consistent as implemented. If a change toward standard English spelling is desired, it should be applied uniformly across the entire project.

Likely an incorrect or invalid review comment.

apps/web/components/specific/product-editor/modals/varient-item-model/image-input.tsx (1)

15-45: LGTM with minor suggestions

The component correctly implements image upload functionality, conditionally rendering either a preview or an upload dropzone based on whether an image exists. It properly integrates with form context and the image upload hook.

apps/web/app/(pages)/layout.tsx (4)

1-5: Updated imports correctly support new UploadThing SSR integration.

The imports have been properly updated to support the UploadThing server-side rendering functionality, including the necessary components from the UploadThing library and Next.js server.


8-9: Relative import path for uploadFileRouter is correctly specified.

The import path for uploadFileRouter is properly specified as a relative path that matches the location of the core.ts file in the project structure.


10-14: UTSSR function implementation correctly follows UploadThing's SSR pattern.

This async function properly establishes a connection using await connection() and returns the NextSSRPlugin with the correct router configuration extracted from uploadFileRouter.


25-30: Proper implementation of Suspense boundary for async UploadThing component.

The UTSSR component is correctly wrapped in a Suspense boundary, which is essential for handling the asynchronous nature of the server-side rendering process. This approach ensures that the layout can continue rendering while the UploadThing configuration is being loaded.

apps/web/next.config.js (4)

10-11: Quote style updated for consistency.

Single quotes are now used consistently for string values in the configuration object.


18-28: Remote patterns correctly updated to support UploadThing domains.

The configuration now properly includes the necessary domains for UploadThing's file storage: 'utfs.sh' and '*.utfs.sh'. This ensures images from these domains can be displayed in the application.


29-33: Additional wildcard domain pattern for UFS hosting.

The pattern for '*.ufs.sh' provides support for the alternate domain naming used by the UploadThing service, ensuring comprehensive coverage of potential image sources.


39-40: Consistent formatting in the remote patterns configuration.

The closing brackets and commas follow a consistent formatting pattern throughout the configuration object.

apps/web/components/shared/modal/modal-provider.tsx (1)

11-12: Added VariantItemModal to component tree.

The component is now correctly rendering both VariantModal (with fixed spelling) and the new VariantItemModal, enhancing the product variant editing capabilities.

apps/web/utils/uploadthing/core.ts (3)

1-7: Well-structured UploadThing initialization with clear constants.

The implementation properly initializes the UploadThing instance and defines clear constants for maximum file size and count, which enhances maintainability.


8-12: Correctly configured product image upload endpoint.

The uploadFileRouter is properly set up with appropriate constraints for product images, limiting file size to 4MB and allowing only one file per upload.


22-24: Proper type export using satisfies pattern.

The router is correctly typed using the satisfies FileRouter pattern, and the type is properly exported. This ensures type safety when using the router throughout the application.

apps/web/components/specific/product-editor/components/product-varient/product-variants.tsx (3)

2-4: Spelling correction and import path update.

The changes correctly standardize the naming convention by replacing "Varient" with "Variant" in component names and import paths, while also updating the EditorCard import path.


13-13: Component name corrected.

Properly updated to use the renamed AddVariant component, maintaining consistency with the import statement.


18-18: Component name corrected.

Properly updated to use the renamed VariantItems component, maintaining consistency with the import statement.

apps/web/components/specific/product-editor/components/product-varient/variant-items.tsx (4)

6-6: Spelling correction in import statement.

The import path and component name have been updated from "Varient" to "Variant", maintaining naming consistency.


27-27: Function name corrected.

The function name has been standardized from VarientItems to VariantItems, which aligns with the export statement and the component usage throughout the codebase.


48-48: Component name corrected.

Properly updated to use the renamed AddVariantItem component, maintaining consistency with the import statement.


53-53: Export name corrected.

The export statement has been updated to match the new function name, ensuring consistency.

apps/web/hooks/use-image-upload.ts (2)

1-10: New hook imports and dependencies.

The imports look good, bringing in necessary utilities for file operations, toast notifications, React hooks, and form types.


11-16: Well-typed hook signature with form field watching.

The hook is generically typed to work with any form values, accepting a form object and field path as parameters.

apps/web/components/specific/product-editor/components/editor-preview/preview-category.tsx (3)

3-6: Good addition of type interface.

The ProductFormValues interface properly defines the structure for form values, improving type safety.


8-16: Improved form handling with error state.

The component now correctly extracts both watched values and form errors, along with properly formatting display values.


17-23: Added error handling and display.

Good implementation of error handling logic to show validation errors to the user.

apps/web/components/specific/product-editor/product-editor.tsx (2)

6-10: Import paths have been updated for better organization.

The import paths have been systematically reorganized to improve the project structure, moving from a flat structure to a more hierarchical one with specific directories for editor fields and hooks. This improves code organization and maintainability.

Also applies to: 12-12


7-7:

✅ Verification successful

Verify hook import path compatibility.

The hook import path has changed significantly, moving from global hooks (@/hooks/use-product-form) to component-specific hooks (@/components/specific/product-editor/hooks/use-product-form). Ensure that this new hook properly implements the same interface, particularly considering the AI summary mentioned a new brand property.


🏁 Script executed:

#!/bin/bash
# Check if the new hook properly implements the expected interface
echo "Checking the implementation of the new hook..."
cat $(fd "use-product-form.tsx" --type f)

Length of output: 732


Hook Implementation and Import Path Verified

The new hook at apps/web/components/specific/product-editor/hooks/use-product-form.tsx correctly implements the expected interface, including the new brand property in its default values. The change from the global hook import path to the component-specific path is valid, and no further modifications are required.

apps/web/actions/UTApi.ts (1)

1-6: Server action implementation with UploadThing API integration.

You've correctly implemented a server action with the 'use server' directive and initialized the UploadThing API with an environment token. This follows best practices for Next.js server actions.

However, ensure that the UPLOADTHING_TOKEN environment variable is properly set in all environments (development, staging, production).

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…form.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@Akshay-Vs Akshay-Vs merged commit b92e11e into main Mar 25, 2025
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant