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

This week imp #519

Merged
merged 14 commits into from
Nov 4, 2024
Merged

This week imp #519

merged 14 commits into from
Nov 4, 2024

Conversation

sajdakabir
Copy link
Member

@sajdakabir sajdakabir commented Nov 1, 2024

What does this PR do?

  • If an item has a due date, it will be displayed in the corresponding week.

Fixes:

  • [ ] #XXX (GitHub issue number)
  • [ ] MAR-XXX (Linear issue number - should be visible at the bottom of the GitHub issue description)

Mandatory Tasks:

  • I have self-reviewed the code (A decent size PR without self-review might be rejected)
  • I pinky swear that my codes gonna work as I have testing every possible scenario.
  • I ignored Coderabbit suggestion because it does not make any sense.
  • I took Coderabbit suggestion under consideration as some of it makes sense.

How should this be tested?

Environment Setup: ( if applicable)

  • Required env variables:
    # Add required env variables here
    

Checklist:

  • My code follows the style guidelines of this project.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have checked if my changes generate no new warnings.
  • I have checked for Build errors.
  • I have checked if my branch is up to date with preview.

Copy link

coderabbitai bot commented Nov 1, 2024

Caution

Review failed

The pull request is closed.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request focus on enhancing the functionality of the getThisWeekItemsByDateRange function in the item.service.js file and introducing new components for managing item rescheduling in the frontend. The query conditions for filtering items by date have been updated to use an $or operator, allowing for greater flexibility. Additionally, new components like Calendar, DateSelectionButton, and RescheduleCalendar have been added to facilitate the user interface for rescheduling items.

Changes

File Path Change Summary
apps/backend/src/services/lib/item.service.js Modified getThisWeekItemsByDateRange to use $or for filtering items by startDate, endDate, and dueDate.
apps/frontend/src/components/Inbox/InboxItems.tsx Added state variables and methods for managing item rescheduling; modified event handlers and rendering logic.
apps/frontend/src/components/Inbox/RescheduleCalendar/Calendar.tsx Introduced Calendar component utilizing DayPicker for date selection.
apps/frontend/src/components/Inbox/RescheduleCalendar/DateSelectionButton.tsx Added DateSelectionButton component for displaying and selecting dates.
apps/frontend/src/components/Inbox/RescheduleCalendar/RescheduleCalendar.tsx Introduced RescheduleCalendar component for managing date selections and interactions.
apps/frontend/src/lib/@types/Items/Cycle.ts Updated dueDate property type in CycleItem interface from `string
apps/frontend/src/lib/store/cycle.store.ts Added updateItemsInViewInbox helper function for item updates and standardized error handling messages.
apps/frontend/src/components/DropDownItems.tsx Added useEffect to log changes to the item prop for debugging purposes.
apps/frontend/src/components/ThisWeek/CustomKanban.tsx Updated date handling in onDragEnd and handleSubmit functions to use Date objects instead of strings.
apps/frontend/src/utils/datetime.ts Changed parameter type for getOverdueText function from `string

Possibly related PRs

  • fix: overdue item #363: Modifies the item.service.js file, specifically the getThisWeekItems function, which is closely related to the getThisWeekItemsByDateRange function.
  • feat: getThisWeekItemsByDateRange #397: Introduces a new controller function getThisWeekItemsByDateRangeController, which directly relates to the changes made in the getThisWeekItemsByDateRange function.
  • fix: this week newest items appear at the bottom #486: Adds sorting logic to the getThisWeekItemsByDateRange function, directly relating to the date filtering changes in the main PR.
  • fix: this week cycle #512: Introduces a new cycle object with startsAt and endsAt fields, which is relevant to the changes in the main PR that modifies item queries based on cycle dates.

Suggested reviewers

  • deewakar-k

🐇 In the fields where items play,
A change has come to light today.
With dates now flexibly aligned,
More treasures we shall surely find!
So hop along, let’s fetch with glee,
For every cycle holds a key! 🌼


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 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 Nov 1, 2024

Hey there! 👋

We require pull request titles to follow the Conventional Commits specification.

Valid types:

  • feat: A new feature
  • fix: A bug fix
  • docs: Documentation only changes
  • style: Changes that do not affect the meaning of the code
  • refactor: A code change that neither fixes a bug nor adds a feature
  • perf: A code change that improves performance
  • test: Adding missing or correcting existing tests
  • build: Changes that affect the build system or external dependencies
  • ci: Changes to CI configuration files and scripts
  • chore: Other changes that don't modify src or test files
  • revert: Reverts a previous commit

Format: type: description

Error details:

No release type found in pull request title "This week imp". Add a prefix to indicate what kind of release this pull request corresponds to. For reference, see https://www.conventionalcommits.org/

Available types:
 - feat
 - fix
 - docs
 - style
 - refactor
 - perf
 - test
 - build
 - ci
 - chore
 - revert

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: 0

🧹 Outside diff range and nitpick comments (1)
apps/backend/src/services/lib/item.service.js (1)

80-84: Consider adding an index to improve query performance.

The query uses multiple date range conditions across different fields. To optimize performance, especially as the dataset grows, consider adding a compound index.

Add the following index to your MongoDB schema:

{
  user: 1,
  isArchived: 1,
  isDeleted: 1,
  "cycle.startsAt": 1,
  "cycle.endsAt": 1,
  dueDate: 1
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0c42e3c and 91d2a68.

📒 Files selected for processing (1)
  • apps/backend/src/services/lib/item.service.js (1 hunks)
🔇 Additional comments (2)
apps/backend/src/services/lib/item.service.js (2)

80-84: Maintain consistency with getThisWeekItems function.

The getThisWeekItems function (lines 28-54) uses a different approach for handling completed items with cycleDate. Consider whether this logic should also be applied here for consistency.

Let's verify the differences:

#!/bin/bash
# Description: Compare the status handling between weekly item functions

# Test: Search for status conditions in weekly item queries
rg -B 5 -A 5 'status.*\$nin.*done'

80-84: Verify the completeness of the date range query conditions.

The query logic has been expanded to include items based on cycle.startsAt, cycle.endsAt, or dueDate falling within the date range. While this change makes sense, there are a few considerations:

  1. The query might miss items that span across the date range (i.e., starts before and ends after). Consider if this is the intended behavior.
  2. The function name getThisWeekItemsByDateRange suggests a weekly context, but the implementation allows any date range. Consider renaming for clarity.

Let's verify the query behavior with this script:

✅ Verification successful

Let me gather more information about the existing date range queries and cycle-related functionality.


The date range query implementation is correct and consistent with the codebase

After analyzing both functions, I can confirm that:

  1. The new date range query in getThisWeekItemsByDateRange correctly handles items that fall within the specified date range, including cycle-based items.
  2. The implementation is complementary to getThisWeekItems, which focuses on cycle dates and item status, serving a different use case.
  3. The query will not miss items that span across the date range because it checks both start and end dates of cycles.
  4. The function name is appropriate as it's used specifically in the "this-week" route (/this-week/) despite accepting custom date ranges, allowing for flexible week definitions.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for similar date range queries in the codebase to ensure consistency

# Test: Search for similar date range queries using cycle or due dates
rg -A 5 '\$or.*cycle\.(starts|ends)At.*dueDate'

# Test: Search for other weekly item queries for comparison
rg -A 5 'ThisWeek.*Items'

Length of output: 8194


Script:

#!/bin/bash
# Search for the implementation of getThisWeekItems to compare logic
ast-grep --pattern 'const getThisWeekItems = async ($$$) => {
  $$$
}'

# Search for other cycle-related queries
rg -A 5 'cycle\.(starts|ends)At.*\$' --type js

Length of output: 2896

@oliursahin oliursahin self-requested a review November 2, 2024 08:28
@oliursahin oliursahin requested review from oliursahin and removed request for oliursahin November 2, 2024 08:56
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: 13

🧹 Outside diff range and nitpick comments (4)
apps/frontend/src/components/Inbox/RescheduleCalendar/DateSelectionButton.tsx (1)

14-14: Improve visual feedback and theme support.

The current styling could be enhanced for better user experience:

Consider these improvements:

-      className="hover-bg hover-text flex w-full cursor-pointer items-center justify-between gap-4 rounded-lg p-2"
+      className="flex w-full cursor-pointer items-center justify-between gap-4 rounded-lg p-2 transition-colors hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-primary-500 dark:hover:bg-gray-800"

Also consider adding visual feedback for different button states:

  • Loading state with a spinner
  • Disabled state with appropriate styling
  • Active/pressed state

Also applies to: 17-20

apps/frontend/src/components/Inbox/RescheduleCalendar/Calendar.tsx (1)

12-17: Consider adding prop documentation.

While the props are well-structured, adding JSDoc comments would improve maintainability and developer experience.

Add documentation like this:

+/**
+ * Calendar component that wraps react-day-picker with custom styling
+ * @param {string} className - Additional classes to apply to the calendar
+ * @param {object} classNames - Custom class names for calendar elements
+ * @param {boolean} showOutsideDays - Whether to show days from previous/next months
+ */
function Calendar({
apps/frontend/src/components/Inbox/InboxItems.tsx (1)

132-141: Consider using more specific TypeScript event type.

While the function works correctly, you could make it more type-safe by using React.MouseEvent<HTMLElement> instead of the generic React.MouseEvent.

 const handleRescheduleCalendar = (
-  e: React.MouseEvent,
+  e: React.MouseEvent<HTMLElement>,
   id: string,
   dueDate: Date | string | null
 ) => {
apps/frontend/src/lib/store/cycle.store.ts (1)

Line range hint 398-425: Consider extracting view-specific logic into separate modules.

The introduction of updateItemsInViewInbox is a good step towards better organization, but as the complexity grows, consider:

  1. Moving view-specific update logic into separate modules
  2. Creating a common interface for view updates
  3. Adding unit tests for each view's update logic

This would improve maintainability and make it easier to add new views in the future.

Would you like help with:

  1. Creating a modular structure for view-specific logic?
  2. Setting up unit tests for the update functions?
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 91d2a68 and 744c8ae.

📒 Files selected for processing (7)
  • apps/backend/src/services/lib/item.service.js (1 hunks)
  • apps/frontend/src/components/Inbox/InboxItems.tsx (6 hunks)
  • apps/frontend/src/components/Inbox/RescheduleCalendar/Calendar.tsx (1 hunks)
  • apps/frontend/src/components/Inbox/RescheduleCalendar/DateSelectionButton.tsx (1 hunks)
  • apps/frontend/src/components/Inbox/RescheduleCalendar/RescheduleCalendar.tsx (1 hunks)
  • apps/frontend/src/lib/@types/Items/Cycle.ts (1 hunks)
  • apps/frontend/src/lib/store/cycle.store.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/backend/src/services/lib/item.service.js
🔇 Additional comments (7)
apps/frontend/src/lib/@types/Items/Cycle.ts (1)

11-11: Consider standardizing date type handling.

While adding Date type support is good for direct date operations, having multiple types (Date | string | null) for dates can lead to inconsistent date handling across the application. Consider standardizing to either:

  1. Use Date consistently and handle string conversion at API boundaries
  2. Use ISO string format consistently and handle Date conversion when needed for operations

Let's verify the consistency of date type handling across the codebase:

apps/frontend/src/components/Inbox/RescheduleCalendar/Calendar.tsx (3)

1-10: LGTM! Well-structured imports and type definition.

The imports are properly organized, and the type definition correctly extends the DayPicker props.


69-71: LGTM! Proper component export configuration.

The displayName is correctly set, and the component is properly exported.


18-67: Consider enhancing accessibility features.

While DayPicker provides basic accessibility, consider adding:

  1. ARIA labels for better screen reader support
  2. Explicit keyboard navigation instructions
  3. High contrast mode support in the styling

Let's check if there are any existing accessibility patterns in the codebase:

apps/frontend/src/components/Inbox/RescheduleCalendar/RescheduleCalendar.tsx (1)

21-27: Verify integration with parent components.

Let's verify that the parent components are correctly passing all required props and handling state updates.

✅ Verification successful

Integration with parent component is properly implemented

The verification shows that:

  • RescheduleCalendar is correctly imported and used in InboxItems.tsx
  • All required props (date, setDate, dateChanged, setDateChanged) are properly passed
  • Parent component maintains appropriate state management:
    • date and setDate using React's useState
    • dateChanged and setDateChanged state for tracking changes
    • Proper modal handling with reschedulingItemId
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components that render RescheduleCalendar
rg -A 5 "RescheduleCalendar" --type tsx

# Verify all required props are passed
ast-grep --pattern 'RescheduleCalendar $$$props={$$$}'

Length of output: 124


Script:

#!/bin/bash
# Search for components that render RescheduleCalendar with proper file extension
rg -A 5 "RescheduleCalendar" --type ts --type jsx --type tsx

# Search for import statements of RescheduleCalendar
rg "import.*RescheduleCalendar" --type ts --type jsx --type tsx

# Find all TypeScript/React files that might contain the component
fd -e tsx -e ts -e jsx | xargs rg "RescheduleCalendar"

Length of output: 1319


Script:

#!/bin/bash
# Get the implementation of InboxItems component to verify prop passing
rg -A 20 "RescheduleCalendar" apps/frontend/src/components/Inbox/InboxItems.tsx

# Get the state management related to date in InboxItems
ast-grep --pattern 'const [$_,$_] = useState<$_>($$$)'

Length of output: 6570

apps/frontend/src/components/Inbox/InboxItems.tsx (2)

5-5: LGTM: Import statements are properly organized.

The new imports for CalendarIcon and RescheduleCalendar are correctly placed and align with the new rescheduling feature.

Also applies to: 8-8


21-25: LGTM: State variables are well-defined.

The new state variables for managing rescheduling functionality are properly typed and initialized with appropriate default values.

Comment on lines +13 to +16
<button
className="hover-bg hover-text flex w-full cursor-pointer items-center justify-between gap-4 rounded-lg p-2"
onClick={onClick}
>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance accessibility and component flexibility.

The button implementation could be improved for better accessibility and flexibility:

Apply these changes:

   <button
     className="hover-bg hover-text flex w-full cursor-pointer items-center justify-between gap-4 rounded-lg p-2"
     onClick={onClick}
+    aria-label={`Select date: ${label} ${formattedDate}`}
+    type="button"
   >

Consider adding these props for better component flexibility:

interface DateSelectionButtonProps {
  // ... existing props
  disabled?: boolean
  iconSize?: number
  className?: string
}

Comment on lines +1 to +11
export default function DateSelectionButton({
label,
icon: Icon,
formattedDate,
onClick,
}: {
label: string
icon: React.ElementType
formattedDate: string
onClick: () => void
}) {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add missing imports and improve type definitions.

The component interface needs some improvements for better maintainability and documentation:

Apply these changes:

+import React from 'react'
+
+interface DateSelectionButtonProps {
+  /** The text label to display on the button */
+  label: string
+  /** The icon component to render */
+  icon: React.ElementType
+  /** The formatted date string to display */
+  formattedDate: string
+  /** Callback function when button is clicked */
+  onClick: () => void
+}
+
+/**
+ * A button component for date selection with an icon and formatted date display
+ */
-export default function DateSelectionButton({
+export default function DateSelectionButton({
   label,
   icon: Icon,
   formattedDate,
   onClick,
-}: {
-  label: string
-  icon: React.ElementType
-  formattedDate: string
-  onClick: () => void
-}) {
+}: DateSelectionButtonProps) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export default function DateSelectionButton({
label,
icon: Icon,
formattedDate,
onClick,
}: {
label: string
icon: React.ElementType
formattedDate: string
onClick: () => void
}) {
import React from 'react'
interface DateSelectionButtonProps {
/** The text label to display on the button */
label: string
/** The icon component to render */
icon: React.ElementType
/** The formatted date string to display */
formattedDate: string
/** Callback function when button is clicked */
onClick: () => void
}
/**
* A button component for date selection with an icon and formatted date display
*/
export default function DateSelectionButton({
label,
icon: Icon,
formattedDate,
onClick,
}: DateSelectionButtonProps) {

Comment on lines +22 to +60
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4 text-primary-foreground",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
"h-7 w-7 text-center bg-transparent p-1 text-secondary-foreground hover-text"
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell:
"text-secondary-foreground rounded-md w-8 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: cn(
"relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected].day-range-end)]:rounded-r-md",
props.mode === "range"
? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
: "[&:has([aria-selected])]:rounded-md"
),
day: cn(
"h-8 w-8 p-0 font-normal aria-selected:opacity-100 text-secondary-foreground hover-bg hover-text rounded-lg"
),
day_range_start: "day-range-start",
day_range_end: "day-range-end",
day_selected:
"bg-background-hover border border-border !text-foreground",
day_today: "bg-background-hover text-foreground",
day_outside:
"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle:
"aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",

...classNames,
}}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider extracting classNames configuration.

The large classNames object mixed with component logic reduces readability. Consider extracting it to a separate constant or configuration file.

Create a separate configuration:

// calendarConfig.ts
export const defaultCalendarClassNames = {
  months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
  month: "space-y-4 text-primary-foreground",
  // ... rest of the classNames
}

// Calendar.tsx
import { defaultCalendarClassNames } from './calendarConfig'

Comment on lines +61 to +64
components={{
IconLeft: ({ ...props }) => <ChevronLeftIcon className="size-4" />,
IconRight: ({ ...props }) => <ChevronRightIcon className="size-4" />,
}}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider making icon components more reusable.

The icon components could be extracted to be more reusable and configurable.

Consider this approach:

type NavigationIconProps = {
  className?: string;
  // Add other props as needed
}

const NavigationIcon = ({ icon: Icon, ...props }: NavigationIconProps & { icon: typeof ChevronLeftIcon | typeof ChevronRightIcon }) => (
  <Icon className={cn("size-4", props.className)} />
);

// Usage in components prop
components={{
  IconLeft: (props) => <NavigationIcon icon={ChevronLeftIcon} {...props} />,
  IconRight: (props) => <NavigationIcon icon={ChevronRightIcon} {...props} />,
}}

Comment on lines +21 to +29
export function RescheduleCalendar({
date,
setDate,
dateChanged,
setDateChanged,
...props
}: RescheduleCalendarProps) {
const [noDate, setNoDateFlag] = React.useState<boolean>(false)

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize state management and prop handling.

  1. The noDate state appears redundant as this information can be derived from the date prop being null.
  2. Spreading unknown props onto a div could lead to invalid HTML attributes.
-  const [noDate, setNoDateFlag] = React.useState<boolean>(false)
+  const isNoDate = date === null
   
   // In the render method
   <div
     className="flex flex-row-reverse overflow-hidden rounded-lg bg-background text-secondary-foreground"
-    {...props}
+    {...(props.className && { className: props.className })}
   >

Also applies to: 62-65

Comment on lines +12 to +19
interface RescheduleCalendarProps {
date: Date | null
setDate: (date: Date | null) => void
dateChanged: boolean
setDateChanged: (state: boolean) => void
icon?: React.ReactNode
[key: string]: any
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider removing the index signature for better type safety.

The interface includes [key: string]: any which bypasses TypeScript's type checking. If additional props are needed, they should be explicitly defined.

 interface RescheduleCalendarProps {
   date: Date | null
   setDate: (date: Date | null) => void
   dateChanged: boolean
   setDateChanged: (state: boolean) => void
   icon?: React.ReactNode
-  [key: string]: any
+  className?: string  // Add specific props as needed
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +57 to +63
useEffect(() => {
if (dateChanged && reschedulingItemId && date) {
updateItem(session, { dueDate: date, status: "todo" }, reschedulingItemId)
setReschedulingItemId(null)
setDateChanged(false)
}
}, [date, updateItem, session, reschedulingItemId, dateChanged])
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling for the updateItem operation.

While the effect logic is sound, it's recommended to add error handling for the updateItem operation to gracefully handle potential failures and provide feedback to the user.

 useEffect(() => {
   if (dateChanged && reschedulingItemId && date) {
-    updateItem(session, { dueDate: date, status: "todo" }, reschedulingItemId)
-    setReschedulingItemId(null)
-    setDateChanged(false)
+    updateItem(session, { dueDate: date, status: "todo" }, reschedulingItemId)
+      .then(() => {
+        setReschedulingItemId(null)
+        setDateChanged(false)
+      })
+      .catch((error) => {
+        // Handle error (e.g., show error message to user)
+        console.error('Failed to update item:', error)
+      })
   }
 }, [date, updateItem, session, reschedulingItemId, dateChanged])

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +210 to +232
{reschedulingItemId !== null && (
<div>
<div
className="fixed inset-0 z-50 cursor-default bg-black/80"
role="button"
onClick={() => setReschedulingItemId(null)}
onKeyDown={(e) => {
if (e.key === "Escape" || e.key === "Esc") {
setReschedulingItemId(null)
}
}}
tabIndex={0}
></div>
<div className="fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2 rounded-md bg-background shadow-lg">
<RescheduleCalendar
date={date}
setDate={setDate}
dateChanged={dateChanged}
setDateChanged={setDateChanged}
/>
</div>
</div>
)}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance modal accessibility.

While the modal implementation is solid, consider these accessibility improvements:

  1. Add aria-modal="true" to the modal container
  2. Add a descriptive aria-label for screen readers
  3. Consider trapping focus within the modal while it's open
-      {reschedulingItemId !== null && (
+      {reschedulingItemId !== null && (
         <div>
           <div
             className="fixed inset-0 z-50 cursor-default bg-black/80"
             role="button"
             onClick={() => setReschedulingItemId(null)}
             onKeyDown={(e) => {
               if (e.key === "Escape" || e.key === "Esc") {
                 setReschedulingItemId(null)
               }
             }}
             tabIndex={0}
           ></div>
-          <div className="fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2 rounded-md bg-background shadow-lg">
+          <div 
+            className="fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2 rounded-md bg-background shadow-lg"
+            role="dialog"
+            aria-modal="true"
+            aria-label="Reschedule Item">
             <RescheduleCalendar
               date={date}
               setDate={setDate}
               dateChanged={dateChanged}
               setDateChanged={setDateChanged}
             />
           </div>
         </div>
       )}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{reschedulingItemId !== null && (
<div>
<div
className="fixed inset-0 z-50 cursor-default bg-black/80"
role="button"
onClick={() => setReschedulingItemId(null)}
onKeyDown={(e) => {
if (e.key === "Escape" || e.key === "Esc") {
setReschedulingItemId(null)
}
}}
tabIndex={0}
></div>
<div className="fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2 rounded-md bg-background shadow-lg">
<RescheduleCalendar
date={date}
setDate={setDate}
dateChanged={dateChanged}
setDateChanged={setDateChanged}
/>
</div>
</div>
)}
{reschedulingItemId !== null && (
<div>
<div
className="fixed inset-0 z-50 cursor-default bg-black/80"
role="button"
onClick={() => setReschedulingItemId(null)}
onKeyDown={(e) => {
if (e.key === "Escape" || e.key === "Esc") {
setReschedulingItemId(null)
}
}}
tabIndex={0}
></div>
<div
className="fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2 rounded-md bg-background shadow-lg"
role="dialog"
aria-modal="true"
aria-label="Reschedule Item">
<RescheduleCalendar
date={date}
setDate={setDate}
dateChanged={dateChanged}
setDateChanged={setDateChanged}
/>
</div>
</div>
)}

Comment on lines +398 to +407
const updateItemsInViewInbox = (items: CycleItem[]) => {
// remove item from inbox if dueDate is set (not null)
if (updates.dueDate) {
return items.filter((item) => item._id !== id)
}
// otherwise, just update the item in inbox
return items.map((item) =>
item._id === id ? { ...item, ...updates } : item
)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type safety and handle edge cases in updateItemsInViewInbox.

The new helper function improves code organization, but could benefit from these enhancements:

-const updateItemsInViewInbox = (items: CycleItem[]) => {
+const updateItemsInViewInbox = (items: CycleItem[], updates: Partial<CycleItem>) => {
   // remove item from inbox if dueDate is set (not null)
-  if (updates.dueDate) {
+  if (updates.dueDate !== undefined && updates.dueDate !== null) {
     return items.filter((item) => item._id !== id)
   }
   // otherwise, just update the item in inbox
   return items.map((item) =>
     item._id === id ? { ...item, ...updates } : item
   )
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const updateItemsInViewInbox = (items: CycleItem[]) => {
// remove item from inbox if dueDate is set (not null)
if (updates.dueDate) {
return items.filter((item) => item._id !== id)
}
// otherwise, just update the item in inbox
return items.map((item) =>
item._id === id ? { ...item, ...updates } : item
)
}
const updateItemsInViewInbox = (items: CycleItem[], updates: Partial<CycleItem>) => {
// remove item from inbox if dueDate is set (not null)
if (updates.dueDate !== undefined && updates.dueDate !== null) {
return items.filter((item) => item._id !== id)
}
// otherwise, just update the item in inbox
return items.map((item) =>
item._id === id ? { ...item, ...updates } : item
)
}

Comment on lines +422 to +425
inbox: {
...state.inbox,
items: updateItemsInViewInbox(state.inbox.items),
},
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Pass updates parameter to updateItemsInViewInbox function

The review comment is correct. Looking at the implementation:

  1. updateItemsInViewInbox function requires the updates parameter to:

    • Remove items from inbox when updates.dueDate is set
    • Update items with the updates object when mapping
  2. Current usage is missing the required parameter:

 inbox: {
   ...state.inbox,
-  items: updateItemsInViewInbox(state.inbox.items),
+  items: updateItemsInViewInbox(state.inbox.items, updates),
 },
🔗 Analysis chain

Pass updates parameter to updateItemsInViewInbox and verify view consistency.

The inbox view update is missing the updates parameter and should be consistent with other views.

 inbox: {
   ...state.inbox,
-  items: updateItemsInViewInbox(state.inbox.items),
+  items: updateItemsInViewInbox(state.inbox.items, updates),
 },

Let's verify the consistency of item updates across different views:


Let me check the implementation of both update functions to ensure they handle parameters consistently.


Let me try a different approach to find these function implementations.


Let me try one last search with a simpler pattern to find these functions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for inconsistencies in how items are updated across different views

# Search for all item update patterns
rg -A 5 'items: update.*Items.*View' apps/frontend/src/lib/store/

Length of output: 4396


Script:

#!/bin/bash
# Search for the implementation of both update functions
ast-grep --pattern 'function updateItemsInView$$$'
ast-grep --pattern 'function updateItemsInViewInbox$$$'

Length of output: 110


Script:

#!/bin/bash
# Search for the function declarations with more context
rg -U "function updateItemsInView.*?\{.*?\}" -A 10
rg -U "function updateItemsInViewInbox.*?\{.*?\}" -A 10

Length of output: 110


Script:

#!/bin/bash
# Search for the function names without regex
rg "updateItemsInView" -B 2 -A 10
rg "updateItemsInViewInbox" -B 2 -A 10

Length of output: 10881

@sajdakabir sajdakabir changed the title This week This week imp Nov 2, 2024
@oliursahin oliursahin removed their request for review November 4, 2024 05:13
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.

2 participants