Skip to content

Simplify markdown without groups - #50

Merged
AnthonyRonning merged 1 commit into
masterfrom
markdown-regex-simplify
Apr 10, 2025
Merged

AnthonyRonning merged 1 commit into
masterfrom
markdown-regex-simplify

Conversation

@AnthonyRonning

@AnthonyRonning AnthonyRonning commented Apr 10, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Refactor
    • Improved text processing to better distinguish code blocks from inline formatting. This update ensures that while code snippets remain intact, surrounding text now converts escaped characters into the correct display style, resulting in a more reliable rendering of formatted content for users.

@coderabbitai

coderabbitai Bot commented Apr 10, 2025 •

Copy link
Copy Markdown

Walkthrough

The changes refactor the escapeBrackets function in the Markdown component. The new implementation extracts code blocks from the input using a dedicated regular expression and replaces them with placeholders. It then processes escaped square brackets and parentheses separately, converting them to LaTeX display ($$...$$) and inline ($...$) formats, respectively. Finally, the original code blocks are restored into the input. These modifications improve the structure of the code by separating concerns and enhancing maintainability.

Changes

Files Change Summary
frontend/src/components/markdown.tsx Refactored the escapeBrackets function by introducing a two-step process: isolating code blocks via placeholders and then processing escaped square brackets and parentheses into LaTeX display and inline formats. Code blocks are restored after conversions.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant Function as escapeBrackets
    Caller->>Function: Call with input text
    Function->>Function: Identify code blocks (using codeBlockPattern)
    Function->>Function: Replace code blocks with placeholders
    Function->>Function: Convert escaped square brackets to $$...$$ (squareBracketPattern)
    Function->>Function: Convert escaped round brackets to $...$ (roundBracketPattern)
    Function->>Function: Restore code blocks from placeholders
    Function->>Caller: Return processed text
Loading

Poem

Hop, skip, and jump with glee,
A rabbit sings a tune so free,
Code blocks safely tucked away,
As LaTeX blooms in bright display,
Brackets dance in lines so neat,
A joyful revision, oh what a treat!
🐇💻✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Apr 10, 2025 •

Copy link
Copy Markdown

Deploying maple with  Cloudflare Pages  Cloudflare Pages

Latest commit: 1847b6c
Status: ✅  Deploy successful!
Preview URL: https://e06c4faa.maple-ca8.pages.dev
Branch Preview URL: https://markdown-regex-simplify.maple-ca8.pages.dev

View logs

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

PR Summary

This PR refactors the escapeBrackets function in the markdown component to improve code clarity by breaking down complex regex operations into discrete steps.

  • Replaced a single complex regex with a three-step approach: protecting code blocks with placeholders, processing LaTeX notation, then restoring code blocks
  • Added clear pattern variables (codeBlockPattern, squareBracketPattern, roundBracketPattern) to improve readability
  • Implemented a placeholder system using __CODE_BLOCK_${i}__ format to temporarily store code blocks during processing
  • Separated LaTeX display mode (\[...\] → $$...$$) and inline mode (\(...\) → $...$) transformations into distinct operations
  • Used array-based storage for code blocks rather than complex regex capture groups

1 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings | Greptile

@AnthonyRonning
AnthonyRonning force-pushed the markdown-regex-simplify branch from 4ccbea1 to 1847b6c Compare April 10, 2025 17:16

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 4

🛑 Comments failed to post (4)
frontend/src/components/markdown.tsx (4)

120-122: ⚠️ Potential issue

Add type annotation to forEach parameter.

The TypeScript linter is flagging the implicit any[] type for codeBlocks. Explicitly typing the parameter will resolve this.

Apply this fix:

- codeBlocks.forEach(function (block, i) {
+ codeBlocks.forEach(function (block: string, i: number) {
    result = result.replace(`__CODE_BLOCK_${i}__`, block);
  });
📝 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.

  codeBlocks.forEach(function (block: string, i: number) {
    result = result.replace(`__CODE_BLOCK_${i}__`, block);
  });
🧰 Tools
🪛 GitHub Actions: Desktop App CI

[error] 120-120: Variable 'codeBlocks' implicitly has an 'any[]' type.


109-111: ⚠️ Potential issue

Remove unused parameter to fix linting error.

The match parameter in the replacement function is declared but never used, causing a linting error.

Apply this fix:

- let result = textWithoutCode.replace(squareBracketPattern, function (match, content) {
+ let result = textWithoutCode.replace(squareBracketPattern, function (_, content) {
    return `$$${content}$$`;
  });
📝 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.

  let result = textWithoutCode.replace(squareBracketPattern, function (_, content) {
    return `$$${content}$$`;
  });
🧰 Tools
🪛 GitHub Actions: Desktop App CI

[error] 109-109: 'match' is declared but its value is never read.


115-117: ⚠️ Potential issue

Remove unused parameter to fix linting error.

Similarly, the match parameter is unused in this replacement function as well.

Apply this fix:

- result = result.replace(roundBracketPattern, function (match, content) {
+ result = result.replace(roundBracketPattern, function (_, content) {
    return `$${content}$`;
  });
📝 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.

  result = result.replace(roundBracketPattern, function (_, content) {
    return `$${content}$`;
  });
🧰 Tools
🪛 GitHub Actions: Desktop App CI

[error] 115-115: 'match' is declared but its value is never read.


99-105: ⚠️ Potential issue

Add type annotation to eliminate implicit any warnings.

The codeBlocks array is causing TypeScript linting errors because it lacks a type annotation.

Apply this fix:

- const codeBlocks = [];
+ const codeBlocks: string[] = [];
📝 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.

// First, handle code blocks to protect them from processing
  const codeBlockPattern = /
🧰 Tools
🪛 GitHub Actions: Desktop App CI

[error] 101-101: Variable 'codeBlocks' implicitly has type 'any[]' in some locations where its type cannot be determined.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
frontend/src/components/markdown.tsx (3)

108-114: Consider improving the square bracket regex pattern for better readability.

The current pattern \\\[([\s\S]*?[^\\])\\\] is a bit complex with its capturing group that excludes escaped closing brackets. While functional, it could be made more explicit about its intentions.

- const squareBracketPattern = /\\\[([\s\S]*?[^\\])\\\]/g;
+ // Match escaped square brackets \[...\] but avoid matching escaped closing brackets \\]
+ const squareBracketPattern = /\\\[([\s\S]*?[^\\])\\\]/g;

102-105: Consider using a more unique placeholder format to prevent potential collisions.

The current placeholder format __CODE_BLOCK_X__ works but could theoretically conflict with content that happens to contain that exact string.

- return `__CODE_BLOCK_${codeBlocks.length - 1}__`;
+ // Use a more unique identifier with lower collision probability
+ return `__CODE_BLOCK_${Date.now()}_${codeBlocks.length - 1}__`;

Alternatively, you could use a UUID or other guaranteed unique identifier if this is a concern in real-world usage.


101-105: Consider using a Map instead of an array for code block storage.

Using a Map with unique keys would make the relationship between placeholders and original content more explicit, and potentially easier to debug.

- const codeBlocks: string[] = [];
- const textWithoutCode = text.replace(codeBlockPattern, function (match: string) {
-   codeBlocks.push(match);
-   return `__CODE_BLOCK_${codeBlocks.length - 1}__`;
- });
+ const codeBlocks = new Map<string, string>();
+ const textWithoutCode = text.replace(codeBlockPattern, function (match: string) {
+   const id = `__CODE_BLOCK_${codeBlocks.size}__`;
+   codeBlocks.set(id, match);
+   return id;
+ });

You would then need to update the restoration code as well:

- codeBlocks.forEach(function (block: string, i: number) {
-   result = result.replace(`__CODE_BLOCK_${i}__`, block);
- });
+ codeBlocks.forEach(function (block: string, id: string) {
+   result = result.replace(id, block);
+ });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4ccbea1 and 1847b6c.

📒 Files selected for processing (1)
  • frontend/src/components/markdown.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-macos (universal-apple-darwin)
  • GitHub Check: build-linux
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (1)
frontend/src/components/markdown.tsx (1)

98-128: Well-structured refactoring with improved separation of concerns.

The refactored escapeBrackets function now follows a clearer, more maintainable approach by:

  1. First protecting code blocks from processing
  2. Handling square brackets for LaTeX display mode
  3. Processing parentheses for LaTeX inline mode
  4. Restoring code blocks at the end

This separation makes the code more readable and easier to maintain than handling everything in a single regex.

@marksftw

Copy link
Copy Markdown
Collaborator

@coderabbitai Generate a QA test plan for this new feature from a user's perspective.

@coderabbitai

coderabbitai Bot commented Apr 10, 2025

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

To create a thorough QA test plan for this feature, I'll need to understand the code changes in more detail.


🏁 Script executed:

#!/bin/bash
# Get the full content of the changed file
cat frontend/src/components/markdown.tsx

# Check the specific changes made in this PR
git diff HEAD~1 HEAD frontend/src/components/markdown.tsx

Length of output: 6234


@marksftw Here's a comprehensive QA test plan for the markdown simplification feature from a user's perspective:

QA Test Plan: Markdown LaTeX Notation Simplification

1. Basic Functionality Tests

  • Display Mode LaTeX Rendering

    • Enter content with \[...\] notation and verify it renders as LaTeX display mode ($$...$$)
    • Check various mathematical expressions (equations, matrices, fractions)
  • Inline Mode LaTeX Rendering

    • Enter content with \(...\) notation and verify it renders as LaTeX inline mode ($...$)
    • Test inline mathematical expressions within regular text

2. Code Block Preservation Tests

  • Code Block with LaTeX Notation

    • Add code blocks ( ), including LaTeX notation inside them
    • Verify LaTeX notation within code blocks remains unchanged (not processed)
  • Inline Code with LaTeX

    • Add inline code blocks ( ) containing LaTeX notation
    • Ensure LaTeX notation is preserved as plain text within the code

3. Mixed Content Tests

  • Content with Mixed Elements
    • Create documents with a combination of:
      • Regular text
      • LaTeX display and inline notation
      • Code blocks and inline code
      • Other markdown elements (lists, headings, tables)
    • Verify all elements render correctly in relation to each other

4. Edge Case Tests

  • Nested Notation

    • Test LaTeX notation within LaTeX notation
    • Check handling of multiple levels of bracket escaping
  • Special Characters

    • Test with special symbols and Unicode characters within LaTeX notation
    • Verify behavior with dollar signs followed by numbers (should use escapeDollarNumber)
  • Large Documents

    • Test rendering performance with documents containing numerous LaTeX expressions

5. Visual Verification

  • Cross-Browser Testing

    • Test rendering in multiple browsers (Chrome, Firefox, Safari, Edge)
    • Verify consistent appearance across platforms
  • Responsive Testing

    • Check rendering at different screen sizes
    • Verify LaTeX expressions wrap appropriately on narrow screens

6. User Experience Tests

  • Copy-Paste Functionality

    • Test copying LaTeX content and pasting it back
    • Verify the "Copy Code" button works with code blocks containing LaTeX
  • Editing Experience

    • Test typing LaTeX expressions in real-time
    • Verify immediate rendering updates

7. Regression Tests

  • Previous LaTeX Functionality

    • Verify all previously supported LaTeX features still work
    • Ensure no regressions in other markdown rendering capabilities
  • Integration with Other Features

    • Test interaction with other markdown elements (tables, links, images)
    • Verify KaTeX styling properly applies to converted expressions

Test Cases with Examples

  1. Basic LaTeX Display Mode

    \[E = mc^2\]
    
  2. Basic LaTeX Inline Mode

    The formula \(E = mc^2\) is famous.
    
  3. LaTeX in Code Block

    ```
    function latexExample() {
      return '\[E = mc^2\]';
    }
    ```
    
  4. Complex Mixed Content

    # Physics Equations
    
    The famous equation \[E = mc^2\] shows that:
    
    1. Energy (\(E\)) equals mass times speed of light squared
    2. Code example: `console.log('\[E = mc^2\]')`
    
    \[F = G \frac{m_1 m_2}{r^2}\]
    

@marksftw

Copy link
Copy Markdown
Collaborator

Markdown formatting is performing well

@AnthonyRonning
AnthonyRonning merged commit d6e0372 into master Apr 10, 2025
@AnthonyRonning
AnthonyRonning deleted the markdown-regex-simplify branch April 10, 2025 17:35
benthecarman pushed a commit to benthecarman/Maple that referenced this pull request Aug 26, 2026
…le-proxy-sdk-3-6-1-maple-proxy

chore: bump maple-proxy to 0.3.1
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