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

v2.8.0 #457

Merged
merged 47 commits into from
Nov 19, 2024
Merged

v2.8.0 #457

merged 47 commits into from
Nov 19, 2024

Conversation

EvanNotFound
Copy link
Owner

@EvanNotFound EvanNotFound commented Nov 18, 2024

resolve #450
resolve #440
resolve #364

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new GitHub Actions workflow to automate building JavaScript and CSS files.
    • Added French translations for various user interface elements to enhance localization.
    • Implemented a local search feature with a user-friendly interface.
    • Added a new progress bar component for improved user feedback during navigation.
    • Enhanced the category list with interactive toggle functionality.
    • Introduced a masonry layout for displaying images and essays.
    • Added functionality for a dynamic table of contents (TOC) with toggle capability.
    • Introduced a bookmark navigation system that highlights active sections based on scroll position.
  • Bug Fixes

    • Resolved issues with the rendering of comments and pagination controls.
  • Documentation

    • Updated configuration files for clarity regarding available CDN providers.
  • Chores

    • Updated project dependencies and scripts for improved build processes.

RocketMaDev and others added 30 commits November 12, 2024 01:13
This commit relates to #437. The hljs style for DIFF language apply
red/green color to background, and the code color is still white,
causing it unreadable. By applying color to foreground to make diff
block readable.
This commit implements a build process to minify and optimize JavaScript and CSS files. The main changes include:

- Added new build scripts in package.json to minify JS and CSS
- Created a new build.js script to handle JS minification
- Updated .gitignore to exclude build output files
- Added new dependencies for minification (terser, glob-promise)
- Updated file paths in layouts to reference new minified files
- Added GitHub Actions workflow to automatically build on push
- Generated minified JS and CSS files in source/build directory

The build process now minifies and optimizes JS and CSS files, improving performance and reducing file sizes. The GitHub Actions workflow ensures the build files are kept up-to-date automatically.
- Change build output paths from build/js and build/css to source/build/js
  and source/build/css
- Update git add and commit message to reflect new build paths
- Ensure CI skips when committing build artifacts
• Replace git push command with a more secure version using GITHUB_TOKEN
• Ensure proper authentication when pushing changes to the repository
• Maintain the existing commit message and skip CI functionality
- Remove SUSTech CDN provider option from configuration
- Delete SUSTech CDN URL from CDN providers list
- Remove SUSTech-related status checks and logging
- Update comments and documentation to reflect changes
• Renamed the workflow from "JS and CSS Build" to "Build JS and CSS"
• This change improves clarity and consistency in the CI pipeline naming
- Add path filters to trigger workflow only on relevant file changes
- Limit workflow execution to changes in 'source/js', 'source/css', and
  'source/build' directories
- Update package.json version from 2.7.3 to 2.7.4
- Update package-lock.json version from 2.7.3 to 2.7.4
- Adjust link icon styling for better visual alignment
- Improve link underline offset and color for better readability
- Update Tailwind CSS classes for consistent styling
Fix unreadable code block color for diff
…nglish

- Implement pangu.js functionality for improved readability
- Add script loading in layout/_partials/scripts.ejs
- Create new pangu.js plugin file with spacing logic
- Include minified version and source map for production use
- Replaced @import with @require for better performance
- Grouped related styles using wildcard imports
- Removed redundant imports and reorganized file structure
- Simplified import statements for better maintainability
- Replace @require with @import for comment system stylesheets
- Move Tailwind directives to a separate source file
- Update build scripts to use new Tailwind source file
- Remove Tailwind directives from main style.styl file
- Move box shadow and ellipsis styles to redefine-theme.styl
- Relocate page title header styles to page.styl
- Remove unused styles from basic.styl
- Clean up style.styl by removing redundant code
- Delete empty text section from basic.styl file
- Clean up unnecessary comments and whitespace
• Change @import to @require in comment.styl for better performance
• Replace redefine-box-shadow-flat with shadow-redefine-flat for consistency
• Update date formatting in essays widget for improved localization
• Add new color variables for UI components in tailwind.config.js
• Restructure theme-related styles by creating separate files
• Introduce new color variables for light and dark modes
• Update CSS to use new color variables and improve theme switching
• Replaced specific class selectors with a more generic "markdown-body" class
• Simplified the code by removing redundant class-specific spacing calls
• Maintains the functionality of adding space between Chinese and English text
- Remove media queries for prefers-color-scheme
- Retain light-mode and dark-mode class selectors
- Streamline root color definitions
- Add configuration option for default color mode
- Set root color based on user-defined default mode
- Fallback to light mode if configuration is not set to dark
• Introduce getPagePartialPath helper for dynamic partial selection
• Add getPageData and getPageTitle helpers for centralized page info
• Refactor page.ejs to use new helpers for cleaner rendering logic
• Create metaHelpers.js for generating SEO-friendly meta tags
• Adjust layout.ejs for consistent indentation and formatting
• Added bookmark navigation functionality with smooth scrolling
• Implemented active state highlighting for bookmark nav items
• Created a new SVG placeholder image for bookmarks
• Updated bookmarks layout to include navigation data attributes
• Integrated bookmarkNav.js script for handling navigation logic
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 (11)
source/css/layout/bookmarks.styl (1)

1-8: Consider adding transition for smoother state changes.

The transform scale effect would benefit from a smooth transition when the active state changes.

Consider adding a transition property to the base class:

 .bookmark-nav-item {
+  transition: transform 0.2s ease-in-out, background-color 0.2s ease-in-out, color 0.2s ease-in-out, border-color 0.2s ease-in-out;
   &.active {
     background-color: var(--second-background-color);
     color: var(--primary-color);
     border-color: var(--second-background-color);
     transform: scale(1.02);
   }
 }
source/build/js/layouts/bookmarkNav.js (2)

1-1: Enhance error handling and debugging

The current error handling is too broad and silently fails. Consider:

  1. Adding specific error handling for Swup initialization
  2. Logging errors in development environment
  3. Adding proper type checking for parameters
// Add error handling utilities
const DEBUG = process.env.NODE_ENV === 'development';

function handleSwupError(error) {
  if (DEBUG) {
    console.warn('Swup initialization failed:', error.message);
  }
  // Optionally report to error tracking service
}

// Update the error handling
try {
  if (typeof swup === 'undefined') {
    throw new Error('Swup is not loaded');
  }
  swup.hooks.on('page:view', initBookmarkNav);
} catch (error) {
  handleSwupError(error);
}
🧰 Tools
🪛 Biome

[error] 1-1: 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)


[error] 1-1: 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)


[error] 1-1: 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)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.

(lint/complexity/noUselessThisAlias)


1-1: Optimize scroll performance

While throttling is implemented, there are additional optimizations that could improve performance:

  1. Use requestAnimationFrame for smoother animations
  2. Implement passive scroll listeners
  3. Cache DOM measurements
function initBookmarkNav() {
  const navItems = document.querySelectorAll('.bookmark-nav-item');
  const sections = document.querySelectorAll('section[id]');
  
  // Cache section positions
  let sectionPositions = [];
  
  function updateSectionPositions() {
    sectionPositions = Array.from(sections).map(section => ({
      id: section.id,
      top: section.offsetTop,
      height: section.offsetHeight
    }));
  }

  function setActiveNavItem() {
    requestAnimationFrame(() => {
      const scrollY = window.scrollY + 100;
      const currentSection = sectionPositions.find(
        section => scrollY >= section.top && scrollY < section.top + section.height
      );

      navItems.forEach(item => {
        const isActive = currentSection && item.dataset.category === currentSection.id;
        item.classList.toggle('bg-second-background-color', isActive);
      });
    });
  }

  if (navItems.length && sections.length) {
    // Update positions on load and resize
    updateSectionPositions();
    window.addEventListener('resize', throttle(updateSectionPositions, 250));
    
    // Use passive scroll listener
    window.addEventListener('scroll', throttle(setActiveNavItem, 100), { passive: true });
    setActiveNavItem();
  }
}
🧰 Tools
🪛 Biome

[error] 1-1: 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)


[error] 1-1: 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)


[error] 1-1: 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)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.

(lint/complexity/noUselessThisAlias)

source/js/layouts/bookmarkNav.js (2)

1-5: Consider namespacing the CSS classes

The selector .bookmark-nav-item could potentially conflict with other components. Consider prefixing it with a theme-specific namespace (e.g., redefine-bookmark-nav-item).


42-52: Remove commented code

Instead of keeping commented code in the codebase:

  1. If the functionality is planned for future implementation, create a GitHub issue to track it
  2. If it's no longer needed, remove it entirely
source/js/main.js (2)

51-52: Consider adding conditional initialization and error handling

While the placement of initBookmarkNav() in the initialization sequence is logical, consider:

  1. Adding a theme configuration check for consistency with other feature initializations
  2. Adding error handling to gracefully handle cases where bookmark elements don't exist

Here's a suggested approach:

-    initBookmarkNav();
+    if (theme.bookmark && theme.bookmark.enable === true) {
+      try {
+        initBookmarkNav();
+      } catch (e) {
+        console.warn('Failed to initialize bookmark navigation:', e);
+      }
+    }

Pangu.js is properly integrated but needs initialization in main.js

The verification shows that pangu.js is correctly set up in the theme:

  • It's implemented in source/js/plugins/pangu.js
  • It's conditionally loaded in scripts.ejs when theme.articles.pangu_js is enabled
  • However, it's missing from the initialization sequence in main.js

To complete the integration, import and initialize pangu.js in main.js:

  • Add import: import initPanguJS from "./plugins/pangu.js";
  • Add initialization in main.refresh(): initPanguJS();
🔗 Analysis chain

Line range hint 1-89: Verify pangu.js integration from Issue #450

The PR objectives mention integrating pangu.js for improved Chinese-English text spacing, but I don't see its initialization in the main.js file. This might be an oversight or implemented elsewhere.

Let's verify if pangu.js is integrated in other files:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for pangu.js integration
echo "Searching for pangu.js imports or usage..."
rg -l 'pangu' 

# Search for any new JS files that might contain pangu integration
echo "Checking for new JS files..."
git diff --name-only | grep '\.js$'

Length of output: 414


Script:

#!/bin/bash
# Check the content of pangu.js plugin
echo "=== Content of source/js/plugins/pangu.js ==="
cat source/js/plugins/pangu.js

# Check if pangu.js is imported in any other files
echo -e "\n=== Files importing pangu.js ==="
rg -l "import.*pangu" --type js

# Check the scripts.ejs template for pangu integration
echo -e "\n=== Content of layout/components/scripts.ejs ==="
cat layout/components/scripts.ejs

Length of output: 2799

scripts/helpers/page-helpers.js (2)

151-151: Remove commented out code

This commented line appears to be unused and should be removed for cleaner code.

-	// const config = type ? pageData[type] : null;

139-153: Add error handling for undefined page types

The getPageTitle function could benefit from better error handling when the page type is undefined.

 hexo.extend.helper.register("getPageTitle", function (page) {
 	const pageData = this.getPageData(page);
 	let type = null;
 
 	// Determine the type based on page properties
 	if (this.is_home()) type = "home";
 	else if (this.is_archive()) type = "archive";
 	else if (this.is_post()) type = "post";
 	else {
-		type = pageData.type;
+		type = pageData?.type;
+		if (!type) {
+			hexo.log.warn(`Unknown page type for: ${page.path}`);
+		}
 	}
 
-	// const config = type ? pageData[type] : null;
 	return page.title || this.__(type) || "Untitled";
 });
source/build/css/tailwind.css (2)

1-1: Generated file - ensure source is version controlled

This is an auto-generated Tailwind CSS file. To maintain consistency and avoid merge conflicts:

  1. The source Tailwind configuration file should be version controlled
  2. This generated file should be added to .gitignore
  3. The build process should regenerate this file during CI/CD
🧰 Tools
🪛 Biome

[error] 1-1: Duplicate font names are redundant and unnecessary: Emoji

Remove duplicate font names within the property

(lint/suspicious/noDuplicateFontNames)


1-1: Remove duplicate Emoji font names

The font family declaration contains duplicate Emoji font names which are redundant. Consider consolidating the Emoji fonts to remove duplicates.

-font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji
+font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Symbol,Noto Color Emoji
🧰 Tools
🪛 Biome

[error] 1-1: Duplicate font names are redundant and unnecessary: Emoji

Remove duplicate font names within the property

(lint/suspicious/noDuplicateFontNames)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 824397c and 28c161b.

⛔ Files ignored due to path filters (3)
  • source/build/js/layouts/bookmarkNav.js.map is excluded by !**/*.map
  • source/build/js/main.js.map is excluded by !**/*.map
  • source/images/bookmark-placeholder.svg is excluded by !**/*.svg
📒 Files selected for processing (9)
  • layout/components/scripts.ejs (1 hunks)
  • layout/pages/bookmarks/bookmarks.ejs (1 hunks)
  • scripts/helpers/page-helpers.js (1 hunks)
  • source/build/css/tailwind.css (1 hunks)
  • source/build/js/layouts/bookmarkNav.js (1 hunks)
  • source/build/js/main.js (1 hunks)
  • source/css/layout/bookmarks.styl (1 hunks)
  • source/js/layouts/bookmarkNav.js (1 hunks)
  • source/js/main.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • layout/components/scripts.ejs
  • layout/pages/bookmarks/bookmarks.ejs
  • source/build/js/main.js
🧰 Additional context used
🪛 Biome
source/build/css/tailwind.css

[error] 1-1: Duplicate font names are redundant and unnecessary: Emoji

Remove duplicate font names within the property

(lint/suspicious/noDuplicateFontNames)

source/build/js/layouts/bookmarkNav.js

[error] 1-1: 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)


[error] 1-1: 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)


[error] 1-1: 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)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.

(lint/complexity/noUselessThisAlias)

source/js/layouts/bookmarkNav.js

[error] 16-16: 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)


[error] 12-12: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.

(lint/complexity/noUselessThisAlias)

🔇 Additional comments (7)
source/css/layout/bookmarks.styl (1)

1-8: LGTM! Clean and maintainable implementation.

The styling implementation follows best practices with proper use of CSS variables for theming and a clean nesting structure.

source/js/main.js (1)

9-9: LGTM! Import statement follows established patterns

The import statement is well-placed among other layout-related imports and follows the consistent pattern used throughout the file.

scripts/helpers/page-helpers.js (4)

1-10: Well-structured documentation with clear explanations!

The documentation effectively explains the purpose and structure of the pageData object, making it easy for other developers to understand and maintain.


79-84: Successfully implements tools page template compatibility

The bookmarks configuration properly implements the tools page template compatibility requested in issue #440 by:

  1. Including "tools" in the types array
  2. Using "raw" layout consistent with hexo-theme-keep

12-91: Runtime validation for pageData structure is still needed

The previous review comment about adding runtime validation for the pageData structure remains valid. This would help prevent potential issues with empty arrays and invalid configurations.


110-137: Simplification of getPagePartialPath logic is still recommended

The previous review comment about simplifying the getPagePartialPath logic and improving error handling remains valid. The current implementation has complex nested conditions that could be simplified.

source/build/css/tailwind.css (1)

Line range hint 1-1024: Verify custom color scheme implementation

The file implements a comprehensive color scheme using CSS custom properties. Ensure that all color variables are properly defined in both light and dark modes, and that they align with the design system.

🧰 Tools
🪛 Biome

[error] 1-1: Duplicate font names are redundant and unnecessary: Emoji

Remove duplicate font names within the property

(lint/suspicious/noDuplicateFontNames)

@@ -0,0 +1,2 @@
export default function initBookmarkNav(){const t=document.querySelectorAll(".bookmark-nav-item"),e=document.querySelectorAll("section[id]");function setActiveNavItem(){const o=window.scrollY+100;let n=null;e.forEach((t=>{const e=t.offsetTop,c=t.offsetHeight;o>=e&&o<e+c&&(n=t)})),t.forEach((t=>{t.classList.remove("bg-second-background-color"),n&&t.getAttribute("data-category")===n.getAttribute("id")&&t.classList.add("bg-second-background-color")}))}t.length&&e.length&&(window.addEventListener("scroll",function throttle(t,e){let o;return function(){const n=arguments,c=this;o||(t.apply(c,n),o=!0,setTimeout((()=>o=!1),e))}}(setActiveNavItem,100)),setActiveNavItem())}try{swup.hooks.on("page:view",initBookmarkNav)}catch(t){}document.addEventListener("DOMContentLoaded",initBookmarkNav);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve code readability and maintainability

The code is minified which makes it difficult to maintain. Consider:

  1. Keeping the source code unminified in the repository
  2. Using a build process to generate minified files
  3. Adding proper documentation for the navigation logic

Here's a suggested unminified and documented version:

/**
 * Initializes the bookmark navigation system
 * @function initBookmarkNav
 */
export default function initBookmarkNav() {
  const navItems = document.querySelectorAll('.bookmark-nav-item');
  const sections = document.querySelectorAll('section[id]');

  /**
   * Updates the active navigation item based on scroll position
   */
  function setActiveNavItem() {
    const scrollY = window.scrollY + 100; // Add offset for better UX
    let currentSection = null;

    sections.forEach((section) => {
      const sectionTop = section.offsetTop;
      const sectionHeight = section.offsetHeight;

      if (scrollY >= sectionTop && scrollY < sectionTop + sectionHeight) {
        currentSection = section;
      }
    });

    navItems.forEach((item) => {
      item.classList.remove('bg-second-background-color');
      if (currentSection && item.dataset.category === currentSection.id) {
        item.classList.add('bg-second-background-color');
      }
    });
  }

  if (navItems.length && sections.length) {
    // Throttle scroll events for better performance
    const throttledSetActive = throttle(setActiveNavItem, 100);
    window.addEventListener('scroll', throttledSetActive);
    setActiveNavItem(); // Initial call
  }
}

/**
 * Throttle function to limit the rate at which a function can fire
 * @param {Function} func - Function to throttle
 * @param {number} limit - Time limit in milliseconds
 */
function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// Initialize on page load and Swup page:view events
try {
  swup.hooks.on('page:view', initBookmarkNav);
} catch (error) {
  // Swup might not be available
}

document.addEventListener('DOMContentLoaded', initBookmarkNav);
🧰 Tools
🪛 Biome

[error] 1-1: 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)


[error] 1-1: 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)


[error] 1-1: 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)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.

(lint/complexity/noUselessThisAlias)

Comment on lines +21 to +40
function setActiveNavItem() {
const fromTop = window.scrollY + 100;
let currentSection = null;

sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.offsetHeight;

if (fromTop >= sectionTop && fromTop < sectionTop + sectionHeight) {
currentSection = section;
}
});

navItems.forEach(item => {
item.classList.remove('bg-second-background-color');
if (currentSection && item.getAttribute('data-category') === currentSection.getAttribute('id')) {
item.classList.add('bg-second-background-color');
}
});
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve scroll position calculation and performance

Several improvements can be made to enhance reliability and performance:

  1. The hardcoded offset (100px) should be configurable to accommodate different header heights
  2. Consider using IntersectionObserver for better performance with many sections
+const SCROLL_OFFSET = 100; // Consider making this configurable via theme settings
+
 function setActiveNavItem() {
-  const fromTop = window.scrollY + 100;
+  const fromTop = window.scrollY + SCROLL_OFFSET;
   let currentSection = null;

   sections.forEach(section => {

Would you like me to provide an alternative implementation using IntersectionObserver?

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +8 to +19
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify throttle implementation

The throttle function can be improved by:

  1. Avoiding assignment in the setTimeout expression
  2. Using arrow functions to preserve this context
 function throttle(func, limit) {
   let inThrottle;
-  return function() {
-    const args = arguments;
-    const context = this;
+  return (...args) => {
     if (!inThrottle) {
-      func.apply(context, args);
+      func(...args);
       inThrottle = true;
-      setTimeout(() => inThrottle = false, limit);
+      setTimeout(() => {
+        inThrottle = false;
+      }, limit);
     }
   }
 }
📝 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 throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
}
}
function throttle(func, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
}
}
🧰 Tools
🪛 Biome

[error] 16-16: 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)


[error] 12-12: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.

(lint/complexity/noUselessThisAlias)

Comment on lines +61 to +65
try {
swup.hooks.on("page:view", initBookmarkNav);
} catch (e) {}

document.addEventListener("DOMContentLoaded", initBookmarkNav);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling and event listener management

Current implementation has several issues:

  1. Empty catch block silently fails
  2. No cleanup of event listeners
  3. Multiple initialization points without deduplication
+let isInitialized = false;
+
+function cleanup() {
+  window.removeEventListener('scroll', throttle(setActiveNavItem, 100));
+}
+
+function init() {
+  if (isInitialized) return;
+  initBookmarkNav();
+  isInitialized = true;
+}
+
 try {
-  swup.hooks.on("page:view", initBookmarkNav);
-} catch (e) {}
+  swup.hooks.on("page:view", init);
+  swup.hooks.on("page:leave", cleanup);
+} catch (e) {
+  console.warn('Swup not initialized:', e.message);
+}
 
-document.addEventListener("DOMContentLoaded", initBookmarkNav);
+document.addEventListener("DOMContentLoaded", init);

Committable suggestion skipped: line range outside the PR's diff.

- Add transition class to main content body for improved animation
- Implement new CSS transitions for fade and content body movements
- Adjust transition timing and effects for smoother page loading experience
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: 0

🧹 Outside diff range and nitpick comments (3)
layout/page.ejs (1)

13-35: Consider adding fallback for dynamic viewport height.

The layout structure is well-organized with clear separation of concerns. However, the min-h-dvh property might need a fallback for older browsers.

Consider adding a fallback:

-<div class="main-content-container flex flex-col justify-between min-h-dvh">
+<div class="main-content-container flex flex-col justify-between min-h-screen min-h-dvh">
source/css/layout/page.styl (2)

3-8: Consider adding responsive font sizes

While the styles look good, the fixed font size of 3.2rem might be too large on mobile devices. Consider adding responsive adjustments using Stylus mixins.

 .page-title-header
   font-size 3.2rem
   line-height 1
   font-weight bold
   color var(--second-text-color)
   margin 6px 0 36px 0
+  
+  +redefine-tablet()
+    font-size 2.8rem
+    margin 4px 0 28px 0
+
+  +redefine-mobile()
+    font-size 2.4rem
+    margin 3px 0 24px 0

150-173: Add support for reduced motion preferences

The transition animations look good and provide smooth page transitions. However, consider adding support for users who prefer reduced motion.

Add this media query to respect user preferences:

 html.is-animating
   .transition-fade
     opacity 0
   
   .transition-main-content-body
     transform translateY(20px)
     opacity 0
+
+@media (prefers-reduced-motion: reduce)
+  .transition-main-content-body,
+  html.is-changing .transition-main-content-body,
+  html.is-animating .transition-main-content-body
+    transform none
+    transition none
+
+  .transition-fade,
+  html.is-changing .transition-fade,
+  html.is-animating .transition-fade
+    transition none
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 28c161b and 0847f0e.

📒 Files selected for processing (2)
  • layout/page.ejs (1 hunks)
  • source/css/layout/page.styl (2 hunks)
🔇 Additional comments (6)
layout/page.ejs (5)

1-4: LGTM! Improved organization of header components.

The relocation of progress bar and preloader components to components/header/ follows a more logical directory structure, making the codebase more maintainable.


7-11: LGTM! Clear conditional logic for home banner.

The home banner components are now properly organized under pages/home/ with well-structured conditions for different display scenarios.


56-57: LGTM! Clean single-page functionality implementation.

The Swup component is properly organized and maintains the existing single-page functionality.


37-51: Missing pangu.js integration mentioned in issue #450.

While the tools section is well-structured, the PR objective to integrate pangu.js for improved Chinese-English text spacing is not implemented in this file.

Let's check if pangu.js is integrated elsewhere:

#!/bin/bash
# Search for pangu.js integration
echo "Checking for pangu.js in package.json..."
grep -r "pangu" package.json || echo "Not found in package.json"

echo "\nChecking for pangu.js imports or usage..."
rg -l "pangu" --type js --type ejs

Would you like assistance with implementing the pangu.js integration?


1-57: Overall assessment of the changes.

The reorganization of the template structure improves maintainability and follows a more logical directory organization. However, some PR objectives need attention:

  1. ✅ Tools page template structure is in place
  2. ❌ pangu.js integration is missing
  3. ❓ Compatibility with hexo-theme-keep tools page needs verification

Let's verify compatibility with hexo-theme-keep:

✅ Verification successful

Previous concerns have been addressed

The verification shows that:

  1. Tools page structure is properly implemented with dedicated files in layout/pages/post/post-tools.ejs and layout/utils/side-tools.ejs
  2. pangu.js is integrated with both source and build files present (source/js/plugins/pangu.js, source/js/libs/pangu.min.js)
  3. Tools functionality is maintained and organized in a clean structure under source/js/tools/ with all necessary components

The reorganization successfully maintains compatibility while improving the codebase structure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Compare tools page implementation with hexo-theme-keep
echo "Searching for tools page template in hexo-theme-keep..."
rg -l "tools" --type ejs

echo "\nComparing with hexo-theme-keep v4.1.0 structure..."
gh api repos/XPoet/hexo-theme-keep/contents/layout?ref=v4.1.0 | jq -r '.[].path' | grep -i tool

Length of output: 388


Script:

#!/bin/bash
# Let's try a different approach to find tools-related files
echo "Searching for tools-related files..."
fd -e ejs -e js . | rg -i "tool"

echo "\nSearching for tool-related content in EJS files..."
fd -e ejs . -x cat {} | rg -l "tool"

echo "\nSearching for pangu.js integration..."
fd . -e js -e ejs | xargs rg -l "pangu"

Length of output: 1095

source/css/layout/page.styl (1)

1-1: LGTM: Good practice using @require

Using @require instead of @import is the preferred approach in Stylus as it prevents duplicate imports.

- Change class name from 'transition-main-content-body' to 'transition-fade-up'
- Update class name in page.ejs and page.styl files
- Maintain existing transition behavior and styling
- Move transition and animation styles from page.styl to animations.styl
- Add import for animations.styl in style.styl
- Remove redundant animation styles from page.styl
- Add path filters to exclude specific files and directories
- Exclude build directory, minified JS/CSS files, and source maps
- Maintain existing auto-review and auto-reply settings
• Introduce new transition-fade-down class for downward fade animations
• Apply transition-fade-down to home banner content for smoother loading
• Ensure consistency with existing transition-fade and transition-fade-up
@EvanNotFound EvanNotFound merged commit 8d2a94a into main Nov 19, 2024
3 checks passed
Copy link

This pull request has been deployed to Vercel.

Latest commit: e22b67c
✅ Preview: https://redefine-preview-pr-457.vercel.app
🔍 Inspect: https://vercel.com/evanovation/hexo-theme-redefine/BYhKj6wHnGF3xvY2jydbyTdD9Hdu

View Workflow Logs

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