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

Disallow empty annotation layer names and names starting with a '.' #8244

Merged
merged 4 commits into from
Dec 2, 2024

Conversation

MichaelBuessemeyer
Copy link
Contributor

@MichaelBuessemeyer MichaelBuessemeyer commented Nov 28, 2024

This pr adds frontend validation to annotation layer names and tries to put the same restrictions to the annotation layer names as to "normal" dataset layer names.
Sadly, it is not easily possible to reuse the rules set for dataset layer names, as these are formulated as antd form validation rules and the annotation layer name setting uses an EditableTextLabel. The EditableTextLabel has its own format for validation rules which is not directly compatible with the antd variation -> Therefore I duplicated the two missing rules:

  • not starting with a .
  • at least one character long

URL of deployed dev instance (used for testing):

  • https://___.webknossos.xyz

Steps to test:

  • Open a hybrid annotation
  • try renaming the segmentation layer to an empty string -> frontend validation should fail
  • try renaming the segmentation layer to something starting with a . -> frontend validation should fail

Issues:


(Please delete unneeded items, merge only when none are left open)

Copy link
Contributor

coderabbitai bot commented Nov 28, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces several enhancements to validation logic within the frontend components of the application. Key changes include the addition of a min property to the Rule type for input validation in the EditableTextLabel component, along with new error messages for volume layer naming constraints. The AddVolumeLayerModal component also receives updates to enforce these naming rules, ensuring that layer names do not start with a dot and have a minimum length. These modifications collectively improve the robustness of user input validation across the application.

Changes

File Path Change Summary
frontend/javascripts/oxalis/view/components/editable_text_label.tsx Added optional property min?: number to Rule type; updated validateFields for new minimum length validation.
CHANGELOG.unreleased.md Updated changelog to reflect new features and fixes, including validation for annotation layer names.
frontend/javascripts/messages.tsx Added new messages for volume layer name validation: too short and starting with a dot.
frontend/javascripts/oxalis/view/left-border-tabs/modals/add_volume_layer_modal.tsx Enhanced validation logic to check for layer names starting with a dot and minimum length requirement.

Possibly related PRs

Suggested labels

usability

Suggested reviewers

  • dieknolle3333
  • hotzenklotz

Poem

🐰 In the land of code where rabbits play,
New rules for layers brighten the day!
With names that must fit, and lengths that are right,
Our validation's strong, making coding a delight!
So hop along, friends, let’s code with glee,
For every layer's name, there's a rule, you see! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8ba23ba and 34b05fa.

📒 Files selected for processing (3)
  • CHANGELOG.unreleased.md (1 hunks)
  • frontend/javascripts/messages.tsx (1 hunks)
  • frontend/javascripts/oxalis/view/left-border-tabs/modals/add_volume_layer_modal.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • frontend/javascripts/messages.tsx
  • frontend/javascripts/oxalis/view/left-border-tabs/modals/add_volume_layer_modal.tsx
  • CHANGELOG.unreleased.md

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.

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

🧹 Outside diff range and nitpick comments (3)
frontend/javascripts/oxalis/view/components/editable_text_label.tsx (1)

122-126: Enhance validation logic robustness

While the basic implementation works, consider these improvements:

  1. Use the rule's message property if provided, falling back to the default message
  2. Add null/undefined value handling
  3. Consider adding max length validation for completeness

Here's a suggested implementation:

 } else if (rule.min != null) {
-  if (this.state.value.length < rule.min) {
-    Toast.error(`Length must at least be ${rule.min}.`);
+  const value = this.state.value;
+  if (!value || value.length < rule.min) {
+    Toast.error(rule.message ?? `${this.props.label} length must be at least ${rule.min} characters.`);
     return false;
   }
 }
frontend/javascripts/oxalis/view/left-border-tabs/layer_settings_tab.tsx (2)

Line range hint 752-761: Consider making the minimum length validation more robust.

The current implementation has potential fragility issues:

  1. Direct array indexing with [0] is brittle
  2. Type assertion as { min: number } suggests potential type safety issues

Consider refactoring to:

-layerNameRules[0] as { min: number }, // Ensuring minimum length
+const [minLengthRule] = layerNameRules;
+minLengthRule as { min: number }, // Ensuring minimum length

Or better yet, improve the type definitions in dataset_components.ts to avoid the type assertion.


761-768: Consider extracting the dot validation rule for reusability.

The validation logic is clear but could be made reusable since this rule might be needed in other components.

Consider extracting the validation to a shared utility:

+// In a shared validation utility file
+export const validateNoLeadingDot = (value: string) => ({
+  isValid: !value.startsWith("."),
+  message: "The name must not start with a dot."
+});

// In this file
-{
-  validator: (newReadableLayerName) => {
-    const startsWithADot = newReadableLayerName.startsWith(".");
-    return startsWithADot
-      ? { isValid: false, message: "The name must not start with a dot." }
-      : { isValid: true, message: "" };
-  },
-},
+{
+  validator: validateNoLeadingDot,
+},
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7206862 and 4b35038.

📒 Files selected for processing (2)
  • frontend/javascripts/oxalis/view/components/editable_text_label.tsx (2 hunks)
  • frontend/javascripts/oxalis/view/left-border-tabs/layer_settings_tab.tsx (3 hunks)
🔇 Additional comments (1)
frontend/javascripts/oxalis/view/components/editable_text_label.tsx (1)

13-13: LGTM: Type definition change is well-structured

The addition of the optional min property to the Rule type is clean and maintains backward compatibility.

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

🧹 Outside diff range and nitpick comments (1)
CHANGELOG.unreleased.md (1)

27-27: Fix typo and improve clarity in changelog entry.

The changelog entry contains a typo and could be clearer by separating the two validation rules.

-Fix that the frontend did not ensure a minium length for annotation layer names. Moreover, names starting with a `.` are also disallowed now. [#8244](https://github.com/scalableminds/webknossos/pull/8244)
+Fix frontend validation for annotation layer names by enforcing a minimum length and disallowing names that start with a '.'. [#8244](https://github.com/scalableminds/webknossos/pull/8244)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4b35038 and 0504908.

📒 Files selected for processing (1)
  • CHANGELOG.unreleased.md (1 hunks)

Copy link
Member

@philippotto philippotto left a comment

Choose a reason for hiding this comment

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

thanks for doing this! see my one suggestion.

@@ -748,6 +749,7 @@ class DatasetSettings extends React.PureComponent<DatasetSettingsProps, State> {
});
}}
rules={[
layerNameRules[0] as { min: number }, // Ensuring minimum length
{
validator: (newReadableLayerName) =>
validateReadableLayerName(
Copy link
Member

Choose a reason for hiding this comment

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

I think the additional rules should be implemented within validateReadableLayerName (or maybe checkLayerNameForInvalidCharacters for the .).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sure thanks for the suggestion. Should be implemented now :)

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

🧹 Outside diff range and nitpick comments (3)
frontend/javascripts/oxalis/view/left-border-tabs/modals/add_volume_layer_modal.tsx (2)

44-50: LGTM! Consider adding JSDoc for the validation rule.

The implementation correctly prevents layer names from starting with a dot. Consider adding a JSDoc comment explaining why this restriction exists (e.g., if it's to prevent hidden files/layers or maintain consistency with dataset layer names).

+/**
+ * Validates that the layer name doesn't start with a dot and contains only URI-safe characters.
+ * The dot restriction aligns with dataset layer name validation rules to prevent hidden layers.
+ */
 export function checkLayerNameForInvalidCharacters(readableLayerName: string): ValidationResult {

72-77: LGTM! Consider adding input trimming.

The minimum length validation is correctly implemented. Consider trimming whitespace from the input to prevent names that appear empty but contain spaces.

 export function validateReadableLayerName(
   readableLayerName: string,
   allReadableLayerNames: string[],
   nameNotToCount?: string,
 ): ValidationResult {
+  const trimmedName = readableLayerName.trim();
+  if (trimmedName.length < 1) {
-  if (readableLayerName.length < 1) {
     return {
       isValid: false,
       message: messages["tracing.volume_layer_name_too_short"],
     };
   }
frontend/javascripts/messages.tsx (1)

215-216: LGTM with a minor suggestion for consistency.

The new validation messages are well-placed within the tracing-related messages section and follow the established message format. However, for better consistency with other validation messages in the file, consider using sentence case for both messages.

-  "tracing.volume_layer_name_too_short": "The layer name must be at least one character long.",
-  "tracing.volume_layer_name_starts_with_dot": "The layer name must not start with a dot.",
+  "tracing.volume_layer_name_too_short": "Layer name must be at least one character long.",
+  "tracing.volume_layer_name_starts_with_dot": "Layer name must not start with a dot.",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0504908 and 8ba23ba.

📒 Files selected for processing (2)
  • frontend/javascripts/messages.tsx (1 hunks)
  • frontend/javascripts/oxalis/view/left-border-tabs/modals/add_volume_layer_modal.tsx (2 hunks)
🔇 Additional comments (1)
frontend/javascripts/oxalis/view/left-border-tabs/modals/add_volume_layer_modal.tsx (1)

Line range hint 44-77: Implementation successfully meets PR objectives.

The changes successfully implement the required validation rules for annotation layer names:

  1. Names cannot be empty (minimum length of 1 character)
  2. Names cannot start with a dot
  3. Error messages are properly externalized for i18n support

The implementation aligns well with the dataset layer name restrictions as mentioned in the PR objectives.

Let's verify that these validation rules are consistent with dataset layer validation:

✅ Verification successful

Frontend validation aligns with backend dataset layer restrictions

The implementation is correctly aligned with the backend validation rules found in DatasetService.scala, which also enforces:

  • Names cannot start with a dot (!name.startsWith("."))
  • Similar validation exists in the admin dataset components

The frontend validation is actually more comprehensive as it also includes:

  • URI-safe character validation
  • Empty name check
  • Proper error messaging
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for dataset layer name validation rules
# Look for similar validation patterns in dataset-related files

# Search for dataset layer name validation
rg -A 5 "validateLayerName|validateDatasetName|layerNameValidation" --type typescript

# Search for similar dot-prefix validation
ast-grep --pattern 'startsWith(".")' --lang typescript

Length of output: 179


Script:

#!/bin/bash
# Let's try different approaches to find validation patterns

# Search for layer name validation patterns without file type restriction
rg -A 5 "validateLayerName|validateDatasetName|layerNameValidation"

# Search for dot prefix validation without language restriction
rg -A 5 "startsWith\\(\"\\.\"\\)"

# Look for similar validation logic in the codebase
rg -A 5 "isValid.*message"

Length of output: 3186

@MichaelBuessemeyer MichaelBuessemeyer enabled auto-merge (squash) December 2, 2024 15:02
@MichaelBuessemeyer MichaelBuessemeyer merged commit fb1f275 into master Dec 2, 2024
3 checks passed
@MichaelBuessemeyer MichaelBuessemeyer deleted the min-length-for-annotation-layer-name branch December 2, 2024 15:15
@coderabbitai coderabbitai bot mentioned this pull request Dec 2, 2024
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants