Skip to content

Add macro for inline badges #109

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Add macro for inline badges #109

wants to merge 2 commits into from

Conversation

JakeSCahill
Copy link
Contributor

This pull request introduces a new badge macro, refactoring of the logic for handling Redpanda Connect and Cloud URLs, and the removal of the enterprise-label macro.

Macro Updates:

  • Added badge macro: A new inline macro was introduced to create badge elements with customizable labels, sizes, and tooltips. This enhances the ability to generate dynamic badges in documentation. (macros/badge.js, macros/badge.jsR1-R21)
  • Removed enterprise-label macro: The enterprise-label macro was removed, simplifying the codebase by eliminating unused functionality. (macros/enterprise-label.js, macros/enterprise-label.jsL1-L11)

Refactoring and Enhancements:

  • Refactored Redpanda Connect and Cloud URL logic: Introduced helper functions isConnectorDocPath and isCloudDoc to streamline and encapsulate logic for identifying documentation paths. Improved logging for missing documentation warnings. (extensions/generate-rp-connect-info.js, extensions/generate-rp-connect-info.jsR118-R169)

Package Metadata:

  • Updated package version: Incremented the version from 4.6.2 to 4.6.3 to reflect the new changes. (package.json, package.jsonL3-R3)
  • Added badge macro to exports: Registered the new badge macro in the package exports for inclusion in the build. (package.json, package.jsonL60-R61)

Copy link

netlify bot commented Jun 20, 2025

Deploy Preview for docs-extensions-and-macros ready!

Name Link
🔨 Latest commit f71ad26
🔍 Latest deploy log https://app.netlify.com/projects/docs-extensions-and-macros/deploys/685a85b5b30e3100082e9d3d
😎 Deploy Preview https://deploy-preview-109--docs-extensions-and-macros.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Copy link
Contributor

coderabbitai bot commented Jun 20, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

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

The changes introduce a new badge macro in macros/badge.js, allowing the generation of customizable badge elements with label, size, and tooltip options. The previously existing enterprise-label macro is removed. The package.json is updated to export the new badge macro and increment the version to 4.6.3. There are also internal refactorings in extensions/generate-rp-connect-info.js to modularize and clarify the logic for detecting documentation URLs and issuing warnings for missing documentation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MacroRegistry
    participant BadgeMacro

    User->>MacroRegistry: Register badge macro
    MacroRegistry->>BadgeMacro: Call register()
    BadgeMacro->>MacroRegistry: Add 'badge' inline macro

    User->>MacroRegistry: Use badge::[label=Beta, size=large, tooltip="..."]
    MacroRegistry->>BadgeMacro: Process macro with attributes
    BadgeMacro->>MacroRegistry: Return styled HTML span
    MacroRegistry->>User: Rendered badge HTML in documentation
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement inline badge macro for section-level badges (DOC-1440)
Macro should allow label customization and optional attributes as described (DOC-1440)
Macro should be registered and exported for use in documentation build system (DOC-1440)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Refactoring and modularization of documentation URL logic in generate-rp-connect-info.js (extensions/generate-rp-connect-info.js) These changes are not mentioned in the objectives of DOC-1440, which is focused solely on the badge macro.

Possibly related PRs

Suggested reviewers

  • mihaitodor

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this 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.

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
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)
macros/badge.js (2)

1-1: Remove redundant 'use strict' directive.

The 'use strict' directive is unnecessary in ES modules as they are automatically in strict mode.

-'use strict';

5-5: Remove unnecessary 'this' aliasing.

Arrow functions inherit 'this' from their enclosing scope, making the alias unnecessary.

-    const self = this;
-    self.named('badge');
-    self.process((parent, target, attrs) => {
+    this.named('badge');
+    this.process((parent, target, attrs) => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 276bbd9 and 72b1457.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • extensions/generate-rp-connect-info.js (1 hunks)
  • macros/badge.js (1 hunks)
  • macros/enterprise-label.js (0 hunks)
  • package.json (2 hunks)
💤 Files with no reviewable changes (1)
  • macros/enterprise-label.js
🧰 Additional context used
🪛 Biome (1.9.4)
macros/badge.js

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


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

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules - docs-extensions-and-macros
  • GitHub Check: Header rules - docs-extensions-and-macros
  • GitHub Check: Pages changed - docs-extensions-and-macros
🔇 Additional comments (8)
package.json (2)

3-3: LGTM! Version increment is appropriate.

The patch version increment is suitable for adding new functionality (badge macro) while maintaining backward compatibility.


61-61: LGTM! Export entry follows established pattern.

The new badge macro export follows the existing convention and properly exposes the functionality.

extensions/generate-rp-connect-info.js (6)

118-124: LGTM! Helper function improves code modularity.

The isConnectorDocPath function effectively encapsulates the directory checking logic, making the code more readable and maintainable.


126-131: LGTM! Clean helper function for cloud documentation detection.

The isCloudDoc function properly encapsulates the cloud documentation path checking logic with clear parameter naming and logic.


135-136: LGTM! Destructuring improves code readability.

The destructuring assignment makes variable usage clearer and reduces repetitive property access.


141-141: LGTM! Improved function call enhances readability.

Using the helper function isConnectorDocPath makes the condition more self-documenting than the previous inline string check.


149-149: LGTM! Enhanced conditional logic with helper function.

The use of isCloudDoc helper function with the cloud support check makes the logic clearer and more maintainable.


158-169: LGTM! Improved warning granularity enhances debugging.

The separation of warnings into distinct cases (missing self-managed docs vs missing cloud docs) provides better insight into documentation gaps and will aid in maintenance.

Comment on lines +8 to +18
const label = attrs.label || 'label';
const className = `badge--${label.toLowerCase().replace(/\s+/g, '-')}`;
const isLarge = attrs.size === 'large';
const sizeClass = isLarge ? 'badge--large' : '';
const tooltip = attrs.tooltip;
const tooltipAttr = tooltip ? ` data-tooltip="${tooltip}"` : '';

// Add brackets if not large
const renderedLabel = isLarge ? label : `(${label})`;

return `<span class="badge ${className} ${sizeClass}"${tooltipAttr}>${renderedLabel}</span>`;
Copy link
Contributor

@coderabbitai coderabbitai bot Jun 20, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address potential XSS vulnerability in HTML generation.

The macro directly interpolates user-provided attributes into HTML without proper escaping, which could lead to XSS attacks if malicious content is provided in the tooltip attribute.

Apply this diff to escape HTML attributes:

      const label = attrs.label || 'label';
      const className = `badge--${label.toLowerCase().replace(/\s+/g, '-')}`;
      const isLarge = attrs.size === 'large';
      const sizeClass = isLarge ? 'badge--large' : '';
      const tooltip = attrs.tooltip;
-      const tooltipAttr = tooltip ? ` data-tooltip="${tooltip}"` : '';
+      const tooltipAttr = tooltip ? ` data-tooltip="${tooltip.replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}"` : '';

      // Add brackets if not large
-      const renderedLabel = isLarge ? label : `(${label})`;
+      // Escape HTML entities in label
+      const escapedLabel = label.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;');
+      const renderedLabel = isLarge ? escapedLabel : `(${escapedLabel})`;

-      return `<span class="badge ${className} ${sizeClass}"${tooltipAttr}>${renderedLabel}</span>`;
+      return `<span class="badge ${className} ${sizeClass}"${tooltipAttr}>${renderedLabel}</span>`;
📝 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 label = attrs.label || 'label';
const className = `badge--${label.toLowerCase().replace(/\s+/g, '-')}`;
const isLarge = attrs.size === 'large';
const sizeClass = isLarge ? 'badge--large' : '';
const tooltip = attrs.tooltip;
const tooltipAttr = tooltip ? ` data-tooltip="${tooltip}"` : '';
// Add brackets if not large
const renderedLabel = isLarge ? label : `(${label})`;
return `<span class="badge ${className} ${sizeClass}"${tooltipAttr}>${renderedLabel}</span>`;
const label = attrs.label || 'label';
const className = `badge--${label.toLowerCase().replace(/\s+/g, '-')}`;
const isLarge = attrs.size === 'large';
const sizeClass = isLarge ? 'badge--large' : '';
const tooltip = attrs.tooltip;
const tooltipAttr = tooltip
? ` data-tooltip="${tooltip
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')}"`
: '';
// Escape HTML entities in label
const escapedLabel = label
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#x27;');
const renderedLabel = isLarge
? escapedLabel
: `(${escapedLabel})`;
return `<span class="badge ${className} ${sizeClass}"${tooltipAttr}>${renderedLabel}</span>`;
🤖 Prompt for AI Agents
In macros/badge.js between lines 8 and 18, user-provided attributes like tooltip
are directly inserted into HTML without escaping, risking XSS attacks. To fix
this, implement a function to escape special HTML characters in attribute values
and apply it to all interpolated user inputs such as tooltip and label before
including them in the returned HTML string.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is run as part of a static site generator called Antora.

Copy link
Contributor

Choose a reason for hiding this comment

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

@JakeSCahill Thank you for that important clarification! You're absolutely right - the context of Antora as a static site generator significantly changes the security implications of my previous concern.

Since this macro executes at build time as part of the static site generation process rather than processing untrusted user input at runtime, the XSS risk is much lower. The input to this macro would typically come from documentation authors writing AsciiDoc content, which is a controlled and trusted environment.

While HTML escaping is still a good defensive programming practice (especially if the macro might be reused in other contexts), the urgency is much lower in this static site generator scenario. The immediate security concern I raised doesn't apply in the same way to build-time processing of trusted documentation content.

The macro implementation is appropriate for its intended use case in the Antora documentation build process.


✏️ Learnings added
Learnt from: JakeSCahill
PR: redpanda-data/docs-extensions-and-macros#109
File: macros/badge.js:8-18
Timestamp: 2025-06-24T11:03:59.146Z
Learning: Badge macro in macros/badge.js runs as part of Antora static site generator at build time, processing trusted documentation author content rather than untrusted user input, which significantly reduces XSS security concerns.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

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.

1 participant