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 5 commits 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 a blur effect on selected episode images.
    • 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 class:blur-sm for selected episode images.

Possibly related PRs

  • feat: add upload logs button #169: The changes in this PR involve the addition of a log upload feature, which includes user feedback mechanisms similar to the toast notifications introduced in the main PR for media actions.

Warning

Rate limit exceeded

@machetie has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 21 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 8ccf9d3 and d928367.


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)

- Add loading states to reset/retry buttons
- Add keyboard navigation to episode cards
- Improve error handling in media actions
- Add ARIA attributes for better accessibility
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

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)

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 +38
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 +203
{#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 +24
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.

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