Skip to content

Fix UploadDemo dropped file validation - #175

Open
shazzar00ni wants to merge 4 commits into
mainfrom
feature/upload-demo-drop-validation
Open

Fix UploadDemo dropped file validation#175
shazzar00ni wants to merge 4 commits into
mainfrom
feature/upload-demo-drop-validation

Conversation

@shazzar00ni

Copy link
Copy Markdown
Owner

Summary

  • Use FileList.item(0) in UploadDemo drop handling so the dropped file is nullable and the unnecessary truthy conditional finding is resolved.
  • Update the UploadDemo drop tests to mock the FileList item API used by browsers.

Acceptance Criteria

  • Dropping .md and .mdx files remains accepted.
  • Non-Markdown files remain rejected.
  • Click-to-select behavior remains unchanged.
  • The scanner finding for the always-truthy droppedFile guard is addressed.

Testing

  • npm run lint
  • npm run typecheck
  • npm run test:run -- src/components/UploadDemo.test.tsx
  • npm run build

How to Test Locally

  1. Check out feature/upload-demo-drop-validation.
  2. Run the validation commands above.
  3. Optionally start the app and drag/drop Markdown and non-Markdown files in the UploadDemo hero demo.

Copilot AI review requested due to automatic review settings May 5, 2026 01:16

@infinitcode-ai infinitcode-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

The change replaces e.dataTransfer.files[0] with e.dataTransfer.files.item(0) for accessing the first dropped file. This is functionally equivalent and improves code consistency with the FileList API. No bugs or security issues are introduced.

Review Verdict: ✅ Review Passed
The change is correct and follows best practices for accessing FileList items.

Changes

File Path Changes Detected
src/components/UploadDemo.tsx • Changed e.dataTransfer.files[0] to e.dataTransfer.files.item(0) for accessing the first dropped file.

Code Style & Consistency

All identifiers follow project casing conventions.

Hot Take

"This diff is so minimal it's practically a haiku. Changing bracket notation to .item() is like swapping your left sock for your right sock—technically different, but nobody will notice."

Example Commands:

@infinitcodeai review          Trigger an instant AI PR review.
@infinitcodeai {prompt}        Ask anything about your codebase.

Note: For additional settings, navigate to Infinitcode AI.

About

Automated review powered by Infinitcode AI
Report generated at 5/5/2026, 1:17:32 AM

@vercel

vercel Bot commented May 5, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
docugen Ready Ready Preview, Comment May 9, 2026 9:28am

@coderabbitai

coderabbitai Bot commented May 5, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved file upload compatibility across different browsers.
  • Tests

    • Enhanced test utilities for file handling scenarios.
  • Documentation

    • Added developer documentation for internal functions.

Walkthrough

Updates replace array-style File access with the FileList API in the UploadDemo component and align tests to mock a FileList. Several components receive JSDoc comments; CI workflow shows no functional changes.

Changes

Upload handling, tests, and docs

Layer / File(s) Summary
Core Implementation
src/components/UploadDemo.tsx
handleDrop now reads the first file with e.dataTransfer.files.item(0) instead of e.dataTransfer.files[0]; validation and upload behavior unchanged.
Test Infrastructure & Cases
src/components/UploadDemo.test.tsx
Adds createFileList(file) helper returning a FileList-like object (length, item(index)) and uses it for the drop-event dataTransfer.files in both acceptance and rejection tests.
Documentation / Comments
src/components/CookieConsent.tsx, src/components/ShareButtons.tsx
Adds JSDoc blocks: getInitialConsentState() behaviour (localStorage semantics) and handleCopyLink clipboard behavior/error logging.
CI Config (no-op)
.github/workflows/ci.yml
No observable functional changes to CI workflow permissions or jobs in the provided hunks.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

A dropped file found its proper place,
item(0) now greets the browser's face.
Tests mirror what real events send,
Comments clarify, CI stays zen. 📄✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix UploadDemo dropped file validation' directly matches the main change in the changeset—updating UploadDemo's drop handling to use FileList.item(0) API and fixing the file validation logic.
Description check ✅ Passed The description clearly relates to the changeset, outlining the specific changes to UploadDemo's file handling, test updates, acceptance criteria, and testing instructions that align with the modified files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/upload-demo-drop-validation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codacy-production

codacy-production Bot commented May 5, 2026

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity · 0 duplication

Metric Results
Complexity 0
Duplication 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes the UploadDemo drag-and-drop file validation by switching from array-style indexing (files[0]) to the browser FileList.item(0) API so the dropped file can be null when absent, resolving the always-truthy guard finding while keeping behavior the same.

Changes:

  • Update drop handling to read the dropped file via e.dataTransfer.files.item(0) (nullable) instead of files[0].
  • Update drag-and-drop tests to mock the FileList.item() API used by browsers.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/components/UploadDemo.tsx Uses FileList.item(0) for dropped file retrieval to make the guard meaningful and align with browser behavior.
src/components/UploadDemo.test.tsx Adds a small FileList-like mock helper and updates drop events to match the new item(0) usage.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@shazzar00ni

Copy link
Copy Markdown
Owner Author

@copilot

Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.

This branch has conflicts that must be resolved
Use the web editor or the command line to resolve conflicts before continuing.

src/components/UploadDemo.tsx

- Keep files.item(0) fix from feature branch in handleDrop
- Keep simulateUpload as useCallback with [simulateUpload] dependency
- Add docstring to getInitialConsentState in CookieConsent.tsx
- Add docstring to handleCopyLink in ShareButtons.tsx

Copilot AI commented May 5, 2026

Copy link
Copy Markdown
Contributor

@copilot
Docstring Coverage | ⚠️ Warning | Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the...

Done in commit 0546fd3:

  1. Merge conflict resolvedsrc/components/UploadDemo.tsx conflict is fixed by keeping the files.item(0) fix from this branch while restoring the useCallback with [simulateUpload] dependency that was added to main.

  2. Docstring coverage — Added the two missing docstrings that were contributing to low coverage:

    • getInitialConsentState in CookieConsent.tsx
    • handleCopyLink in ShareButtons.tsx

    The merge from main also brings in the docstring additions from aa28c66 (for simulateUpload, handleDragOver, etc.), further improving overall coverage.

Also fixed a duplicate permissions key in .github/workflows/ci.yml (commit 9c0bd9f).

@shazzar00ni

Copy link
Copy Markdown
Owner Author

@copilot fix merge conflics to merge with main

- Keep single permissions block in ci.yml (remove duplicate from main)
- Move @eslint/js to devDependencies only (was incorrectly in dependencies)
- Update framer-motion, typescript-eslint, vite, vitest to main's newer versions
- Regenerate package-lock.json

Copilot AI commented May 9, 2026

Copy link
Copy Markdown
Contributor

@copilot fix merge conflics to merge with main

Done in commit 85f9eb5. Three conflicts were resolved:

  • .github/workflows/ci.yml — kept the single permissions block (removed the duplicate reintroduced from main)
  • package.json — moved @eslint/js out of dependencies (it belongs only in devDependencies), and took main's newer versions of framer-motion, typescript-eslint, vite, and vitest
  • package-lock.json — regenerated to match the resolved package.json

All 86 tests still pass and lint is clean.

@sonarqubecloud

sonarqubecloud Bot commented May 9, 2026

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/components/UploadDemo.tsx (1)

82-82: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

Consider using .item(0) for consistency.

For consistency with the fix applied to handleDrop (line 67), consider updating this line to use .item(0) as well:

const selectedFile = e.target.files?.item(0);

This maintains a uniform FileList access pattern throughout the component.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/UploadDemo.tsx` at line 82, Change the FileList access in the
UploadDemo component to use the .item(0) accessor for consistency with the
handleDrop implementation: replace the current usage of e.target.files?.[0] when
setting selectedFile so it reads the first file via e.target.files?.item(0);
update the statement that assigns selectedFile (and any related null/undefined
checks) accordingly to match the handleDrop pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/components/ShareButtons.tsx`:
- Around line 69-72: Update the JSDoc for the function that copies the share URL
to the clipboard (e.g., copyShareUrlToClipboard) to accurately describe that
failures are logged rather than "silent", and change the empty catch to capture
the error (catch (err)) and log the error with context via the existing logger
or console (preserving stack and message) instead of swallowing it; ensure the
catch message mentions the action (copying share URL) and the error object is
included so debugging information is retained.

---

Outside diff comments:
In `@src/components/UploadDemo.tsx`:
- Line 82: Change the FileList access in the UploadDemo component to use the
.item(0) accessor for consistency with the handleDrop implementation: replace
the current usage of e.target.files?.[0] when setting selectedFile so it reads
the first file via e.target.files?.item(0); update the statement that assigns
selectedFile (and any related null/undefined checks) accordingly to match the
handleDrop pattern.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: df1961fd-684b-427f-8ee9-1f2ba1bd0b5f

📥 Commits

Reviewing files that changed from the base of the PR and between 88aa210 and 85f9eb5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • .github/workflows/ci.yml
  • src/components/CookieConsent.tsx
  • src/components/ShareButtons.tsx
  • src/components/UploadDemo.tsx
💤 Files with no reviewable changes (1)
  • .github/workflows/ci.yml
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (3)
src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.{ts,tsx,js,jsx}: Use absolute imports from src/ directory (configured in tsconfig.json)
Organize imports in this order: React → external dependencies → internal components/utils
Use camelCase for variable and function names (e.g., handleSubmit, isLoading)
Use SCREAMING_SNAKE_CASE for constants (e.g., SITE_CONFIG)
Handle runtime errors properly — avoid empty catch blocks; always log the error or re-throw to preserve stack traces

Files:

  • src/components/ShareButtons.tsx
  • src/components/CookieConsent.tsx
  • src/components/UploadDemo.tsx
src/components/**/*.tsx

📄 CodeRabbit inference engine (AGENTS.md)

src/components/**/*.tsx: Use named exports only for components; no default exports
Use PascalCase for component files and component names (e.g., HeroSection, PricingCard)
Use meaningful CSS class names, avoid abbreviations
Use design system colors from tailwind.config.js (e.g., text-dark-100, bg-teal-600)
Dark mode first: The app defaults to dark mode. Use dark: prefix to activate styles when dark mode is active.
Avoid arbitrary Tailwind values ([...]); extend theme instead
Use semantic Tailwind color names: text-dark-300 for secondary text, text-teal-400 for accents
Use consistent spacing scale: 4, 6, 8, 12, 16
Use responsive Tailwind prefixes: sm:, md:, lg: for responsive breakpoints
Use Framer Motion for entrance animations only (fade-in, slide-up); keep duration at 0.5s for most, 0.6s for complex animations
When using Framer Motion, stagger children with delay: index * 0.1
Use inline form validation or simple state for form validation; do not use external validation libraries
Display user-friendly messages for network errors
Place all text copy and site configuration in src/data/content.ts; never hardcode text in components
Use mobile-first responsive design approach
Use React.memo() for expensive components
Optimize images with WebP/AVIF formats

Files:

  • src/components/ShareButtons.tsx
  • src/components/CookieConsent.tsx
  • src/components/UploadDemo.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.{ts,tsx}: No any types - use explicit types or unknown with type guards
Use interface for object types, type for unions/primitives
Use descriptive generic names (T, K, V) or descriptive names (Item, Key) for generics

Files:

  • src/components/ShareButtons.tsx
  • src/components/CookieConsent.tsx
  • src/components/UploadDemo.tsx
🔇 Additional comments (2)
src/components/CookieConsent.tsx (1)

5-10: LGTM!

The JSDoc accurately documents the function's behavior and return semantics. The documentation clearly explains that the consent banner is shown by default when no preference exists.

src/components/UploadDemo.tsx (1)

67-67: LGTM! Correct fix for the always-truthy guard issue.

Using FileList.item(0) properly returns File | null, making the nullability explicit and the guard on line 68 meaningful. This resolves the scanner finding while maintaining identical functionality.

Comment on lines +69 to +72
/**
* Copies the share URL to the clipboard.
* Silently logs an error if the Clipboard API is unavailable.
*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Align JSDoc with behavior and preserve error context in catch.

The new JSDoc is inaccurate: this path is not “silent,” and the catch handles more than just Clipboard API unavailability. Also, catch { ... } drops stack/context, which makes debugging harder.

Suggested update
   /**
    * Copies the share URL to the clipboard.
-   * Silently logs an error if the Clipboard API is unavailable.
+   * Logs a copy failure when writing to the clipboard fails.
    */
   const handleCopyLink = async () => {
     try {
       await navigator.clipboard.writeText(url);
-    } catch {
-      console.error('Failed to copy link');
+    } catch (error) {
+      console.error('Failed to copy link', error);
     }
   };

As per coding guidelines, "Handle runtime errors properly — avoid empty catch blocks; always log the error or re-throw to preserve stack traces".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/ShareButtons.tsx` around lines 69 - 72, Update the JSDoc for
the function that copies the share URL to the clipboard (e.g.,
copyShareUrlToClipboard) to accurately describe that failures are logged rather
than "silent", and change the empty catch to capture the error (catch (err)) and
log the error with context via the existing logger or console (preserving stack
and message) instead of swallowing it; ensure the catch message mentions the
action (copying share URL) and the error object is included so debugging
information is retained.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants