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

新增功能:为 Markdown 内容中的 <del> 标签添加遮罩效果 #464

Open
wants to merge 10 commits into
base: dev
Choose a base branch
from

Conversation

QSlotus
Copy link

@QSlotus QSlotus commented Nov 21, 2024

为 Markdown 内容中的 del 标签添加遮罩效果,可通过配置选项控制删除线内容默认隐藏,悬停时显示。

配置项启用时:
鼠标未悬停:
image
鼠标悬停:
image
Markdown内容:

~~黑幕测试~~

配置项未启用时:
为原删除线效果。

Summary by CodeRabbit

  • New Features

    • Introduced a delete_mask configuration option to enhance the display of deleted content in articles, hiding it by default and revealing it on hover.
    • Added a new filter to process <del> tags in posts based on the delete_mask setting.
  • Style

    • Implemented a new .mask class with hover effects and transitions for improved visual presentation of deleted content.

Copy link

coderabbitai bot commented Nov 21, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduce a new configuration option delete_mask in the _config.yml file, which controls the visibility of content wrapped in <del> tags. A corresponding filter in scripts/filters/delete-mask-handle.js processes these tags based on the configuration. Additionally, new CSS styles for a .mask class are added in source/css/common/markdown.styl to manage the visual presentation of the masked content, enhancing the hover effects and transitions for improved user interaction.

Changes

File Change Summary
_config.yml Added new configuration option delete_mask: false under articles section.
scripts/filters/delete-mask-handle.js Introduced a new filter for after_post_render that modifies <del> tags based on delete_mask option.
source/css/common/markdown.styl Added a new class .mask with styles for hover effects and transitions, affecting <del> tag presentation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Hexo
    participant Filter
    participant CSS

    User->>Hexo: Submit post with <del> tags
    Hexo->>Filter: Trigger after_post_render
    Filter->>Hexo: Check delete_mask configuration
    alt delete_mask is true
        Filter->>Hexo: Wrap <del> content with .mask class
    else delete_mask is false
        Filter->>Hexo: Leave <del> content unchanged
    end
    Hexo->>User: Render post with modified content
    User->>CSS: Hover over <del> content
    CSS->>User: Apply hover effects and transitions
Loading

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.

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.

@QSlotus QSlotus changed the base branch from main to dev November 21, 2024 14:05
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

🧹 Outside diff range and nitpick comments (3)
scripts/filters/delete-mask-handle.js (2)

5-27: Consider performance optimization for large content.

The current implementation processes all content with regex replacement, which might impact performance for large posts.

Consider these optimizations:

  1. Early return if delete_mask is disabled
  2. Quick check for <del> presence before regex processing
  3. Cache compiled regex

Example implementation:

hexo.extend.filter.register('after_post_render', function (data) {
  const deleteMaskEnabled = this.theme.config?.articles?.style?.delete_mask === true;
  
  // Early return if feature is disabled
  if (!deleteMaskEnabled) return data;
  
  // Quick check before expensive regex
  if (!data.content.includes('<del')) return data;
  
  try {
    // Cache compiled regex
    const regPureDelTag = /<del(?:\s+[^>]*)?>((?:(?!<\/?del[\s>])[^])*)<\/del>/g;
    data.content = data.content.replace(regPureDelTag, 
      (_, html) => `<del class="mask">${html}</del>`
    );
  } catch (error) {
    hexo.log.error('Error processing delete masks:', error);
  }
  
  return data;
}, 0);

26-26: Document the priority parameter.

The 0 priority parameter determines when this filter runs relative to other filters. Consider adding a comment explaining this choice.

Add documentation:

  },
+ // Priority 0 ensures this runs at a neutral priority relative to other post-render filters
  0
source/css/common/markdown.styl (1)

213-229: Consider accessibility and RTL support for the mask effect.

The masking implementation looks solid and matches the PR objectives well. However, consider these enhancements:

  1. Add screen reader support:
 del.mask
   text-decoration none !important
+  aria-label "Masked content. Hover to reveal."
   transition .2s cubic-bezier(.25, .46, .45, .94) color, .2s cubic-bezier(.25, .46, .45, .94) background
  1. Add RTL support:
 del.mask
   text-decoration none !important
   transition .2s cubic-bezier(.25, .46, .45, .94) color, .2s cubic-bezier(.25, .46, .45, .94) background
+  [dir="rtl"] &
+    /* Add any RTL-specific adjustments if needed */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eaf1829 and 548723c.

📒 Files selected for processing (3)
  • _config.yml (1 hunks)
  • scripts/filters/delete-mask-handle.js (1 hunks)
  • source/css/common/markdown.styl (2 hunks)
🧰 Additional context used
🪛 Biome
scripts/filters/delete-mask-handle.js

[error] 2-3: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (1)
source/css/common/markdown.styl (1)

336-336: Verify the impact on math formula rendering.

This change to display: inline-block for mjx-container svg appears unrelated to the masking feature. Please verify that this doesn't affect the rendering of mathematical formulas.

✅ Verification successful

Let me check the content of these files to understand the context of MathJax usage and any related styling requirements.


The display: inline-block change for mjx-container svg is safe and actually improves math formula rendering

The change is actually beneficial for math formula rendering. From the context found:

  1. The parent mjx-container already has proper display settings:
    • display: inline for inline formulas
    • display: block with text-align: center for block-level formulas
  2. The inline-block on SVG elements allows them to be centered properly within their containers, as indicated by the code comment.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any math-related test files or documentation
rg -g '!node_modules' -l 'mjx-container|mathjax' .

# Search for any related issues or PRs
gh issue list --search "mjx-container mathjax"
gh pr list --search "mjx-container mathjax"

Length of output: 229


Script:

#!/bin/bash
# Check README and CSS content for MathJax context
echo "=== README.md MathJax section ==="
rg -A 5 -B 5 'mathjax|mjx-container' README.md

echo -e "\n=== markdown.styl MathJax styles ==="
rg -A 5 -B 5 'mjx-container' source/css/common/markdown.styl

# Check if there are any test files or examples with math formulas
echo -e "\n=== Files with math examples ==="
fd -e md -e html . -x rg -l '\$\$|\\\[|\\\(' {} \;

Length of output: 1465

Comment on lines +1 to +4
/* delete mask */

"use strict";

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove redundant 'use strict' directive and consider comment localization.

  1. The 'use strict' directive is redundant in JavaScript modules as they are automatically in strict mode.
  2. Consider using Chinese comments to maintain consistency with the PR title and intended audience.

Apply this diff:

-/* delete mask */
+/* 删除标签遮罩效果 */
-
-"use strict";
📝 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
/* delete mask */
"use strict";
/* 删除标签遮罩效果 */
🧰 Tools
🪛 Biome

[error] 2-3: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

const theme = this.theme;

// 处理del标签的代码
const regPureDelTag = /<del>([^<]*)<\/del>/gim;
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 regex pattern for better HTML compatibility.

The current regex pattern /<del>([^<]*)<\/del>/gim has limitations:

  1. Doesn't handle HTML attributes in <del> tags
  2. Doesn't support nested HTML elements
  3. Case-insensitive flag (i) is unnecessary for HTML tags

Consider using this improved pattern:

-const regPureDelTag = /<del>([^<]*)<\/del>/gim;
+const regPureDelTag = /<del(?:\s+[^>]*)?>((?:(?!<\/?del[\s>])[^])*)<\/del>/g;
📝 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 regPureDelTag = /<del>([^<]*)<\/del>/gim;
const regPureDelTag = /<del(?:\s+[^>]*)?>((?:(?!<\/?del[\s>])[^])*)<\/del>/g;

Comment on lines +13 to +22
data.content = data.content.replace(
regPureDelTag,
function (match, html) {
// 只有在配置为true时才添加mask类
if (theme.config.articles.style.delete_mask === true) {
return `<del class="mask">${html}</del>`;
}
return match;
}
);
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 error handling and theme config validation.

The current implementation lacks error handling and config validation:

  1. No validation of theme.config.articles.style
  2. No error handling for malformed HTML

Consider this safer implementation:

-    data.content = data.content.replace(
-      regPureDelTag,
-      function (match, html) {
-        // 只有在配置为true时才添加mask类
-        if (theme.config.articles.style.delete_mask === true) {
-          return `<del class="mask">${html}</del>`;
-        }
-        return match;
-      }
-    );
+    try {
+      const deleteMaskEnabled = theme.config?.articles?.style?.delete_mask === true;
+      data.content = data.content.replace(
+        regPureDelTag,
+        function (match, html) {
+          // 只有在配置为true时才添加mask类
+          return deleteMaskEnabled ? `<del class="mask">${html}</del>` : match;
+        }
+      );
+    } catch (error) {
+      hexo.log.error('Error processing delete masks:', error);
+      return data;
+    }
📝 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
data.content = data.content.replace(
regPureDelTag,
function (match, html) {
// 只有在配置为true时才添加mask类
if (theme.config.articles.style.delete_mask === true) {
return `<del class="mask">${html}</del>`;
}
return match;
}
);
try {
const deleteMaskEnabled = theme.config?.articles?.style?.delete_mask === true;
data.content = data.content.replace(
regPureDelTag,
function (match, html) {
// 只有在配置为true时才添加mask类
return deleteMaskEnabled ? `<del class="mask">${html}</del>` : match;
}
);
} catch (error) {
hexo.log.error('Error processing delete masks:', error);
return data;
}

@@ -275,6 +275,7 @@ articles:
image_alignment: center # image alignment. left, center
image_caption: false # Whether to display image caption
link_icon: true # Whether to display link icon
delete_mask: false # Add mask effect to <del> tags, hiding content by default and revealing on hover
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Documentation update needed for the new delete_mask feature

The new delete_mask configuration option needs documentation as it's not currently documented in any of the existing files. Please add documentation in the following locations:

  • Add the configuration option to the theme configuration section in README.md
  • Include it in the translated README files (README_zh-CN.md and README_zh-TW.md)
  • Document the feature's behavior and usage in the configuration guide
🔗 Analysis chain

Configuration looks good, but needs documentation update

The new delete_mask configuration option is well-placed under the articles.style section and properly defaults to false for backward compatibility. However, since this introduces a new user-facing feature, it should be documented in the theme's documentation.

Let's verify if the documentation needs to be updated:

Would you like me to help draft the documentation for this new feature? I can prepare:

  1. Configuration guide explaining the delete_mask option
  2. Usage examples with and without the mask effect
  3. Screenshots demonstrating the hover behavior

Let me search for any existing documentation in other potential locations and check for related configuration files to ensure we have a complete picture.


Let me check if there's a dedicated documentation directory or theme-specific documentation files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if documentation exists for the new feature
# Look for any documentation files that might need updating

# Search for potential documentation files
fd -e md -e mdx . | while read -r file; do
  if [[ -f "$file" ]]; then
    echo "Checking $file for existing documentation..."
    rg -i "delete_?mask|del tag|strikethrough" "$file"
  fi
done

# Check if there's a dedicated documentation site
if [[ -f "docs/README.md" ]]; then
  echo "Checking documentation site..."
  rg -i "delete_?mask|del tag|strikethrough" "docs/README.md"
fi

Length of output: 1364


Script:

#!/bin/bash
# Check for documentation in docs directory and theme configuration files
fd -t f -e yml -e yaml . | while read -r file; do
  echo "Checking $file for related configuration..."
  rg -i "delete_?mask|del tag|strikethrough" "$file"
done

# Check for any documentation in Jekyll includes/layouts
fd -t f -e html . "_includes" "_layouts" | while read -r file; do
  echo "Checking template file $file..."
  rg -i "delete_?mask|del tag|strikethrough" "$file"
done

Length of output: 1531


Script:

#!/bin/bash
# Look for theme documentation and configuration files
fd -t d "docs|wiki|documentation" .

# Check for theme-specific documentation files
fd -t f -e md "theme|config|setting|documentation" .

# Check the directory structure to understand the theme organization
ls -la

Length of output: 1728

@EvanNotFound
Copy link
Owner

lgtm,就缺个文档补充了

Copy link

This pull request has been deployed to Vercel.

Latest commit: 548723c
✅ Preview: https://redefine-preview-pr-464.vercel.app
🔍 Inspect: https://vercel.com/evanovation/hexo-theme-redefine/FTQBrw5wkY8UYawJPXAWwfZiNKkN

View Workflow Logs

@QSlotus
Copy link
Author

QSlotus commented Nov 22, 2024

lgtm,就缺个文档补充了

已提pr EvanNotFound/redefine-docs-v2#38
请求合并 @EvanNotFound

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants