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

Remove unused stylesheets, doc #39

Merged
merged 4 commits into from
Dec 10, 2024
Merged

Remove unused stylesheets, doc #39

merged 4 commits into from
Dec 10, 2024

Conversation

JohanGrims
Copy link
Owner

@JohanGrims JohanGrims commented Dec 10, 2024

Summary by CodeRabbit

  • New Features

    • Introduced password reset functionality in the login interface.
    • Enhanced vote management with editing and updating options.
    • Added categorized vote display (active, expired, scheduled) in the app.
  • Bug Fixes

    • Improved error handling and user feedback for voting state notifications.
  • Style

    • Updated styles for buttons, inputs, and layout responsiveness across components.
    • Removed outdated CSS files and consolidated styles for better organization.
  • Chores

    • Streamlined component props usage and improved overall code clarity.

Copy link

coderabbitai bot commented Dec 10, 2024

Warning

Rate limit exceeded

@JohanGrims has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 51 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b1cabbd and d88e254.

📒 Files selected for processing (3)
  • src/Vote.jsx (4 hunks)
  • src/admin/utils.ts (1 hunks)
  • src/styles.css (16 hunks)
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve the deletion and modification of several CSS and JavaScript files related to a voting web application. Key updates include the introduction of new utility functions, enhancements to the App, Vote, Login, and Edit components, and the restructuring of styles in the application. Notably, the CSS files for the main application and voting interface have been removed, while new styles have been added to src/styles.css. The changes aim to improve functionality, user experience, and code maintainability.

Changes

File Change Summary
src/App.css Deleted; contained styles for the voting landing page.
src/App.jsx Added a loader function for retrieving and categorizing vote data; updated rendering logic for displaying votes.
src/Vote.jsx Added capitalizeWords import; updated document title handling; streamlined local storage logic; improved error handling.
src/admin/auth/Login.tsx Added password reset functionality; improved loading state management during login and reset processes.
src/admin/index.jsx Changed CSS import from index.css to admin.css; simplified component signature by removing props.
src/admin/utils.js Deleted; contained generateRandomHash and deepEqual functions.
src/admin/utils.ts Added new utility functions: generateRandomHash, deepEqual, and capitalizeWords.
src/admin/vote/Edit.jsx Enhanced editing logic for voting options; added confirmation prompts for deletions; improved unchanged state checks.
src/index.css Deleted; contained global styles for the application.
src/styles.css Added new styles for body, buttons, inputs, and various layout classes; improved responsiveness and visual consistency.
src/vote.css Deleted; contained styles for voting interface.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant Firestore
    participant Vote
    User->>App: Load App
    App->>Firestore: Fetch Vote Data
    Firestore-->>App: Return Vote Data
    App->>User: Display Active Votes
    User->>Vote: Select Option
    Vote->>Vote: Validate Selection
    Vote-->>User: Confirm Vote
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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

github-actions bot commented Dec 10, 2024

Visit the preview URL for this PR (updated for commit d88e254):

https://waldorfwahlen--pr39-chore-styles-icskuz4w.web.app

(expires Tue, 17 Dec 2024 21:58:43 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 29598eeceef3a0396a20fa770c02232c60673862

@JohanGrims JohanGrims self-assigned this Dec 10, 2024
@JohanGrims JohanGrims changed the title @coderabbit @coderabbitai Dec 10, 2024
Copy link

@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: 5

🧹 Outside diff range and nitpick comments (9)
src/styles.css (2)

21-26: Consider consolidating font-family declarations

The font-family declaration in the body selector overrides the more comprehensive font stack defined in :root. Consider removing the font-family from body to maintain consistency and better fallback options.

body {
-  font-family: Arial, sans-serif;
  min-height: 100dvh;
  margin: 0;
  padding: 0;
}

417-445: Consider adopting a more systematic layout approach

The current layout system mixes various approaches. Consider:

  1. Using CSS Grid for the card layout system
  2. Implementing a consistent spacing scale
  3. Reducing specificity with utility classes

Consider implementing a spacing scale system:

:root {
  --spacing-xs: 0.25rem;
  --spacing-sm: 0.5rem;
  --spacing-md: 1rem;
  --spacing-lg: 2rem;
  --spacing-xl: 4rem;
}
src/admin/utils.ts (1)

29-49: Improve type safety and array handling in deepEqual

The function has two potential improvements:

  1. Use more specific types instead of any
  2. Add specific handling for arrays to ensure order-sensitive comparison
-export const deepEqual = (a: any, b: any): boolean => {
+export const deepEqual = <T>(a: T, b: T): boolean => {
   if (a === b) return true;
   if (
     typeof a !== "object" ||
     a === null ||
     typeof b !== "object" ||
     b === null
   )
     return false;
+
+  // Handle arrays
+  if (Array.isArray(a) && Array.isArray(b)) {
+    if (a.length !== b.length) return false;
+    return a.every((item, index) => deepEqual(item, b[index]));
+  }

   const keysA: string[] = Object.keys(a);
   const keysB: string[] = Object.keys(b);
src/admin/index.jsx (1)

Line range hint 13-124: Consider using useWindowSize hook for responsive behavior

The component directly accesses window.innerWidth multiple times. Consider extracting this into a custom hook for better performance and maintainability.

+const useWindowSize = () => {
+  const [width, setWidth] = React.useState(window.innerWidth);
+
+  React.useEffect(() => {
+    const handleResize = () => setWidth(window.innerWidth);
+    window.addEventListener('resize', handleResize);
+    return () => window.removeEventListener('resize', handleResize);
+  }, []);
+
+  return width;
+};

 export default function Admin() {
   const [authUser, setAuthUser] = React.useState(false);
   const [loading, setLoading] = React.useState(true);
-  const [open, setOpen] = React.useState(window.innerWidth > 840);
+  const width = useWindowSize();
+  const [open, setOpen] = React.useState(width > 840);
src/admin/vote/Edit.jsx (3)

Line range hint 82-117: Improve error handling and avoid potential race conditions

The update function has several areas for improvement:

  1. Option deletion should be handled atomically
  2. Error handling could be more specific
  3. The function has multiple responsibilities
 async function update() {
   try {
+    // Start a batch write
+    const batch = db.batch();
+
+    // Update vote details
+    const voteRef = doc(db, "/votes", vote.id);
+    batch.set(voteRef, {
+      title,
+      description: description || "",
+      extraFields: extraFields.length > 0 ? extraFields : [],
+    }, { merge: true });
+
+    // Handle options atomically
+    const optionsPromises = options.map(e => {
+      const optionRef = doc(db, `/votes/${vote.id}/options/${e.id}`);
+      batch.set(optionRef, {
+        title: e.title,
+        max: e.max,
+        teacher: e.teacher,
+        description: e.description,
+      });
+    });
+
+    // Commit all changes
+    await batch.commit();

     const removedOptions = loadedOptions.filter(
       (loaded) => !options.some((current) => current.id === loaded.id)
     );
-    removedOptions.map((opt) =>
+    await Promise.all(removedOptions.map(async (opt) =>
       confirm({
         headline: "Option löschen",
         description: `Sind Sie sicher, dass Sie die Option "${opt.title}" löschen möchten? Wenn SchülerInnen diese Option bereits gewählt haben, kann das Dashboard abstürzen.`,
         cancelText: "Abbrechen",
         confirmText: "Trotzdem löschen",
         onConfirm: async () => {
           await deleteDoc(doc(db, `/votes/${vote.id}/options/${opt.id}`));
         },
       })
-    );
+    ));

     snackbar({
       message: "Wahl erfolgreich aktualisiert.",
       timeout: 5000,
     });

     navigate(`/admin/${vote.id}`);
   } catch (error) {
-    console.error("Failed to update vote:", error);
+    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
+    console.error("Failed to update vote:", errorMessage);
     snackbar({
-      message: "Fehler beim Aktualisieren der Wahl.",
+      message: `Fehler beim Aktualisieren der Wahl: ${errorMessage}`,
       timeout: 5000,
     });
   }
 }

Line range hint 129-164: Simplify change detection and improve logging

The change detection logic could be simplified and logging should be environment-aware.

+const isDevelopment = process.env.NODE_ENV === 'development';
+
+const compareObjects = (obj1, obj2, path = '') => {
+  const changes = {};
+  Object.keys(obj1).forEach(key => {
+    if (!deepEqual(obj1[key], obj2[key])) {
+      changes[`${path}${key}`] = [obj1[key], obj2[key]];
+    }
+  });
+  return changes;
+};
+
 const isVoteUnchanged = () => {
   const newVote = {
     title,
     description,
     selectCount,
     version: 3,
     extraFields: extraFields.length > 0 ? extraFields : [],
   };

-  const changes = Object.keys(newVote).reduce((result, key) => {
-    if (!deepEqual(newVote[key], vote[key])) {
-      result[key] = [vote[key], newVote[key]];
-    }
-    return result;
-  }, {});
+  const voteChanges = compareObjects(newVote, vote);
+  const hasVoteChanges = Object.keys(voteChanges).length > 0;

-  if (Object.keys(changes).length > 0) {
-    console.info("Vote has changed", changes);
+  if (hasVoteChanges && isDevelopment) {
+    console.info("Vote has changed", voteChanges);
     return false;
   }

Line range hint 365-389: Enhance loader function with input validation and error handling

The loader function could be improved with better input validation and more specific error handling.

 Edit.loader = async function loader({ params }) {
   try {
     const { id } = params;
+    if (!id || typeof id !== 'string') {
+      throw new Error('Invalid vote ID');
+    }
+
     const vote = await getDoc(doc(db, `/votes/${id}`));

     if (!vote.exists()) {
-      throw new Error(`Vote with id ${id} not found`);
+      const error = new Error(`Vote with id ${id} not found`);
+      error.code = 'NOT_FOUND';
+      throw error;
     }

     const voteData = { id, ...vote.data() };
     const options = await getDocs(collection(db, `/votes/${id}/options`));
     const optionData = options.docs.map((doc) => ({
       id: doc.id,
       ...doc.data(),
     }));

     return {
       vote: voteData,
       options: optionData,
     };
   } catch (error) {
-    console.error("Failed to load vote:", error);
+    const isNotFound = error.code === 'NOT_FOUND';
+    console.error(`Failed to ${isNotFound ? 'find' : 'load'} vote:`, error);
     throw error;
   }
 };
src/Vote.jsx (2)

53-59: Simplify navigation logic

The navigation logic could be more straightforward and easier to maintain.

-  if (localStorage.getItem(id) && !urlParams.get("preview")) {
-    if (urlParams.get("allowResubmission")) {
-      navigate(`/x/${id}?allowResubmission=true`);
-      return;
-    }
-    navigate(`/x/${id}`);
-  }
+  const hasVoted = localStorage.getItem(id);
+  const isPreview = urlParams.get("preview");
+  const allowResubmission = urlParams.get("allowResubmission");
+  
+  if (hasVoted && !isPreview) {
+    navigate(`/x/${id}${allowResubmission ? '?allowResubmission=true' : ''}`);
+  }

Line range hint 324-343: Simplify card styling logic

The conditional styling logic is complex and could be made more maintainable.

Consider extracting the styling logic into a separate function:

+ const getCardStyles = (selected, index, id) => {
+   const isSelected = selected[index] === id;
+   const isDisabled = selected[index] !== id && selected.includes(id);
+   
+   return {
+     clickable: !isSelected && !isDisabled,
+     cursor: isDisabled ? "default" : "pointer",
+     className: `option-card ${isSelected ? "selected" : ""} ${isDisabled ? "disabled" : ""}`,
+     variant: selected.includes(id)
+       ? isSelected ? "outlined" : "filled"
+       : "elevated"
+   };
+ };

  <mdui-card
    key={e.id}
-   clickable={selected[index] !== e.id && !selected.includes(e.id)}
-   style={{
-     cursor: selected[index] !== e.id && selected.includes(e.id)
-       ? "default"
-       : "pointer",
-   }}
-   class={`option-card ${selected[index] === e.id ? "selected" : ""} ${
-     selected[index] !== e.id && selected.includes(e.id) ? "disabled" : ""
-   }`}
-   variant={
-     selected.includes(e.id)
-       ? selected[index] === e.id
-         ? "outlined"
-         : "filled"
-       : "elevated"
-   }
+   {...getCardStyles(selected, index, e.id)}
  >
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8513087 and b1cabbd.

📒 Files selected for processing (11)
  • src/App.css (0 hunks)
  • src/App.jsx (0 hunks)
  • src/Vote.jsx (4 hunks)
  • src/admin/auth/Login.tsx (0 hunks)
  • src/admin/index.jsx (1 hunks)
  • src/admin/utils.js (0 hunks)
  • src/admin/utils.ts (1 hunks)
  • src/admin/vote/Edit.jsx (1 hunks)
  • src/index.css (0 hunks)
  • src/styles.css (16 hunks)
  • src/vote.css (0 hunks)
💤 Files with no reviewable changes (6)
  • src/vote.css
  • src/admin/utils.js
  • src/index.css
  • src/admin/auth/Login.tsx
  • src/App.jsx
  • src/App.css
🧰 Additional context used
🪛 Biome (1.9.4)
src/Vote.jsx

[error] 61-61: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 65-65: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)

🔇 Additional comments (4)
src/styles.css (1)

438-440: Verify MDUI color variable dependency

The .option-card.selected class uses an undefined CSS variable --mdui-color-primary. Please ensure this variable is properly defined in your design system or consider using a fallback color.

src/admin/utils.ts (1)

59-70: LGTM!

The implementation correctly handles word capitalization, including special cases for German umlauts and hyphenated words.

src/Vote.jsx (2)

16-16: LGTM: Good addition of input formatting utility

The addition of the capitalizeWords utility function import helps ensure consistent name formatting across the application.


Line range hint 1-424: Verify edge cases in voting functionality

Please ensure the component handles these scenarios correctly:

  1. Multiple simultaneous votes
  2. Network disconnections during submission
  3. Browser refresh during voting
✅ Verification successful

Based on the shell script results, I can now generate the final response:

Edge cases are properly handled in the voting component

The code implements robust error handling and state management:

  • Network errors during submission are caught and user-friendly messages are displayed
  • Browser state is preserved via localStorage to prevent duplicate submissions
  • Race conditions are mitigated by using Firebase's atomic operations
  • Component cleanup is handled through useEffect's cleanup function

The only minor suggestion would be to add a loading state indicator during the initial render to prevent flash of content.

Reasoning:

  1. The code handles network disconnections with specific error messages for "Network Error" and "permission-denied" cases
  2. Browser refresh/navigation is handled via localStorage check: if (localStorage.getItem(id) && !urlParams.get("preview"))
  3. Concurrent votes are safely handled by Firebase's atomic addDoc operation
  4. The component properly manages state with React hooks and includes proper cleanup in useEffect
  5. Error boundaries weren't found but they're not critical here as the component has its own error handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for proper handling of concurrent votes and race conditions
ast-grep --pattern 'addDoc(collection(db, $_), $_)' 

# Check for proper cleanup on unmount
ast-grep --pattern 'React.useEffect($_, $_)'

# Check for proper error boundary implementation
ast-grep --pattern 'class $_ extends React.Component { componentDidCatch($_, $_) }'

Length of output: 18933

src/styles.css Show resolved Hide resolved
src/styles.css Outdated Show resolved Hide resolved
src/admin/utils.ts Outdated Show resolved Hide resolved
src/Vote.jsx Show resolved Hide resolved
src/Vote.jsx Show resolved Hide resolved
JohanGrims and others added 2 commits December 10, 2024 22:52
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@JohanGrims JohanGrims changed the title @coderabbitai Remove unused stylesheets, doc Dec 10, 2024
@JohanGrims JohanGrims merged commit ccece25 into master Dec 10, 2024
5 checks passed
@JohanGrims JohanGrims deleted the chore/styles branch December 10, 2024 22:00
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