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

feat: add label to viewer #483

Merged
merged 4 commits into from
Jan 4, 2025
Merged

feat: add label to viewer #483

merged 4 commits into from
Jan 4, 2025

Conversation

vishwa2710
Copy link
Contributor

@vishwa2710 vishwa2710 commented Jan 4, 2025

Screenshot 2025-01-03 at 6 46 04 PM

Summary by CodeRabbit

  • New Features

    • Enhanced Viewer class with new capabilities:
      • Added ability to include labels for targets
      • Introduced method to add labels at specific positions
    • Expanded visualization options with more detailed rendering support
  • Tests

    • Added comprehensive test coverage for new viewer functionality
      • Testing target label addition
      • Verifying line rendering
      • Confirming label placement and styling

@vishwa2710 vishwa2710 self-assigned this Jan 4, 2025
Copy link
Contributor

coderabbitai bot commented Jan 4, 2025

Warning

Rate limit exceeded

@vishwa2710 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 2 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 40a7298 and 22c051b.

📒 Files selected for processing (1)
  • bindings/python/test/test_viewer.py (1 hunks)

Walkthrough

The pull request enhances the Viewer class in the Python bindings by introducing new functionality for adding labels to targets and creating standalone labels. The changes include updating the add_target method to optionally include a label and adding a new add_label method that allows creating labels with customizable properties such as position, text, size, and color. Corresponding test methods are added to validate these new features in the viewer's functionality.

Changes

File Change Summary
bindings/python/tools/.../viewer.py - Added optional label parameter to add_target method
- Implemented new add_label method to create labels with customizable properties
bindings/python/test/.../test_viewer.py - Added test_add_target_with_label_success test method
- Added test_add_line_success test method
- Added test_add_label_success test method

Sequence Diagram

sequenceDiagram
    participant User
    participant Viewer
    participant CesiumEntities
    
    User->>Viewer: add_target(position, label=optional)
    alt Label provided
        Viewer->>Viewer: add_label(position, label)
    end
    Viewer->>CesiumEntities: Create target/label entities
Loading

Poem

🐰 In the realm of cosmic view,
Labels dance with targets true,
Positions marked with vibrant grace,
A rabbit's code now finds its space!
Visualization leaps with glee! 🚀


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
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 (3)
bindings/python/test/test_viewer.py (2)

130-155: Consider adding negative tests for invalid label inputs.

This test verifies the happy path but doesn't test scenarios where label is an empty string, excessively long string, or None. Adding negative tests helps ensure robust handling of edge cases.


179-202: Remove leftover debug-related code.

Lines 192–194 (importing IPython and embedding a shell) appear to be temporary debug statements. Consider removing these to keep the test file clean and free of interactive stubs.

-        import IPython
-
-        IPython.embed()
bindings/python/tools/python/ostk/astrodynamics/viewer.py (1)

250-276: Use consistent naming for label parameters.

The add_label function is straightforward, but consider naming the text parameter “label_text” or “message” for consistency with add_target's “label”. This reduces potential confusion.

-    def add_label(
-        self,
-        position: Position,
-        text: str,
-        size: int | None = None,
-        color: str | None = None,
-    ) -> None:
+    def add_label(
+        self,
+        position: Position,
+        label_text: str,
+        size: int | None = None,
+        color: str | None = None,
+    ) -> None:
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 911b0ba and fe156a0.

📒 Files selected for processing (2)
  • bindings/python/test/test_viewer.py (1 hunks)
  • bindings/python/tools/python/ostk/astrodynamics/viewer.py (4 hunks)
🔇 Additional comments (3)
bindings/python/test/test_viewer.py (1)

156-178: Good coverage for polyline addition.

Adding multiple positions and verifying the rendered HTML is sufficiently tested here. The logic and asserts look solid. No immediate concerns.

bindings/python/tools/python/ostk/astrodynamics/viewer.py (2)

Line range hint 191-200: Docstring properly updated to reflect new label parameter.

The parameter documentation appears consistent with the function's signature, clarifying usage of the label argument. Great work!


211-213: Sanitize or validate label to mitigate potential injection risks.

Because label is directly placed within rendered HTML/JS, it’s prudent to sanitize or validate user-provided label content. This helps prevent cross-site scripting (XSS) or other injection vulnerabilities if untrusted input is passed in.
[security]

Consider searching for all references to add_target calls to ensure user-provided labels are from a trusted source:

Copy link

codecov bot commented Jan 4, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.21%. Comparing base (911b0ba) to head (22c051b).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #483   +/-   ##
=======================================
  Coverage   91.21%   91.21%           
=======================================
  Files          86       86           
  Lines        8720     8720           
=======================================
  Hits         7954     7954           
  Misses        766      766           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

text (str): Label text.
size (int, optional): Label size. Defaults to None.
color (str, optional): Label color. Defaults to None.

Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change

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 (3)
bindings/python/test/test_viewer.py (3)

131-154: Enhance test coverage for labeled targets

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

  1. Edge cases for the label parameter (empty string, special characters, very long text)
  2. Separate size controls for point and label scale
  3. Different colors for point and label

Example test cases to add:

def test_add_target_with_empty_label(self, viewer: Viewer):
    viewer.add_target(
        position=Position.meters([1.0, 2.0, 3.0], Frame.ITRF()),
        size=10,
        color="red",
        label=""
    )

def test_add_target_with_special_chars_label(self, viewer: Viewer):
    viewer.add_target(
        position=Position.meters([1.0, 2.0, 3.0], Frame.ITRF()),
        size=10,
        color="red",
        label="Test #1 & <special> chars"
    )

156-177: Expand line rendering test coverage

The current test only covers a basic line with two points. Consider adding tests for:

  1. Edge cases (single point, multiple points)
  2. Different line styles (dashed, dotted)
  3. Validation of coordinate transformations

Also, document the significance of the hardcoded size value (10.0) or make it more meaningful:

-            size=10.0,
+            size=Length.pixels(2.0),  # Standard line width for visibility

131-198: General test improvements needed

Consider the following improvements to strengthen the test suite:

  1. Add docstrings to new test methods describing test scenarios
  2. Include negative test cases (invalid inputs, error conditions)
  3. Use pytest.mark.parametrize for testing multiple scenarios efficiently

Example parametrized test:

@pytest.mark.parametrize("position,label,size,color", [
    (Position.meters([1.0, 2.0, 3.0], Frame.ITRF()), "Test1", 10, "red"),
    (Position.meters([0.0, 0.0, 6371000.0], Frame.ITRF()), "Test2", 20, "blue"),
])
def test_add_target_with_label_parametrized(self, viewer: Viewer, position, label, size, color):
    viewer.add_target(position=position, size=size, color=color, label=label)
    rendered_html: str = viewer.render()
    # assertions
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fe156a0 and bb877fa.

📒 Files selected for processing (1)
  • bindings/python/test/test_viewer.py (1 hunks)

Comment on lines 179 to 198
def test_add_label_success(
self,
viewer: Viewer,
):
viewer.add_label(
position=Position.meters([6671000.0, 0.0, 0.0], Frame.ITRF()),
text="Hello, World!",
size=1.0,
color="red",
)

rendered_html: str = viewer.render()

assert rendered_html.startswith('<meta charset="utf-8">')
assert "var widget = new Cesium.Viewer" in rendered_html
assert (
'widget.entities.add({position: Cesium.Cartesian3.fromDegrees(63.43494882292201, 18.22447811510915, -6376045.535225509), label: {text: "Hello, World!", fillColor: Cesium.Color.RED, scale: 10.0}});'
in rendered_html
)
assert rendered_html.endswith("</script>")
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistencies in label test

There are several issues in this test:

  1. The test sets size=1.0 but asserts scale: 10.0 in the rendered HTML
  2. The position coordinates and their rendered transformation appear inconsistent:
    • Input: [6671000.0, 0.0, 0.0]
    • Rendered: -6376045.535225509 (negative Z coordinate)

Additionally, consider adding tests for:

  1. Label positioning relative to the point
  2. Text alignment options
  3. Label visibility at different zoom levels

Apply this fix for the size inconsistency:

-            size=1.0,
+            size=10.0,  # Match the expected scale in rendered HTML

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

@vishwa2710 vishwa2710 force-pushed the feat/add-label-to-viewer branch from bb877fa to 40a7298 Compare January 4, 2025 14:26
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

♻️ Duplicate comments (1)
bindings/python/test/test_viewer.py (1)

179-198: ⚠️ Potential issue

Address label rendering inconsistencies and enhance test coverage

The test has several issues that need attention:

  1. Size inconsistency between input and rendered scale
  2. Position coordinates inconsistency between input and rendered transformation
  3. Missing tests for text alignment options
  4. No validation of multi-line labels or special characters

Apply this fix for the size and position inconsistencies:

-            position=Position.meters([6671000.0, 0.0, 0.0], Frame.ITRF()),
-            size=1.0,
+            position=Position.meters([1.0, 2.0, 3.0], Frame.ITRF()),  # Use consistent position
+            size=10.0,  # Match the expected scale in rendered HTML

Additionally, add tests for:

def test_add_multiline_label_success(self, viewer: Viewer):
    viewer.add_label(
        position=Position.meters([1.0, 2.0, 3.0], Frame.ITRF()),
        text="Hello\nWorld!",  # Test multi-line text
        size=10.0,
        color="red",
        alignment="CENTER"  # Test text alignment
    )
🧹 Nitpick comments (3)
bindings/python/test/test_viewer.py (3)

131-154: Enhance test coverage for labeled targets

The test could be more comprehensive. Consider:

  1. Testing label positioning relative to the target
  2. Using a more realistic point size (e.g., 5-10 pixels instead of 123)
  3. Testing different label colors and text content
  4. Verifying label visibility at different zoom levels
-    size=123,
+    size=8,  # More realistic point size for visualization

Additionally, consider adding test cases for:

def test_add_target_with_label_different_color(self, viewer: Viewer):
    viewer.add_target(
        position=Position.meters([1.0, 2.0, 3.0], Frame.ITRF()),
        size=8,
        color="red",
        label="TEST",
        label_color="blue"  # Different color for label
    )

156-177: Improve line rendering test coverage

The test could be enhanced in several ways:

  1. Test polylines with multiple segments (>2 points)
  2. Verify line visibility at different zoom levels
  3. Test different line styles (dashed, dotted)
  4. Test line width visibility thresholds

Consider adding test cases for:

def test_add_complex_line_success(self, viewer: Viewer):
    viewer.add_line(
        positions=[
            Position.meters([1.0, 2.0, 3.0], Frame.ITRF()),
            Position.meters([4.0, 5.0, 6.0], Frame.ITRF()),
            Position.meters([7.0, 8.0, 9.0], Frame.ITRF()),
        ],
        size=2.0,  # More realistic line width
        color="red",
        style="dashed"  # Test different line styles
    )

131-198: Consider structural improvements for test maintainability

To improve test maintainability and reduce duplication:

  1. Add shared test constants for common values (positions, colors, sizes)
  2. Create helper methods for common assertions
  3. Consider using parameterized tests for different configurations

Example implementation:

# At the top of the test file
TEST_POSITION = Position.meters([1.0, 2.0, 3.0], Frame.ITRF())
DEFAULT_POINT_SIZE = 8
DEFAULT_LINE_WIDTH = 2

def assert_rendered_entity(html: str, expected_position: str, entity_type: str):
    """Helper method to verify entity rendering"""
    assert f"widget.entities.add({{position: {expected_position}" in html
    if entity_type == "point":
        assert "point: {" in html
    elif entity_type == "label":
        assert "label: {" in 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 bb877fa and 40a7298.

📒 Files selected for processing (1)
  • bindings/python/test/test_viewer.py (1 hunks)

@vishwa2710 vishwa2710 enabled auto-merge (squash) January 4, 2025 14:53
@vishwa2710 vishwa2710 disabled auto-merge January 4, 2025 15:07
@vishwa2710 vishwa2710 merged commit d1c4ed4 into main Jan 4, 2025
15 checks passed
@vishwa2710 vishwa2710 deleted the feat/add-label-to-viewer branch January 4, 2025 15:07
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