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: export as markdown #245

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

Conversation

AmitChauhan63390
Copy link
Contributor

@AmitChauhan63390 AmitChauhan63390 commented Dec 10, 2024

Summary by CodeRabbit

  • New Features
    • Introduced the ability to download data as a Markdown file.
    • Added functionality to convert table data into Markdown format.
  • UI Enhancements
    • New download option for Markdown integrated into the output data section, styled consistently with existing download options.

Copy link

coderabbitai bot commented Dec 10, 2024

Walkthrough

The changes introduce new functionality to the RunContent component in the src/components/molecules/RunContent.tsx file. Two methods, convertToMarkdown and downloadMarkdown, are added to convert table data into Markdown format and facilitate downloading this content as a .md file, respectively. The user interface is updated to include an option for downloading data as Markdown, styled to match existing download options. The core logic for handling data remains unchanged, ensuring a seamless integration of the new features.

Changes

File Path Change Summary
src/components/molecules/RunContent.tsx Added methods: convertToMarkdown for formatting data as Markdown and downloadMarkdown for downloading Markdown content. Updated UI to include a download option for Markdown.

Poem

In the burrow where data flows,
A Markdown path now brightly glows.
With a click, the tables dance,
Downloading dreams, a new chance!
Hopping through code, we celebrate,
For every change, we elevate! 🐇✨


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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 (1)
src/components/molecules/RunContent.tsx (1)

167-171: Improve accessibility and consistency of download options

The Markdown download option should follow accessibility best practices and maintain consistency with other download options.

-<Typography
-  onClick={downloadMarkdown}
->
-  <a style={{ textDecoration: 'none', cursor: 'pointer' }}>Download as Markdown</a>
-</Typography>
+<Typography>
+  <Button
+    component="a"
+    onClick={downloadMarkdown}
+    sx={{ textDecoration: 'none' }}
+    aria-label="Download data as Markdown"
+  >
+    Download as Markdown
+  </Button>
+</Typography>

Consider:

  1. Using Material-UI Button component for better accessibility
  2. Adding proper ARIA labels
  3. Maintaining consistent styling with other download options
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ebb6e3a and 00e3599.

📒 Files selected for processing (1)
  • src/components/molecules/RunContent.tsx (4 hunks)
🔇 Additional comments (1)
src/components/molecules/RunContent.tsx (1)

Line range hint 61-171: Verify table data handling consistency

Let's verify that the table data handling is consistent across all export formats.

✅ Verification successful

Table data handling is consistent across export formats

The code review shows that:

  1. The table data is consistently sourced from row.serializableOutput for all export formats (JSON, CSV, and Markdown)
  2. The conversion functions (convertToCSV and convertToMarkdown) handle the data uniformly:
    • Both use the same columns array for headers
    • Both handle empty/undefined values appropriately
    • Both properly escape special characters (CSV uses JSON.stringify, Markdown escapes pipe characters)
  3. The download implementations follow the same secure pattern using Blob and URL.createObjectURL
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for table data handling patterns across the codebase
echo "Checking table data handling patterns..."
rg -A 5 "serializableOutput" --type typescript

# Look for similar download implementations
echo "Checking download implementations..."
rg -A 10 "download.*Blob" --type typescript

Length of output: 336


Script:

#!/bin/bash
# Search for table data handling patterns across the codebase
echo "Checking table data handling patterns..."
rg -A 5 "serializableOutput"

# Look for similar download implementations
echo "Checking download implementations..."
rg -A 10 "download.*Blob"

# Look for CSV and Markdown conversion functions
echo "Checking data conversion implementations..."
rg -A 10 "convertTo(CSV|Markdown)"

Length of output: 15309

Comment on lines +96 to +107
const downloadMarkdown = () => {
const markdownContent = convertToMarkdown(tableData, columns);
const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8;' });
const url = URL.createObjectURL(blob);

const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "data.md");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
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 cleanup and error handling to downloadMarkdown function

The current implementation might cause memory leaks and doesn't handle potential errors.

 const downloadMarkdown = () => {
-  const markdownContent = convertToMarkdown(tableData, columns);
-  const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8;' });
-  const url = URL.createObjectURL(blob);
+  try {
+    const markdownContent = convertToMarkdown(tableData, columns);
+    const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8;' });
+    const url = URL.createObjectURL(blob);
 
-  const link = document.createElement("a");
-  link.href = url;
-  link.setAttribute("download", "data.md");
-  document.body.appendChild(link);
-  link.click();
-  document.body.removeChild(link);
+    const link = document.createElement("a");
+    link.href = url;
+    link.setAttribute("download", "data.md");
+    document.body.appendChild(link);
+    link.click();
+    document.body.removeChild(link);
+    URL.revokeObjectURL(url);
+  } catch (error) {
+    console.error('Failed to download markdown:', error);
+    // Consider adding user feedback here
+  }
 };

The changes:

  1. Add error handling with try-catch
  2. Clean up the URL object to prevent memory leaks
  3. Consider adding user feedback for errors
📝 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 downloadMarkdown = () => {
const markdownContent = convertToMarkdown(tableData, columns);
const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "data.md");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const downloadMarkdown = () => {
try {
const markdownContent = convertToMarkdown(tableData, columns);
const blob = new Blob([markdownContent], { type: 'text/markdown;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "data.md");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch (error) {
console.error('Failed to download markdown:', error);
// Consider adding user feedback here
}
};

Comment on lines +61 to +81
const convertToMarkdown = (data: any[], columns: string[]): string => {

const headerRow = `| ${columns.join(' | ')} |`;

// Create separator row for Markdown tables
const separatorRow = `| ${columns.map(() => '---').join(' | ')} |`;


const dataRows = data.map(row =>
`| ${columns.map(col => {

const value = row[col];
return value === undefined || value === "" ? "-" :

String(value).replace(/\|/g, '\\|').replace(/\n/g, ' ');
}).join(' | ')} |`
);


return [headerRow, separatorRow, ...dataRows].join('\n');
};
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 the robustness of Markdown conversion

The implementation needs improvements in type safety and data handling:

-const convertToMarkdown = (data: any[], columns: string[]): string => {
+interface TableData {
+  [key: string]: string | number | boolean | null | undefined;
+}
+
+const convertToMarkdown = (data: TableData[], columns: string[]): string => {
   const headerRow = `| ${columns.join(' | ')} |`;
   const separatorRow = `| ${columns.map(() => '---').join(' | ')} |`;
   
   const dataRows = data.map(row => 
     `| ${columns.map(col => {
       const value = row[col];
-      return value === undefined || value === "" ? "-" : 
-             String(value).replace(/\|/g, '\\|').replace(/\n/g, ' ');
+      if (value === null || value === undefined || value === "") {
+        return "-";
+      }
+      return String(value)
+        .replace(/\|/g, '\\|')
+        .replace(/\n/g, ' ')
+        .replace(/\[/g, '\\[')
+        .replace(/\]/g, '\\]')
+        .replace(/\*/g, '\\*')
+        .replace(/_/g, '\\_');
     }).join(' | ')} |`
   );

   return [headerRow, separatorRow, ...dataRows].join('\n');
 };

The changes:

  1. Add proper TypeScript interface for table data
  2. Handle null values explicitly
  3. Escape additional Markdown special characters
  4. Remove unnecessary empty lines
📝 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 convertToMarkdown = (data: any[], columns: string[]): string => {
const headerRow = `| ${columns.join(' | ')} |`;
// Create separator row for Markdown tables
const separatorRow = `| ${columns.map(() => '---').join(' | ')} |`;
const dataRows = data.map(row =>
`| ${columns.map(col => {
const value = row[col];
return value === undefined || value === "" ? "-" :
String(value).replace(/\|/g, '\\|').replace(/\n/g, ' ');
}).join(' | ')} |`
);
return [headerRow, separatorRow, ...dataRows].join('\n');
};
interface TableData {
[key: string]: string | number | boolean | null | undefined;
}
const convertToMarkdown = (data: TableData[], columns: string[]): string => {
const headerRow = `| ${columns.join(' | ')} |`;
const separatorRow = `| ${columns.map(() => '---').join(' | ')} |`;
const dataRows = data.map(row =>
`| ${columns.map(col => {
const value = row[col];
if (value === null || value === undefined || value === "") {
return "-";
}
return String(value)
.replace(/\|/g, '\\|')
.replace(/\n/g, ' ')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/\*/g, '\\*')
.replace(/_/g, '\\_');
}).join(' | ')} |`
);
return [headerRow, separatorRow, ...dataRows].join('\n');
};

@amhsirak amhsirak added Status: In Review This PR is being reviewed Status: Work In Progess This issue/PR is actively being worked on labels Dec 10, 2024
@amhsirak amhsirak changed the title export as markdown feat: export as markdown Dec 10, 2024
@amhsirak amhsirak added the Type: Feature New features label Dec 11, 2024
@amhsirak amhsirak removed the Status: Work In Progess This issue/PR is actively being worked on label Dec 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: In Review This PR is being reviewed Type: Feature New features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants