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

Add replaceAllMetaTags function to replace-meta-tag util #2644

Merged
merged 1 commit into from
Feb 11, 2025

Conversation

VasylMarchuk
Copy link
Collaborator

@VasylMarchuk VasylMarchuk commented Feb 11, 2025

Related to #2607

Brief

In preparation to adding pre-rendering for user & concept pages, this extracts the logic to replace all required OG meta tags from our vercel middleware into app/utils/replace-meta-tag.js, so that it can be reused in prerender functions.

Details

Tests included.

Checklist

  • I've thoroughly self-reviewed my changes
  • I've added tests for my changes, unless they affect admin-only areas (or are otherwise not worth testing)
  • I've verified any visual changes using Percy (add a commit with [percy] in the message to trigger)

Summary by CodeRabbit

  • New Features
    • Streamlined meta tag management now updates your page title, description, and image in one unified step.
    • Enhanced handling of page metadata ensures that previews on search engines and social platforms display the latest, accurate information.

@VasylMarchuk VasylMarchuk added the enhancement New feature or request label Feb 11, 2025
@VasylMarchuk VasylMarchuk self-assigned this Feb 11, 2025
Copy link
Contributor

coderabbitai bot commented Feb 11, 2025

Walkthrough

The pull request introduces a new utility function, replaceAllMetaTags, in the meta tag utility file to sequentially update multiple meta tags in one pass. The middleware is updated to import and use this new function instead of repeatedly invoking the older replaceMetaTag function. The test suite is also enhanced to verify the multi-tag replacement functionality, ensuring that updated meta tag content is correctly applied in the HTML response.

Changes

File(s) Change Summary
app/utils/replace-meta-tag.js, tests/unit/utils/replace-meta-tag-test.ts Added the replaceAllMetaTags function which iterates over meta tag specifications using the existing replaceMetaTag. Tests now validate multiple tag updates and remove the single meta tag existence check.
middleware.js Updated the import and usage of meta tag replacement by switching from replaceMetaTag to replaceAllMetaTags, simplifying the meta tag update process in the HTML response.

Sequence Diagram(s)

sequenceDiagram
    participant M as Middleware
    participant U as replaceAllMetaTags
    participant R as replaceMetaTag

    M->>U: Invoke replaceAllMetaTags(indexFileText, pageTitle, pageDescription, pageImageUrl)
    loop For each meta tag specification
        U->>R: Call replaceMetaTag(text, currentSpec)
        R-->>U: Return updated text
    end
    U-->>M: Return final updated text
Loading

Possibly related PRs

  • feat: add Open Graph image for Amazon Contest #1 #2618: The changes in the main PR, which introduce the replaceAllMetaTags function for updating multiple meta tags, are related to the modifications in the retrieved PR that enhance middleware functionality for generating Open Graph meta tags, as both involve handling meta tags in the middleware.js file.
  • feat: add contest details mapping for dynamic OG metadata #2634: The changes in the main PR, which introduce the replaceAllMetaTags function for updating multiple meta tags, are related to the modifications in the retrieved PR that also involve the middleware handling of metadata, specifically through the use of the getContestDetails function for dynamic metadata assignment.

Suggested reviewers

  • rohitpaulk

Poem

I'm a little rabbit, hopping through the code,
Tweaking meta tags, lightening up the load.
With replaceAllMetaTags I bound with glee,
Updating headers swiftly, as happy as can be!
In a meadow of clean code, my paws now rest—
Joy in each change, and a build that’s truly blessed!
🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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

github-actions bot commented Feb 11, 2025

Test Results

  1 files  ±0    1 suites  ±0   6m 20s ⏱️ -15s
613 tests ±0  572 ✅ ±0  41 💤 ±0  0 ❌ ±0 
628 runs  ±0  587 ✅ ±0  41 💤 ±0  0 ❌ ±0 

Results for commit 9ca1074. ± Comparison against base commit e9ad543.

This pull request removes 1 and adds 1 tests. Note that renamed tests count towards both.
Chrome 132.0 ‑ Unit | Utility | replace-meta-tag: it exists and is a function
Chrome 132.0 ‑ Unit | Utility | replace-meta-tag > replaceAllMetaTags: it overwrites content of all specified meta tags in passed text

♻️ This comment has been updated with latest results.

@VasylMarchuk VasylMarchuk changed the title Add replaceAllMetaTags function to replace-meta-tags util Add replaceAllMetaTags function to replace-meta-tag util Feb 11, 2025
Copy link

codecov bot commented Feb 11, 2025

❌ 1 Tests Failed:

Tests completed Failed Passed Skipped
573 1 572 41
View the full list of 1 ❄️ flaky tests
Chrome 132.0 Integration | Component | code-mirror &gt; Options &gt; filename: it doesn't break the editor when passed

Flake rate in main: 65.62% (Passed 22 times, Failed 42 times)

Stack Traces | 5.04s run time
Test took longer than 5000ms; test timed out.

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

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: 1

🧹 Nitpick comments (2)
app/utils/replace-meta-tag.js (1)

34-44: Add parameter validation and error handling.

While the implementation is clean and efficient, consider adding validation for required parameters and error handling for invalid input.

 export function replaceAllMetaTags(text, pageTitle, pageDescription, pageImageUrl) {
+  if (!text) {
+    throw new Error('text parameter is required');
+  }
+
+  // Use empty string as fallback for optional parameters
+  const title = pageTitle || '';
+  const description = pageDescription || '';
+  const imageUrl = pageImageUrl || '';
+
   return [
-    ['name', 'description', pageDescription], // <meta name="description" content="...">
-    ['property', 'og:title', pageTitle],
-    ['property', 'og:description', pageDescription],
-    ['property', 'og:image', pageImageUrl],
-    ['name', 'twitter:title', pageTitle],
-    ['name', 'twitter:description', pageDescription],
-    ['name', 'twitter:image', pageImageUrl],
+    ['name', 'description', description], // <meta name="description" content="...">
+    ['property', 'og:title', title],
+    ['property', 'og:description', description],
+    ['property', 'og:image', imageUrl],
+    ['name', 'twitter:title', title],
+    ['name', 'twitter:description', description],
+    ['name', 'twitter:image', imageUrl],
   ].reduce((text, args) => replaceMetaTag(text, ...args), text);
 }
tests/unit/utils/replace-meta-tag-test.ts (1)

54-67: Add test cases for edge cases.

While the basic functionality is tested, consider adding test cases for:

  • Empty or invalid input parameters
  • Missing meta tags in input text
  • Malformed meta tags
 module('replaceAllMetaTags', function () {
   test('it overwrites content of all specified meta tags in passed text', function (assert) {
     assert.strictEqual(
       replaceAllMetaTags(
         '<meta property="og:image" content="old image"><meta property="og:title" content="old title"><meta property="og:description" content="old description"><meta name="twitter:image" content="old twitter image">',
         'new title',
         'new description',
         'new image url',
       ),
       '<meta property="og:image" content="new image url"><meta property="og:title" content="new title"><meta property="og:description" content="new description"><meta name="twitter:image" content="new image url">',
       'all old content is replaced with new content',
     );
   });
+
+  test('it handles empty input parameters gracefully', function (assert) {
+    assert.strictEqual(
+      replaceAllMetaTags('<meta property="og:title" content="old title">', '', '', ''),
+      '<meta property="og:title" content="">',
+      'empty parameters result in empty content',
+    );
+  });
+
+  test('it handles missing meta tags in input text', function (assert) {
+    assert.strictEqual(
+      replaceAllMetaTags('<div>no meta tags here</div>', 'title', 'desc', 'img'),
+      '<div>no meta tags here</div>',
+      'text without meta tags remains unchanged',
+    );
+  });
+
+  test('it handles malformed meta tags', function (assert) {
+    assert.strictEqual(
+      replaceAllMetaTags('<meta property="og:title" content="old title" />', 'new title', '', ''),
+      '<meta property="og:title" content="new title" />',
+      'handles self-closing meta tags',
+    );
+  });
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e9ad543 and 3db00d6.

📒 Files selected for processing (3)
  • app/utils/replace-meta-tag.js (1 hunks)
  • middleware.js (2 hunks)
  • tests/unit/utils/replace-meta-tag-test.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (1)
app/utils/replace-meta-tag.js (1)

25-33: LGTM! Documentation is clear and follows JSDoc format.

The documentation clearly describes the function's purpose, parameters, and return value.

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: 0

🧹 Nitpick comments (1)
tests/unit/utils/replace-meta-tag-test.ts (1)

54-67: Add test cases for edge cases.

While the current test case verifies the basic functionality, consider adding test cases for:

  • Missing meta tags
  • Invalid meta tags
  • Empty values for title, description, or image URL
  • Malformed HTML

Here's an example of additional test cases:

 module('replaceAllMetaTags', function () {
   test('it overwrites content of all specified meta tags in passed text', function (assert) {
     assert.strictEqual(
       replaceAllMetaTags(
         '<meta property="og:image" content="old image"><meta property="og:title" content="old title"><meta property="og:description" content="old description"><meta name="twitter:image" content="old twitter image">',
         'new title',
         'new description',
         'new image url',
       ),
       '<meta property="og:image" content="new image url"><meta property="og:title" content="new title"><meta property="og:description" content="new description"><meta name="twitter:image" content="new image url">',
       'all old content is replaced with new content',
     );
   });
+
+  test('it handles missing meta tags gracefully', function (assert) {
+    assert.strictEqual(
+      replaceAllMetaTags(
+        '<meta property="og:title" content="old title">',
+        'new title',
+        'new description',
+        'new image url',
+      ),
+      '<meta property="og:title" content="new title">',
+      'only updates existing meta tags',
+    );
+  });
+
+  test('it handles empty values gracefully', function (assert) {
+    assert.strictEqual(
+      replaceAllMetaTags(
+        '<meta property="og:title" content="old title"><meta property="og:description" content="old description">',
+        '',
+        '',
+        '',
+      ),
+      '<meta property="og:title" content=""><meta property="og:description" content="">',
+      'updates meta tags with empty values',
+    );
+  });
+
+  test('it handles malformed HTML gracefully', function (assert) {
+    assert.strictEqual(
+      replaceAllMetaTags(
+        '<meta property="og:title" content="old title"<meta property="og:description">',
+        'new title',
+        'new description',
+        'new image url',
+      ),
+      '<meta property="og:title" content="new title"<meta property="og:description">',
+      'updates valid meta tags in malformed HTML',
+    );
+  });
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3db00d6 and 9ca1074.

📒 Files selected for processing (3)
  • app/utils/replace-meta-tag.js (1 hunks)
  • middleware.js (2 hunks)
  • tests/unit/utils/replace-meta-tag-test.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/utils/replace-meta-tag.js
🔇 Additional comments (4)
tests/unit/utils/replace-meta-tag-test.ts (2)

1-1: LGTM!

The import statement correctly imports both functions.


5-52: LGTM!

The existing test cases for replaceMetaTag are comprehensive and cover important edge cases.

middleware.js (2)

19-19: LGTM!

The import statement correctly imports the new function.


133-134: LGTM!

The meta tag replacement logic has been simplified and improved by using replaceAllMetaTags. The parameter order is correct, and the code is more maintainable.

Copy link

codecov bot commented Feb 11, 2025

Bundle Report

Changes will increase total bundle size by 278 bytes (0.0%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
client-array-push 36.1MB 278 bytes (0.0%) ⬆️

Affected Assets, Files, and Routes:

view changes for bundle: client-array-push

Assets Changed:

Asset Name Size Change Total Size Change (%)
assets/chunk.*.js 278 bytes 2.44MB 0.01%

Files in assets/chunk.*.js:

  • ./utils/replace-meta-tag.js → Total Size: 2.0kB

@VasylMarchuk VasylMarchuk merged commit f08576e into main Feb 11, 2025
7 checks passed
@VasylMarchuk VasylMarchuk deleted the add-replace-all-meta-tags-util branch February 11, 2025 20:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants