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

Generalized visibility property logic and added to CallToActionNode #1431

Merged

Conversation

kevinansfield
Copy link
Member

@kevinansfield kevinansfield commented Feb 3, 2025

ref https://linear.app/ghost/issue/PLG-332

  • switched from exporting DEFAULT_VISIBILITY as a constant to a buildDefaultVisibility() factory function to avoid potential modify-by-reference of the nested objects in an exported constant
  • added hasVisibility option to generateDecoratorNode()
    • keeps all visibility related logic in one place and prevents behaviour divergence across nodes if each node specified it's own visibility property logic
    • adds visibility property to the node
    • ensures default value is correct and can't accidentally be modified if nested objects in node.visibility are modified
    • adds automatic migration of visibility from old beta format to new when importing older serialized documents
    • added associated test file so behaviour can be tested outside of card-specific tets
  • updated HtmlNode to use new hasVisibility option
  • added hasVisibility option to new CallToActionNode

Copy link

coderabbitai bot commented Feb 3, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/koenig-lexical/src/utils/visibility.js

Oops! Something went wrong! :(

ESLint: 8.57.0

ESLint couldn't find the config "react-app" to extend from. Please check that the name of the config is correct.

The config "react-app" was referenced from the config file in "/packages/koenig-lexical/.eslintrc.cjs".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

packages/kg-default-nodes/lib/generate-decorator-node.js

Oops! Something went wrong! :(

ESLint: 8.57.0

Error: Failed to load parser '@babel/eslint-parser' declared in 'packages/kg-default-nodes/.eslintrc.js': Cannot find module '@babel/eslint-parser'
Require stack:

  • /packages/kg-default-nodes/.eslintrc.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object.resolve (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2346:46)
    at ConfigArrayFactory._loadParser (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3325:39)
    at ConfigArrayFactory._normalizeObjectConfigDataBody (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3099:43)
    at _normalizeObjectConfigDataBody.next ()
    at ConfigArrayFactory._normalizeObjectConfigData (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3040:20)
    at _normalizeObjectConfigData.next ()
    at ConfigArrayFactory.loadInDirectory (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2886:28)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3871:46)
packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js

Oops! Something went wrong! :(

ESLint: 8.57.0

Error: Failed to load parser '@babel/eslint-parser' declared in 'packages/kg-default-nodes/.eslintrc.js': Cannot find module '@babel/eslint-parser'
Require stack:

  • /packages/kg-default-nodes/.eslintrc.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object.resolve (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2346:46)
    at ConfigArrayFactory._loadParser (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3325:39)
    at ConfigArrayFactory._normalizeObjectConfigDataBody (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3099:43)
    at _normalizeObjectConfigDataBody.next ()
    at ConfigArrayFactory._normalizeObjectConfigData (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3040:20)
    at _normalizeObjectConfigData.next ()
    at ConfigArrayFactory.loadInDirectory (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2886:28)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3871:46)
  • 3 others

Walkthrough

This pull request introduces a new property, hasVisibility, to the CallToActionNode and HtmlNode classes, modifying their constructors and properties to enhance visibility management. The DEFAULT_VISIBILITY constant has been removed from exports in favor of a new function, buildDefaultVisibility(), which creates a deep copy of the visibility object. Test cases for CallToActionNode have been expanded to validate the new visibility features, ensuring accurate initialization and functionality across the affected components.

Changes

File(s) Change Summary
packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js
packages/kg-default-nodes/lib/nodes/html/HtmlNode.js
Added hasVisibility property, modified constructors, and removed visibility property from HtmlNode.
packages/kg-default-nodes/lib/utils/visibility.js
packages/koenig-lexical/src/utils/visibility.js
Removed export of DEFAULT_VISIBILITY, added buildDefaultVisibility() function to create a deep copy of visibility.
packages/kg-default-nodes/test/nodes/call-to-action.test.js Enhanced tests for CallToActionNode to include assertions for the new visibility property and its setter functionality.
packages/kg-default-nodes/lib/generate-decorator-node.js
packages/kg-default-nodes/lib/kg-default-nodes.js
Updated generateDecoratorNode to include hasVisibility parameter and modified exports to include utility functions related to visibility management.
packages/kg-default-nodes/test/generate-decorator-node.test.js Introduced tests for generateDecoratorNode to validate visibility properties and migration from old formats.

Sequence Diagram(s)

sequenceDiagram
    participant Node as CallToAction/Html Node
    participant VisibilityUtil as buildDefaultVisibility()
    participant Default as DEFAULT_VISIBILITY
    Node ->> VisibilityUtil: Request default visibility
    VisibilityUtil ->> Default: Create deep copy (using JSON methods)
    Default -->> VisibilityUtil: Return copy
    VisibilityUtil -->> Node: Return default visibility
Loading

Possibly related PRs

  • Updated CTA card icon in card menu #1423: The changes in the main PR, which add the hasVisibility property to the CallToActionNode class, are related to the retrieved PR as both involve modifications to the same class, specifically altering its properties and constructor logic.
  • Integrated CTA Node Component into Koenig-Lexical #1413: The changes in the main PR, which add the hasVisibility property to the CallToActionNode class, are related to the retrieved PR as both involve modifications to the CallToActionNode class, albeit with different properties being added.
  • Added CallToAction Lexical Nodes #1412: The changes in the main PR, which add the hasVisibility property to the CallToActionNode class, are directly related to the modifications in the retrieved PR that introduces the CallToActionNode itself, as both involve alterations to the same class.

Poem

I'm a little rabbit hopping through the code,
Crafting default visibility on my scenic road.
With buildDefaultVisibility(), I make a deep copy with care,
Ensuring each node shines with a brightness so rare.
Test by test, I bounce along with glee,
Celebrating these changes—hop on and code with me!

✨ 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

@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 comments (1)
packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (1)

22-47: Update constructor to handle visibility parameter.

The constructor should be updated to handle the new visibility property consistently with other properties.

 constructor({
     layout,
     textValue,
     showButton,
     buttonText,
     buttonUrl,
     buttonColor,
     buttonTextColor,
     hasSponsorLabel,
     backgroundColor,
     hasImage,
-    imageUrl
+    imageUrl,
+    visibility
 } = {}, key) {
     super(key);
     this.__layout = layout ?? 'minimal';
     this.__textValue = textValue ?? '';
     this.__showButton = showButton ?? false;
     this.__buttonText = buttonText ?? '';
     this.__buttonUrl = buttonUrl ?? '';
     this.__buttonColor = buttonColor ?? 'none';
     this.__buttonTextColor = buttonTextColor ?? 'none';
     this.__hasSponsorLabel = hasSponsorLabel ?? true;
     this.__backgroundColor = backgroundColor ?? 'grey';
     this.__hasImage = hasImage ?? false;
     this.__imageUrl = imageUrl ?? '';
+    this.__visibility = visibility ?? buildDefaultVisibility();
 }
🧹 Nitpick comments (2)
packages/kg-default-nodes/lib/utils/visibility.js (1)

14-17: Consider using structuredClone for better performance.

While JSON.parse(JSON.stringify()) works for this case, structuredClone() is a more efficient built-in method for deep cloning objects.

-    return JSON.parse(JSON.stringify(DEFAULT_VISIBILITY));
+    return structuredClone(DEFAULT_VISIBILITY);
packages/kg-default-nodes/test/nodes/call-to-action.test.js (1)

69-69: Consider adding edge case tests for visibility.

The visibility getter and setter tests look good and properly verify the basic functionality. Consider adding tests for:

  1. Invalid visibility object structures
  2. Partial visibility updates
  3. Null/undefined values

Example test cases:

it('handles invalid visibility objects', editorTest(function () {
    const callToActionNode = new CallToActionNode();
    
    // Should retain default when setting invalid structure
    callToActionNode.visibility = {invalid: true};
    callToActionNode.visibility.should.deepEqual(utils.visibility.buildDefaultVisibility());
    
    // Should handle null/undefined
    callToActionNode.visibility = null;
    callToActionNode.visibility.should.deepEqual(utils.visibility.buildDefaultVisibility());
}));

it('handles partial visibility updates', editorTest(function () {
    const callToActionNode = new CallToActionNode();
    const defaultVisibility = utils.visibility.buildDefaultVisibility();
    
    // Should merge with existing visibility
    callToActionNode.visibility = {
        web: {nonMembers: false}
    };
    callToActionNode.visibility.should.deepEqual({
        ...defaultVisibility,
        web: {
            ...defaultVisibility.web,
            nonMembers: false
        }
    });
}));

Also applies to: 119-137

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 31c9d78 and 10cc158.

📒 Files selected for processing (5)
  • packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (2 hunks)
  • packages/kg-default-nodes/lib/nodes/html/HtmlNode.js (1 hunks)
  • packages/kg-default-nodes/lib/utils/visibility.js (2 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (4 hunks)
  • packages/koenig-lexical/src/utils/visibility.js (1 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/kg-default-nodes/lib/utils/visibility.js (1)
Learnt from: kevinansfield
PR: TryGhost/Koenig#1424
File: packages/kg-default-nodes/lib/utils/visibility.js:14-18
Timestamp: 2025-01-28T18:55:16.157Z
Learning: The `usesOldVisibilityFormat` function in `visibility.js` already checks for the existence of the 'web' property using `Object.prototype.hasOwnProperty.call(visibility, 'web')` before accessing `visibility.web.nonMember`.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1
🔇 Additional comments (6)
packages/kg-default-nodes/lib/utils/visibility.js (1)

4-12: LGTM! Good practice to prevent external modifications.

Making DEFAULT_VISIBILITY a local constant prevents accidental modifications from external code.

packages/kg-default-nodes/lib/nodes/html/HtmlNode.js (1)

5-5: LGTM! Consistent usage of buildDefaultVisibility.

The changes correctly implement the new visibility initialization pattern in both the property definition and constructor.

Also applies to: 10-10, 15-15

packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (1)

3-3: LGTM! Visibility property added correctly.

The import and property definition are properly implemented.

Also applies to: 17-18

packages/koenig-lexical/src/utils/visibility.js (1)

3-3: LGTM! Using buildDefaultVisibility correctly.

The change correctly uses the new factory function to initialize the default visibility.

packages/kg-default-nodes/test/nodes/call-to-action.test.js (2)

5-5: LGTM!

The import of utils is correctly structured and aligns with the PR's objective to support visibility functionality.


41-42: LGTM!

The dataset initialization correctly uses the new buildDefaultVisibility() factory function for the visibility property, which aligns with the PR's goal of preventing issues with nested object references.

@kevinansfield kevinansfield force-pushed the cta-card-visibility-property branch from 10cc158 to 7177aaa Compare February 3, 2025 09:16
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

🧹 Nitpick comments (1)
packages/kg-default-nodes/test/nodes/call-to-action.test.js (1)

69-69: Consider adding more test cases for visibility property.

The current tests verify basic getter/setter functionality well. However, consider adding these test cases for more comprehensive coverage:

  1. Partial updates to visibility structure
  2. Invalid visibility structure handling
  3. Edge cases (null, undefined values)

Example test cases to add:

it('handles partial visibility updates', editorTest(function () {
    const callToActionNode = new CallToActionNode();
    
    // Test partial web update
    callToActionNode.visibility = {
        web: { nonMembers: false }
    };
    callToActionNode.visibility.web.nonMembers.should.equal(false);
    callToActionNode.visibility.web.memberSegment.should.equal('');
    
    // Test partial email update
    callToActionNode.visibility = {
        email: { memberSegment: 'paid' }
    };
    callToActionNode.visibility.email.memberSegment.should.equal('paid');
}));

it('validates visibility structure', editorTest(function () {
    const callToActionNode = new CallToActionNode();
    
    // Test invalid structure
    (() => {
        callToActionNode.visibility = {
            invalid: true
        };
    }).should.throw();
    
    // Test null/undefined
    (() => {
        callToActionNode.visibility = null;
    }).should.throw();
}));

Also applies to: 119-137

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 10cc158 and 7177aaa.

📒 Files selected for processing (5)
  • packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (2 hunks)
  • packages/kg-default-nodes/lib/nodes/html/HtmlNode.js (1 hunks)
  • packages/kg-default-nodes/lib/utils/visibility.js (2 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (4 hunks)
  • packages/koenig-lexical/src/utils/visibility.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js
  • packages/kg-default-nodes/lib/utils/visibility.js
  • packages/kg-default-nodes/lib/nodes/html/HtmlNode.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1
🔇 Additional comments (3)
packages/koenig-lexical/src/utils/visibility.js (1)

46-47: LGTM! Good improvement to prevent shared state mutation.

The change from using a default parameter to explicitly creating default visibility objects prevents issues with modifying nested objects by reference. This ensures each function call gets a fresh copy of the default visibility settings.

packages/kg-default-nodes/test/nodes/call-to-action.test.js (2)

5-5: LGTM: Import changes are correct.

The addition of utils to the destructured import is appropriate for accessing the visibility utilities.


41-42: LGTM: Dataset initialization properly includes visibility.

The dataset correctly initializes the visibility property using buildDefaultVisibility(), aligning with the PR's objective to prevent issues with modifying nested objects by reference.

@kevinansfield kevinansfield force-pushed the cta-card-visibility-property branch from 7177aaa to 549c94c Compare February 3, 2025 11:57
@kevinansfield kevinansfield changed the title Added visibility property to CallToActionNode Generalized visibility property logic and added to CallToActionNode Feb 3, 2025
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: 1

🧹 Nitpick comments (3)
packages/kg-default-nodes/lib/generate-decorator-node.js (1)

150-155: Add more explicit handling for unexpected old visibility formats.
The migration logic is good, but consider logging or fallback behavior if the old schema doesn't match expectations. This could improve debugging and reliability.

packages/kg-default-nodes/lib/kg-default-nodes.js (1)

66-72: LGTM! Consider adding JSDoc comments.

The new utils export object provides a clean interface for accessing utility functions. The structure looks good and maintains backward compatibility.

Consider adding JSDoc comments to document the purpose and usage of the exported utilities:

+/**
+ * Utility functions for node generation and visibility management
+ * @type {Object}
+ * @property {Function} generateDecoratorNode - Generates a decorator node with optional visibility
+ * @property {Object} visibility - Utilities for managing node visibility
+ */
 export const utils = {
     generateDecoratorNode,
     visibility: visibilityUtils
 };
packages/kg-default-nodes/test/generate-decorator-node.test.js (1)

79-103: Consider adding more test cases for migration.

The migration test is good, but consider adding tests for:

  • Invalid old format data
  • Empty or null segment values
  • Multiple segments

Example test case:

it('handles invalid old visibility format gracefully', editorTest(function () {
    const node = NodeWithVisibility.importJSON({
        visibility: {
            showOnWeb: 'invalid',
            showOnEmail: null,
            segment: undefined
        }
    });

    // should fall back to defaults for invalid values
    node.visibility.should.deepEqual({
        showOnWeb: false,
        showOnEmail: false,
        segment: '',
        web: {
            nonMember: true,
            memberSegment: ''
        },
        email: {
            memberSegment: ''
        }
    });
}));
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7177aaa and 549c94c.

📒 Files selected for processing (8)
  • packages/kg-default-nodes/lib/generate-decorator-node.js (4 hunks)
  • packages/kg-default-nodes/lib/kg-default-nodes.js (1 hunks)
  • packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (2 hunks)
  • packages/kg-default-nodes/lib/nodes/html/HtmlNode.js (1 hunks)
  • packages/kg-default-nodes/lib/utils/visibility.js (2 hunks)
  • packages/kg-default-nodes/test/generate-decorator-node.test.js (1 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (3 hunks)
  • packages/koenig-lexical/src/utils/visibility.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/koenig-lexical/src/utils/visibility.js
  • packages/kg-default-nodes/lib/utils/visibility.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1
🔇 Additional comments (9)
packages/kg-default-nodes/lib/generate-decorator-node.js (3)

3-3: Import statement changes look consistent with usage.
All imported utilities appear to be properly referenced throughout the file.


39-39: Doc and function signature alignment looks good.
The inclusion of the hasVisibility parameter is clearly documented and matches the function definition.

Also applies to: 42-42


51-62: Conditional property addition for ‘visibility’ is well-structured.
Using a getter to create a fresh visibility object via buildDefaultVisibility() avoids reference-sharing issues. Great choice.

packages/kg-default-nodes/lib/nodes/html/HtmlNode.js (2)

7-7: hasVisibility implementation is consistent.
Ensuring this node supports visibility complements the updates in generateDecoratorNode.


9-9: Property definition appears well-chosen.
Declaring html as wordCount: true helps accurately include HTML text in word counts.

packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (2)

4-6: Visibility support for CallToActionNode is properly enabled.
This lines up with the new hasVisibility pattern in generateDecoratorNode.


19-20: Properties array finalization is valid.
No issues with the structure; it's consistent with generateDecoratorNode usage.

packages/kg-default-nodes/test/generate-decorator-node.test.js (1)

41-47: LGTM! Tests cover the core functionality.

The test verifies that the default visibility is correctly initialized and accessible through different methods.

packages/kg-default-nodes/test/nodes/call-to-action.test.js (1)

141-144: LGTM! Dataset includes visibility.

The dataset correctly includes the visibility property with default values.

ref https://linear.app/ghost/issue/PLG-332

- switched from exporting `DEFAULT_VISIBILITY` as a constant to a `buildDefaultVisibility()` factory function to avoid potential modify-by-reference of the nested objects in an exported constant
- added `hasVisibility` option to `generateDecoratorNode()`
  - keeps all visibility related logic in one place
  - adds `visibility` property to the node
  - ensures default value is correct and can't accidentally be modified if nested objects in `node.visibility` are modified
  - adds automatic migration of `visibility` from old beta format to new when importing older serialized documents
  - added associated test file so behaviour can be tested outside of card-specific tets
- updated `HtmlNode` to use new `hasVisibility` option
- added `hasVisibility` option to new `CallToActionNode`
@kevinansfield kevinansfield force-pushed the cta-card-visibility-property branch from 549c94c to ac621a8 Compare February 3, 2025 12:25
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

🧹 Nitpick comments (3)
packages/kg-default-nodes/test/generate-decorator-node.test.js (1)

49-103: Consider adding edge cases to strengthen the test suite.

While the current tests are good, consider adding these scenarios:

  • Invalid visibility format handling
  • Partial visibility updates
  • Edge cases for segment values
+ it('handles invalid visibility format gracefully', editorTest(function () {
+   const node = NodeWithVisibility.importJSON({
+     visibility: {
+       invalid: 'format'
+     }
+   });
+   node.visibility.should.deepEqual(defaultVisibility);
+ }));

+ it('handles partial visibility updates', editorTest(function () {
+   const node = $createNodeWithVisibility();
+   node.visibility.web.nonMember = false;
+   node.visibility.web.should.deepEqual({
+     nonMember: false,
+     memberSegment: defaultVisibility.web.memberSegment
+   });
+ }));
packages/kg-default-nodes/lib/generate-decorator-node.js (2)

147-161: Add error handling for invalid visibility format.

While the migration logic is good, consider adding error handling for invalid visibility formats to prevent runtime errors.

 static importJSON(serializedNode) {
     const data = {};

     // migrate older nodes that were saved with an earlier version of the visibility format
     const visibility = serializedNode.visibility;
-    if (visibility && usesOldVisibilityFormat(visibility)) {
+    if (visibility) {
+        try {
+            if (usesOldVisibilityFormat(visibility)) {
+                migrateOldVisibilityFormat(visibility);
+            }
+        } catch (error) {
+            console.warn(`Invalid visibility format: ${error.message}`);
+            data.visibility = buildDefaultVisibility();
+        }
+    }

     properties.forEach((prop) => {
         data[prop.name] = serializedNode[prop.name];
     });

     return new this(data);
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 160-160: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


244-261: Consider caching the visibility format check.

The implementation is correct but could be optimized by caching the format check result.

 getIsVisibilityActive() {
     if (!properties.some(prop => prop.name === 'visibility')) {
         return false;
     }

     const self = this.getLatest();
     const visibility = self.__visibility;
+    
+    // Cache the format check result
+    if (!this.__visibilityFormat) {
+        this.__visibilityFormat = usesOldVisibilityFormat(visibility) ? 'old' : 'new';
+    }

-    if (usesOldVisibilityFormat(visibility)) {
+    if (this.__visibilityFormat === 'old') {
         return visibility.showOnEmail === false
             || visibility.showOnWeb === false
             || visibility.segment !== '';
     } else {
         return visibility.web.nonMember === false
             || visibility.web.memberSegment !== ALL_MEMBERS_SEGMENT
             || visibility.email.memberSegment !== ALL_MEMBERS_SEGMENT;
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 549c94c and ac621a8.

📒 Files selected for processing (8)
  • packages/kg-default-nodes/lib/generate-decorator-node.js (4 hunks)
  • packages/kg-default-nodes/lib/kg-default-nodes.js (1 hunks)
  • packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (2 hunks)
  • packages/kg-default-nodes/lib/nodes/html/HtmlNode.js (1 hunks)
  • packages/kg-default-nodes/lib/utils/visibility.js (2 hunks)
  • packages/kg-default-nodes/test/generate-decorator-node.test.js (1 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (3 hunks)
  • packages/koenig-lexical/src/utils/visibility.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js
  • packages/kg-default-nodes/lib/utils/visibility.js
  • packages/kg-default-nodes/lib/kg-default-nodes.js
  • packages/koenig-lexical/src/utils/visibility.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1
🔇 Additional comments (7)
packages/kg-default-nodes/lib/nodes/html/HtmlNode.js (1)

6-10: LGTM! Verify visibility behavior in integration tests.

The changes correctly implement the new visibility handling by:

  1. Adding hasVisibility: true to utilize the centralized visibility logic
  2. Removing the visibility property to prevent duplicate definition

Run the following script to verify that the visibility behavior is tested:

✅ Verification successful

Visibility integration tests confirmed

The integration tests in packages/kg-default-nodes/test/nodes/html.test.js exercise the HtmlNode behavior with a visibility parameter. The tests verify the node's export behavior—ensuring that types such as "value" and "inner" are returned as expected—which confirms that:

  • The addition of hasVisibility: true correctly delegates visibility handling to the centralized logic.
  • The removal of the visibility property avoids duplicate definitions and aligns with the new implementation.

No further issues were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for visibility-related tests for HtmlNode

# Search for visibility-related tests in test files
rg -A 5 'HtmlNode.*visibility' --type js

Length of output: 4218

packages/kg-default-nodes/test/generate-decorator-node.test.js (4)

1-21: Well-structured test setup with proper error handling!

The test setup is clean and follows best practices:

  • Proper error handling in the editorTest utility ensures test failures are correctly reported
  • Clear comments explaining the importance of using the utility function

23-39: Clean test node setup with proper encapsulation!

The test node setup follows good practices:

  • Node configuration is isolated in the before hook
  • Node creation is encapsulated in a utility function for reuse

41-47: Comprehensive visibility verification!

The test thoroughly verifies the default visibility:

  • Checks visibility through direct property access
  • Verifies dataset access
  • Validates JSON export

105-127: Good coverage of constructor initialization!

The test properly verifies that visibility can be set through the constructor with complete visibility structure.

packages/kg-default-nodes/lib/generate-decorator-node.js (2)

1-61: Excellent implementation of immutable default visibility!

The implementation follows best practices:

  • Uses getter for default visibility to prevent mutation
  • Clear JSDoc documentation of the new parameter
  • Proper validation of arguments

282-293: Clean implementation of property accessors!

The implementation follows best practices:

  • Uses Object.defineProperty for clean getter/setter definition
  • Properly handles Lexical's immutability with getLatest/getWritable

Copy link
Member

@ronaldlangeveld ronaldlangeveld left a comment

Choose a reason for hiding this comment

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

LGTM. Great implementation and tests. 👍

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