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

feat: add reset and retry buttons to episode cards #176

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

machetie
Copy link

@machetie machetie commented Nov 15, 2024

Add reset and retry functionality to episode cards:

  • Add click-to-show action buttons on episode cards
  • Implement reset and retry functionality
  • Add visual feedback with blur effect and overlay
  • Show success/error toasts for actions

Summary by CodeRabbit

  • New Features

    • Enhanced media episode management with new action buttons for resetting and retrying episodes.
    • Introduced visual feedback with animation effects on selected episodes.
    • Added icons for improved user interface.
    • Implemented functionality to track and toggle selected episodes.
    • Added keyboard accessibility for episode selection.
  • Bug Fixes

    • Improved user notifications for success or failure of media item actions.

Copy link

coderabbitai bot commented Nov 15, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request focus on enhancing the functionality of the +page.svelte file related to media episode management. Key updates include the addition of new icons, state management for selected episodes, and asynchronous functions for resetting and retrying media items. The user interface is updated to allow episode selection and conditional rendering of action buttons, along with styling changes for improved visual feedback.

Changes

File Path Change Summary
src/routes/[type=mediaType]/[id]/[season]/+page.svelte - Added icons: CirclePower, RotateCcw from lucide-svelte.
- Introduced variables: selectedEpisodeNumber, isResetting, isRetrying.
- Added methods: handleMediaAction, resetItem, retryItem, and handleEpisodeClick.
- Updated template to include click events and conditional rendering for action buttons.
- Applied styling changes with animation classes for selected episodes.
eslint.config.js - Updated no-console rule to allow only warn and error console statements.
tailwind.config.ts - Added keyframe animations blur-in and blur-out.
- Introduced a new backgroundImage property for unavailable.

Possibly related PRs

  • feat: add season states to the item details #173: The changes in this PR involve modifications to the src/routes/[type=mediaType]/[id]/+page.svelte file, which is also part of the media episode management functionality, enhancing the display logic for seasons and episodes, similar to the enhancements made in the main PR.

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

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between af4b2fb and 2bad253.

📒 Files selected for processing (1)
  • src/routes/[type=mediaType]/[id]/[season]/+page.svelte (3 hunks)
🧰 Additional context used
🪛 eslint
src/routes/[type=mediaType]/[id]/[season]/+page.svelte

[error] 24-24: 'invalidateAll' is not defined.

(no-undef)


[error] 40-40: 'invalidateAll' is not defined.

(no-undef)


[error] 122-188: A11y: visible, non-interactive elements with an on:click event must be accompanied by a keyboard event handler. Consider whether an interactive element such as or might be more appropriate. See https://svelte.dev/docs/accessibility-warnings#a11y-click-events-have-key-events for more details.(a11y-click-events-have-key-events)

(svelte/valid-compile)


[error] 122-188: A11y:

with click handler must have an ARIA role(a11y-no-static-element-interactions)

(svelte/valid-compile)

src/routes/[type=mediaType]/[id]/[season]/+page.svelte Outdated Show resolved Hide resolved
src/routes/[type=mediaType]/[id]/[season]/+page.svelte Outdated Show resolved Hide resolved
src/routes/[type=mediaType]/[id]/[season]/+page.svelte Outdated Show resolved Hide resolved
src/routes/[type=mediaType]/[id]/[season]/+page.svelte Outdated Show resolved Hide resolved
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 2bad253 and 8ccf9d3.

📒 Files selected for processing (1)
  • src/routes/[type=mediaType]/[id]/[season]/+page.svelte (3 hunks)
🧰 Additional context used
🪛 eslint
src/routes/[type=mediaType]/[id]/[season]/+page.svelte

[error] 18-18: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)


[error] 190-190: Classes can only be applied to DOM elements, not components(invalid-class)

(svelte/valid-compile)

let isRetrying = false;

async function handleMediaAction(
action: (id: string) => Promise<any>,
Copy link

@coderabbitai coderabbitai bot Nov 15, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Specify a more precise return type instead of any.

Using any in TypeScript defeats the purpose of type checking and can lead to runtime errors. Define a specific interface or type for the expected response to enhance type safety and code reliability.

Apply this diff to specify a proper return type:

-   action: (id: string) => Promise<any>,
+   action: (id: string) => Promise<{ error?: boolean; [key: string]: any }>,

Alternatively, define a custom interface for the response:

interface ActionResponse {
  error?: boolean;
  // other relevant properties
}

And update the function signature:

-   action: (id: string) => Promise<any>,
+   action: (id: string) => Promise<ActionResponse>,
🧰 Tools
🪛 eslint

[error] 18-18: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

Copy link
Collaborator

Choose a reason for hiding this comment

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

+1

Copy link

Choose a reason for hiding this comment

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

@Gaisberg, glad to hear that!


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Comment on lines 73 to 77
if (selectedEpisodeNumber === episodeNumber) {
selectedEpisodeNumber = null;
} else {
selectedEpisodeNumber = episodeNumber;
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify the toggle logic in handleEpisodeClick.

You can streamline the logic by setting selectedEpisodeNumber to null if it's already selected, or to the new episodeNumber otherwise.

Apply this diff for a cleaner implementation:

 function handleEpisodeClick(episodeNumber: number) {
-   if (selectedEpisodeNumber === episodeNumber) {
-     selectedEpisodeNumber = null;
-   } else {
-     selectedEpisodeNumber = episodeNumber;
-   }
+   selectedEpisodeNumber = selectedEpisodeNumber === episodeNumber ? null : episodeNumber;
 }
📝 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
if (selectedEpisodeNumber === episodeNumber) {
selectedEpisodeNumber = null;
} else {
selectedEpisodeNumber = episodeNumber;
}
selectedEpisodeNumber = selectedEpisodeNumber === episodeNumber ? null : episodeNumber;

Comment on lines +36 to +39
console.error('Network or unexpected error:', error);
toast.error('Network error occurred. Please check your connection and try again.');
throw error;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Avoid re-throwing caught errors after handling.

Since you're already displaying a toast notification and logging the error, re-throwing it might not be necessary and could interrupt the flow.

Apply this diff to prevent re-throwing the error:

       } catch (error) {
         console.error('Network or unexpected error:', error);
         toast.error('Network error occurred. Please check your connection and try again.');
-        throw error;
       } finally {
📝 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
console.error('Network or unexpected error:', error);
toast.error('Network error occurred. Please check your connection and try again.');
throw error;
console.error('Network or unexpected error:', error);
toast.error('Network error occurred. Please check your connection and try again.');

on:click|stopPropagation={() => resetItem(data.mediaID)}
disabled={isResetting || isRetrying}
>
<CirclePower class="size-4" class:animate-spin={isResetting} />
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix invalid use of class directive on components.

The class and class: directives cannot be applied directly to Svelte components like <CirclePower />. To apply classes or directives, wrap the component in a DOM element or use a spread attribute if the component supports it.

Apply this diff to fix the issue:

-       <CirclePower class="size-4" class:animate-spin={isResetting} />
+       <span class="size-4" class:animate-spin={isResetting}>
+         <CirclePower />
+       </span>

Repeat the same adjustment for the <RotateCcw /> component in the retry button.

📝 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
<CirclePower class="size-4" class:animate-spin={isResetting} />
<span class="size-4" class:animate-spin={isResetting}>
<CirclePower />
</span>
🧰 Tools
🪛 eslint

[error] 190-190: Classes can only be applied to DOM elements, not components(invalid-class)

(svelte/valid-compile)

Comment on lines 187 to 198
on:click|stopPropagation={() => resetItem(data.mediaID)}
disabled={isResetting || isRetrying}
>
<CirclePower class="size-4" class:animate-spin={isResetting} />
{isResetting ? 'Resetting...' : 'Reset'}
</button>
<button
class="flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
on:click|stopPropagation={() => retryItem(data.mediaID)}
disabled={isResetting || isRetrying}
>
<RotateCcw class="size-4" class:animate-spin={isRetrying} />
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Pass the correct episode ID to resetItem and retryItem functions.

Currently, the functions are called with data.mediaID, which refers to the entire media item. To target the specific episode, pass episode.id instead.

Apply this diff to fix the IDs being passed:

   on:click|stopPropagation={() => resetItem(
-     data.mediaID
+     episode.id
   )}
   on:click|stopPropagation={() => retryItem(
-     data.mediaID
+     episode.id
   )}

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

🧰 Tools
🪛 eslint

[error] 190-190: Classes can only be applied to DOM elements, not components(invalid-class)

(svelte/valid-compile)

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 8ccf9d3 and d928367.

📒 Files selected for processing (1)
  • src/routes/[type=mediaType]/[id]/[season]/+page.svelte (3 hunks)
🧰 Additional context used
🪛 eslint
src/routes/[type=mediaType]/[id]/[season]/+page.svelte

[error] 18-18: Unexpected any. Specify a different type.

(@typescript-eslint/no-explicit-any)

🔇 Additional comments (1)
src/routes/[type=mediaType]/[id]/[season]/+page.svelte (1)

4-9: Imports are correctly updated

The necessary modules and components are imported appropriately, ensuring all required functionalities are available.

Comment on lines 181 to 206
{#if selectedEpisodeNumber === episode.episode_number && data.mediaItemDetails.find((x) => x.number == episode.episode_number)}
<div
class="absolute inset-0 flex items-center justify-center gap-4 bg-black/40"
>
<button
class="flex items-center gap-2 rounded-md bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground hover:bg-destructive/90 disabled:opacity-50 disabled:cursor-not-allowed"
on:click|stopPropagation={() => resetItem(episode.id)}
disabled={isResetting || isRetrying}
>
<CirclePower class={`size-4 ${isResetting ? 'animate-spin' : ''}`} />
{isResetting ? 'Resetting...' : 'Reset'}
</button>
<button
class="flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
on:click|stopPropagation={() => retryItem(episode.id)}
disabled={isResetting || isRetrying}
>
<RotateCcw class={`size-4 ${isRetrying ? 'animate-spin' : ''}`} />
{isRetrying ? 'Retrying...' : 'Retry'}
</button>
</div>
{/if}

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Optimize repeated lookups by caching media item details

The expression data.mediaItemDetails.find((x) => x.number == episode.episode_number) is used multiple times within the loop. Consider caching these lookups to improve performance and readability.

You can create a map of mediaItemDetails before the loop:

<script lang="ts">
  // ... existing code
  const mediaItemDetailsMap = new Map<number, typeof data.mediaItemDetails[0]>(
    data.mediaItemDetails.map((item) => [item.number, item])
  );
</script>

Then, within the {#each} loop, retrieve the item efficiently:

{#each data.details.episodes as episode}
  {#if selectedEpisodeNumber === episode.episode_number && mediaItemDetailsMap.has(episode.episode_number)}
    <!-- Action buttons -->
  {/if}

  <!-- Use the cached item elsewhere -->
  {#if mediaItemDetailsMap.has(episode.episode_number)}
    <div class="mt-1 line-clamp-1 rounded-md bg-zinc-900/60 px-2 text-xs text-white sm:text-sm">
      {statesName[mediaItemDetailsMap.get(episode.episode_number)?.state ?? 'Unknown']}
    </div>
  {/if}
{/each}

This approach avoids repeated find operations, enhancing performance, especially with larger datasets.

Comment on lines +22 to +25
loadingState: { set: (value: boolean) => void }
) {
loadingState.set(true);
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify the loadingState parameter for clarity

Consider simplifying the loadingState parameter in handleMediaAction by passing the setter function directly instead of an object with a set method. This enhances readability and reduces unnecessary complexity.

Apply this diff to update the function signature and usage:

-    loadingState: { set: (value: boolean) => void }
+    loadingState: (value: boolean) => void

Update the function body accordingly:

-    loadingState.set(true);
+    loadingState(true);

And similarly for setting it back to false:

-    loadingState.set(false);
+    loadingState(false);

Update the calls to handleMediaAction in resetItem:

return await handleMediaAction(
    (id) => ItemsService.resetItems({ query: { ids: id.toString() } }),
    'Media reset successfully',
    'An error occurred while resetting the media',
    id,
-   { set: (value) => (isResetting = value) }
+   (value) => { isResetting = value }
);

And in retryItem:

return await handleMediaAction(
    (id) => ItemsService.retryItems({ query: { ids: id.toString() } }),
    'Media retried successfully',
    'An error occurred while retrying the media',
    id,
-   { set: (value) => (isRetrying = value) }
+   (value) => { isRetrying = value }
);

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

@davidemarcoli davidemarcoli force-pushed the feat/episode-action-buttons branch from d928367 to 0be24f5 Compare November 28, 2024 19: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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between d928367 and 0be24f5.

📒 Files selected for processing (3)
  • eslint.config.js (1 hunks)
  • src/routes/[type=mediaType]/[id]/[season]/+page.svelte (3 hunks)
  • tailwind.config.ts (2 hunks)
🧰 Additional context used
🪛 eslint
tailwind.config.ts

[error] 3-3: 'blur' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: Lint
tailwind.config.ts

[failure] 3-3:
'blur' is defined but never used

🔇 Additional comments (7)
eslint.config.js (1)

30-30: LGTM! Good practice for error handling.

The updated no-console rule appropriately allows console.warn and console.error while still warning about other console statements. This is particularly useful for the new reset/retry functionality where proper error handling is important for user feedback.

Let's verify the console usage in the related component:

✅ Verification successful

ESLint rule change aligns perfectly with actual console usage

The updated no-console rule is well-justified by the codebase's usage patterns. All console statements found are console.error calls used appropriately for error handling in:

  • Network/unexpected errors in media episode operations
  • Reset/retry operation failures
  • Data mapping errors

This confirms that the ESLint configuration change to allow console.warn and console.error while warning about other console methods is the right approach for maintaining proper error handling practices.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check console usage in the episode card component
# Expected: Only console.warn and console.error should be used for error handling

# Search for console statements in the related Svelte component
rg -p "console\." "src/routes/\[type=mediaType\]/\[id\]/\[season\]/\+page.svelte"

Length of output: 185


Script:

#!/bin/bash
# Let's first find the correct path for media-related Svelte components
fd -e svelte

# Then search for console statements in all Svelte files
rg -p "console\." -g "*.svelte"

Length of output: 8675

tailwind.config.ts (1)

88-89: LGTM! Well-designed visual indicator.

The repeating striped pattern with semi-transparent red provides a subtle but clear visual indication for unavailable content, which aligns well with the PR's goal of improving visual feedback.

src/routes/[type=mediaType]/[id]/[season]/+page.svelte (5)

19-19: Specify a more precise return type instead of any.

Using any in TypeScript defeats the purpose of type checking and can lead to runtime errors. Define a specific interface or type for the expected response to enhance type safety and code reliability.


37-39: Avoid re-throwing the error after handling.

Since the error is already logged and a toast notification is shown to the user, re-throwing the error might not be necessary and could interrupt the flow by propagating the error further up.

Apply this diff to remove the unnecessary throw statement:

} catch (error) {
  console.error('Network or unexpected error:', error);
  toast.error('Network error occurred. Please check your connection and try again.');
- throw error;
} finally {
  loadingState.set(false);
}

76-78: Great job optimizing media item lookups.

Creating the mediaItemDetailsMap improves performance by caching media item details and avoiding repeated find operations within the loop.


148-164: Accessibility enhancements are well-implemented.

Adding keyboard event handlers, ARIA roles, and attributes improves the accessibility of the episode cards, allowing users to navigate using the keyboard and assistive technologies effectively.


193-201: Ensure components accept class prop or adjust usage.

Passing the class attribute to Svelte components like <CirclePower> and <RotateCcw> may not work as expected if these components do not forward the class prop to the underlying DOM elements. This could prevent your styling and animations from being applied.

Apply this diff to wrap the icon components with a <span> and apply the class to the wrapper:

- <CirclePower class={`size-4 ${isResetting ? 'animate-spin' : ''}`} />
+ <span class={`size-4 ${isResetting ? 'animate-spin' : ''}`}>
+   <CirclePower />
+ </span>

- <RotateCcw class={`size-4 ${isRetrying ? 'animate-spin' : ''}`} />
+ <span class={`size-4 ${isRetrying ? 'animate-spin' : ''}`}>
+   <RotateCcw />
+ </span>

@@ -1,5 +1,6 @@
import { fontFamily } from 'tailwindcss/defaultTheme';
import type { Config } from 'tailwindcss';
import { blur } from 'svelte/transition';
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unused import.

The blur import from svelte/transition is not used in this Tailwind configuration file. Svelte-specific imports should be in the component files where they're used, not in the Tailwind configuration.

-import { blur } from 'svelte/transition';
🧰 Tools
🪛 eslint

[error] 3-3: 'blur' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: Lint

[failure] 3-3:
'blur' is defined but never used

Comment on lines +90 to +102
keyframes: {
'blur-in': {
'0%': { filter: 'blur(0px)' },
'100%': { filter: 'blur(4px)' }
},
'blur-out': {
'0%': { filter: 'blur(4px)' },
'100%': { filter: 'blur(0px)' }
}
},
animation: {
'blur-in': 'blur-in 0.5s forwards',
'blur-out': 'blur-out 0.5s forwards'
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding prefers-reduced-motion support.

The blur animations are well-implemented with appropriate timing and subtle effects. However, consider respecting the user's motion preferences.

Add a media query to disable animations for users who prefer reduced motion:

 animation: {
-  'blur-in': 'blur-in 0.5s forwards',
-  'blur-out': 'blur-out 0.5s forwards'
+  'blur-in': 'blur-in 0.5s forwards @media(prefers-reduced-motion: no-preference)',
+  'blur-out': 'blur-out 0.5s forwards @media(prefers-reduced-motion: no-preference)'
 }

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

Comment on lines +23 to +24
loadingState: { set: (value: boolean) => void }
) {
Copy link

@coderabbitai coderabbitai bot Nov 28, 2024

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify the loadingState parameter for clarity.

Consider passing the setter function directly instead of an object with a set method. This will enhance readability and reduce unnecessary complexity.

Apply this diff to update the function signature and usage:

// Update the function signature
async function handleMediaAction(
  action: (id: string) => Promise<any>,
  successMessage: string,
  errorMessage: string,
  id: string,
- loadingState: { set: (value: boolean) => void }
+ loadingState: (value: boolean) => void
) {
- loadingState.set(true);
+ loadingState(true);
  try {
    // ...
  } finally {
-   loadingState.set(false);
+   loadingState(false);
  }
}

// Update the calls to `handleMediaAction` in `resetItem`:
return await handleMediaAction(
  (id) => ItemsService.resetItems({ query: { ids: id.toString() } }),
  'Media reset successfully',
  'An error occurred while resetting the media',
  id,
- { set: (value) => (isResetting = value) }
+ (value) => (isResetting = value)
);

// Similarly, in `retryItem`:
return await handleMediaAction(
  (id) => ItemsService.retryItems({ query: { ids: id.toString() } }),
  'Media retried successfully',
  'An error occurred while retrying the media',
  id,
- { set: (value) => (isRetrying = value) }
+ (value) => (isRetrying = value)
);

Also applies to: 52-53, 66-67

Copy link
Collaborator

Choose a reason for hiding this comment

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

+1

Copy link

Choose a reason for hiding this comment

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

@Gaisberg, glad you agree with the suggestion! Let me know if you need any further assistance.

Comment on lines +45 to +57
async function resetItem(id: string) {
try {
return await handleMediaAction(
(id) => ItemsService.resetItems({ query: { ids: id.toString() } }),
'Media reset successfully',
'An error occurred while resetting the media',
id,
{ set: (value) => (isResetting = value) }
);
} catch (error) {
console.error('Reset operation failed:', error);
}
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify resetItem and retryItem by removing unnecessary try...catch blocks.

Since handleMediaAction already handles errors and provides user feedback, the additional try...catch blocks in resetItem and retryItem may be redundant. Removing them can simplify the code.

Apply this diff to streamline the functions:

async function resetItem(id: string) {
- try {
    return await handleMediaAction(
      (id) => ItemsService.resetItems({ query: { ids: id.toString() } }),
      'Media reset successfully',
      'An error occurred while resetting the media',
      id,
      { set: (value) => (isResetting = value) }
    );
- } catch (error) {
-   console.error('Reset operation failed:', error);
- }
}

async function retryItem(id: string) {
- try {
    return await handleMediaAction(
      (id) => ItemsService.retryItems({ query: { ids: id.toString() } }),
      'Media retried successfully',
      'An error occurred while retrying the media',
      id,
      { set: (value) => (isRetrying = value) }
    );
- } catch (error) {
-   console.error('Retry operation failed:', error);
- }
}

Also applies to: 59-71

@@ -27,7 +27,7 @@ export default [
}
},
rules: {
'no-console': 'warn',
'no-console': ['warn', { allow: ['warn', 'error'] }],
Copy link
Collaborator

Choose a reason for hiding this comment

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

Lets not allow these...

Copy link
Collaborator

Choose a reason for hiding this comment

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

What should we do then? Don't we want to have some logging for troubleshooting?

let isRetrying = false;

async function handleMediaAction(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Copy link
Collaborator

Choose a reason for hiding this comment

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

Please define the types

Copy link
Collaborator

Choose a reason for hiding this comment

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

Problem is that I'm not sure what it return. I would have to do union types here. But I can do that.

let isRetrying = false;

async function handleMediaAction(
action: (id: string) => Promise<any>,
Copy link
Collaborator

Choose a reason for hiding this comment

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

+1

Comment on lines +23 to +24
loadingState: { set: (value: boolean) => void }
) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

+1

@@ -1,5 +1,6 @@
import { fontFamily } from 'tailwindcss/defaultTheme';
import type { Config } from 'tailwindcss';
import { blur } from 'svelte/transition';
Copy link
Collaborator

Choose a reason for hiding this comment

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

remove this

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.

3 participants