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

Auto filter end tags, add 1 click offset #75

Merged
merged 4 commits into from
Oct 17, 2024
Merged

Auto filter end tags, add 1 click offset #75

merged 4 commits into from
Oct 17, 2024

Conversation

t3dotgg
Copy link
Member

@t3dotgg t3dotgg commented Oct 16, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced video marker parsing and display in the VodPlayer component.
    • Added functionality to convert various time formats into total seconds.
    • Improved organization of marker types and durations in the UI.
    • Updated CSV download link to utilize newly generated data.
  • Bug Fixes

    • Streamlined state management by removing outdated variables for better performance.

Copy link

vercel bot commented Oct 16, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
markerthing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 17, 2024 2:10am

Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

Walkthrough

The changes made in the VodPlayer component of the application involve the addition of several new functions and modifications to existing logic. Key additions include parseOffsetValue, parseMetadataFromMarker, and parseMarkers, which enhance the parsing of time formats and video markers. The state management has been updated, removing outdated variables in favor of the new parsing logic. The rendering of markers in the UI has been refined to display structured data, and the CSV download functionality has been updated to reflect these changes.

Changes

File Change Summary
src/app/(core)/v/[slug]/player.tsx Added functions: parseOffsetValue, parseMetadataFromMarker, parseMarkers. Updated logic for marker parsing and state management, removed mockedMarkers and videoDuration, and adjusted UI rendering for markers. Updated CSV download link to use generated CSV string.

Poem

In the land of code where rabbits play,
New functions hop in, brightening the day.
Parsing markers, oh what a sight,
With time formats dancing, all feels right!
CSVs ready, let’s share the cheer,
For every change brings us closer, my dear! 🐇✨


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
Contributor

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

📥 Commits

Files that changed from the base of the PR and between 404d904 and 63b7874.

📒 Files selected for processing (1)
  • src/app/(core)/v/[slug]/player.tsx (4 hunks)
🧰 Additional context used
🪛 Biome
src/app/(core)/v/[slug]/player.tsx

[error] 24-24: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Comment on lines +334 to +342
className={`-m-2 rounded-full px-2 py-1 text-sm font-bold ${
marker.type === "start"
? "bg-green-800 text-white"
: marker.type === "end"
? "bg-red-800 text-white"
: marker.type === "offset"
? "bg-blue-800 text-white"
: "bg-gray-800 text-white"
}`}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor nested ternary operator for clarity

The nested ternary operator used for className determination reduces readability. Consider using a mapping object or a helper function to enhance clarity.

Example using a mapping object:

const typeClassMap = {
  start: "bg-green-800 text-white",
  end: "bg-red-800 text-white",
  offset: "bg-blue-800 text-white",
  default: "bg-gray-800 text-white",
};

...

className={`-m-2 rounded-full px-2 py-1 text-sm font-bold ${
  typeClassMap[marker.type] || typeClassMap.default
}`}


return value
.split(":")
.reduce((acc, cur) => (acc = acc * 60 + parseInt(cur, 10)), 0);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid assignment within expression in reduce callback

The assignment within the reduce function can be confusing and is unnecessary. Assignments in expressions may lead to unintended side effects and reduce code clarity.

Apply this diff to remove the assignment:

-    .reduce((acc, cur) => (acc = acc * 60 + parseInt(cur, 10)), 0);
+    .reduce((acc, cur) => acc * 60 + parseInt(cur, 10), 0);
📝 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
.reduce((acc, cur) => (acc = acc * 60 + parseInt(cur, 10)), 0);
.reduce((acc, cur) => acc * 60 + parseInt(cur, 10), 0);
🧰 Tools
🪛 Biome

[error] 24-24: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Comment on lines 215 to 222
const parsedMarkers = useMemo(() => {
if (!props.vod) return;

if (endTime < 0) endTime = 1;

const startTime = Math.max(
marker.position_seconds - offset.totalSeconds - EXPORT_BUFFER,
0
);

if (marker.description.toLowerCase().startsWith("end of")) return [];

return [`${startTime},${endTime},${marker.description.replace(",", "")}`];
});

const ytChapters = mockedMarkers.reduce((acc, marker) => {
const startTime = new Date(
(marker.position_seconds - offset.totalSeconds) * 1000
);
const timeStr = startTime.toISOString().substr(11, 8);
return `${acc}${marker.description} - ${timeStr}\n`;
}, "");
return parseMarkers({
vod: props.vod,
offset: offset,
});
}, [props, offset]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize dependencies in useMemo hook

Including props in the dependency array can cause unnecessary recomputations. It's better to specify the exact properties that affect the memoization.

Apply this diff to adjust the dependencies:

-  }, [props, offset]);
+  }, [props.vod, offset]);
📝 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 parsedMarkers = useMemo(() => {
if (!props.vod) return;
if (endTime < 0) endTime = 1;
const startTime = Math.max(
marker.position_seconds - offset.totalSeconds - EXPORT_BUFFER,
0
);
if (marker.description.toLowerCase().startsWith("end of")) return [];
return [`${startTime},${endTime},${marker.description.replace(",", "")}`];
});
const ytChapters = mockedMarkers.reduce((acc, marker) => {
const startTime = new Date(
(marker.position_seconds - offset.totalSeconds) * 1000
);
const timeStr = startTime.toISOString().substr(11, 8);
return `${acc}${marker.description} - ${timeStr}\n`;
}, "");
return parseMarkers({
vod: props.vod,
offset: offset,
});
}, [props, offset]);
const parsedMarkers = useMemo(() => {
if (!props.vod) return;
return parseMarkers({
vod: props.vod,
offset: offset,
});
}, [props.vod, offset]);

t3dotgg and others added 2 commits October 16, 2024 19:08
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
src/app/(core)/v/[slug]/player.tsx (2)

39-71: Effective marker categorization with room for optimization

The parseMetadataFromMarker function successfully categorizes markers into types (start, end, offset) based on their labels. The implementation is clear and easy to understand.

Consider optimizing the function by using a single loop instead of multiple loops. Here's a suggested refactor:

function parseMetadataFromMarker(marker: string) {
  const lowerMarker = marker.toLowerCase();
  for (const [type, labels] of Object.entries({
    start: START_LABELS,
    end: END_LABELS,
    offset: OFFSET_LABELS,
  })) {
    for (const label of labels) {
      if (lowerMarker.startsWith(label.toLowerCase())) {
        return {
          type,
          label: type === 'offset'
            ? marker.slice(label.length).trim().replaceAll("-", ":")
            : marker.slice(label.length).trim(),
        };
      }
    }
  }
  return { type: "start", label: marker };
}

This refactored version reduces code duplication and improves maintainability.


Line range hint 216-345: Effective integration of new parsing logic with UI improvements

The VodPlayer component has been successfully updated to use the new parseMarkers function and render more detailed marker information. The CSV download functionality has been appropriately updated.

Consider refactoring the nested ternary operator for className determination to improve readability. Here's a suggested approach:

const typeClassMap = {
  start: "bg-green-800 text-white",
  end: "bg-red-800 text-white",
  offset: "bg-blue-800 text-white",
  default: "bg-gray-800 text-white",
};

// In the JSX
className={`-m-2 rounded-full px-2 py-1 text-sm font-bold ${
  typeClassMap[marker.type] || typeClassMap.default
}`}

This change will make the code more maintainable and easier to read.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 63b7874 and 315ae19.

📒 Files selected for processing (1)
  • src/app/(core)/v/[slug]/player.tsx (4 hunks)
🧰 Additional context used
🪛 Biome
src/app/(core)/v/[slug]/player.tsx

[error] 24-24: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

🔇 Additional comments (1)
src/app/(core)/v/[slug]/player.tsx (1)

Line range hint 1-359: Overall assessment: Significant improvements with minor refinements needed

The changes to the VodPlayer component and its supporting functions greatly enhance the functionality of marker parsing and display. The new functions parseOffsetValue, parseMetadataFromMarker, and parseMarkers provide a robust foundation for handling various marker formats and generating useful data.

Key improvements:

  1. Enhanced time format parsing
  2. Structured marker categorization
  3. Comprehensive marker processing with YouTube chapter and CSV generation
  4. Improved UI rendering of marker details

To further refine the implementation, consider addressing the following:

  1. Optimize the parseMetadataFromMarker function
  2. Fix the YouTube chapters format
  3. Improve type safety by avoiding any types
  4. Refactor the nested ternary operator for better readability

These changes will result in a more maintainable, efficient, and type-safe implementation.

🧰 Tools
🪛 Biome

[error] 24-24: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

Comment on lines +73 to +136
function parseMarkers(props: { vod: VOD; offset?: { totalSeconds: number } }) {
const videoDuration = getDurationFromTwitchFormat(
(props.vod as any)?.duration ?? "0h0m0s"
);

const mockedMarkers = [
{ position_seconds: 0, id: "start", description: "Intro" },
...props.vod.markers,
];

const OFFSET = props.offset?.totalSeconds ?? 0;

const taggedMarkers = mockedMarkers.map((marker, id) => {
let endTime =
(mockedMarkers[id + 1]?.position_seconds ??
(videoDuration as duration.Duration)?.asSeconds?.()) - OFFSET;

endTime += EXPORT_BUFFER;

if (endTime < 0) endTime = 1;

const startTime = Math.max(
marker.position_seconds - OFFSET - EXPORT_BUFFER,
0
);

const duration = dayjs
.duration(endTime * 1000 - startTime * 1000)
.format("HH:mm:ss");

const taggedDescription = parseMetadataFromMarker(marker.description);

return {
startTime,
endTime,
duration,
...taggedDescription,
};
});

const filteredMarkers = taggedMarkers.filter(
(m) => m.type === "start" || m.type === "offset"
);

const ytChapters = filteredMarkers.reduce((acc, marker) => {
const timeStr = dayjs
.duration(marker.startTime * 1000)
.format("HH:mm:ss");
return `${acc}${timeStr} ${marker.label}\n`;
}, "");

const csv = filteredMarkers
.map((marker) => {
return `${marker.startTime},${marker.endTime},${marker.label}`;
})
.join("\n");

return {
taggedMarkers,
filteredMarkers,
ytChapters,
csv,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Comprehensive marker processing with minor improvements needed

The parseMarkers function effectively processes video markers, calculates start and end times, and generates YouTube chapter strings and CSV data.

  1. The YouTube chapters format is incorrect. Apply this diff to fix it:
-    return `${acc}${timeStr} ${marker.label}\n`;
+    return `${acc}${marker.startTime} ${marker.label}\n`;
  1. Avoid using any type for props.vod. Consider defining a proper type for the VOD object.

Replace the any type with a proper type definition:

interface VODWithDuration extends VOD {
  duration?: string;
}

function parseMarkers(props: { vod: VODWithDuration; offset?: { totalSeconds: number } }) {
  // ...
}

These changes will improve type safety and ensure correct YouTube chapter formatting.

Comment on lines +14 to +25
function parseOffsetValue(value: string): number | undefined {
// if there are no colons, assume its seconds
if (/^\d+$/.test(value)) return parseInt(value, 10);

// Supports HH:MM:SS, MM:SS, SS
// If it's not in the format, return undefined
if (!/^([0-5]?[0-9]:){0,2}[0-5][0-9]$/.test(value)) return undefined;

return value
.split(":")
.reduce((acc, cur) => (acc = acc * 60 + parseInt(cur, 10)), 0);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Good implementation of time parsing, with a minor improvement needed

The parseOffsetValue function effectively handles various time formats (seconds, MM:SS, HH:MM:SS) and converts them to total seconds. The use of regex for input validation is appropriate.

However, there's a minor issue in the reduce function. Apply this diff to remove the unnecessary assignment:

-    .reduce((acc, cur) => (acc = acc * 60 + parseInt(cur, 10)), 0);
+    .reduce((acc, cur) => acc * 60 + parseInt(cur, 10), 0);

This change improves clarity and avoids potential side effects from assignments in expressions.

📝 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
function parseOffsetValue(value: string): number | undefined {
// if there are no colons, assume its seconds
if (/^\d+$/.test(value)) return parseInt(value, 10);
// Supports HH:MM:SS, MM:SS, SS
// If it's not in the format, return undefined
if (!/^([0-5]?[0-9]:){0,2}[0-5][0-9]$/.test(value)) return undefined;
return value
.split(":")
.reduce((acc, cur) => (acc = acc * 60 + parseInt(cur, 10)), 0);
}
function parseOffsetValue(value: string): number | undefined {
// if there are no colons, assume its seconds
if (/^\d+$/.test(value)) return parseInt(value, 10);
// Supports HH:MM:SS, MM:SS, SS
// If it's not in the format, return undefined
if (!/^([0-5]?[0-9]:){0,2}[0-5][0-9]$/.test(value)) return undefined;
return value
.split(":")
.reduce((acc, cur) => acc * 60 + parseInt(cur, 10), 0);
}
🧰 Tools
🪛 Biome

[error] 24-24: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

@t3dotgg t3dotgg merged commit c7a00eb into main Oct 17, 2024
5 checks passed
@t3dotgg t3dotgg deleted the theo/filtering branch October 17, 2024 02:21
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