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

Added editable Sponsored Label to CTA Card #1437

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

Conversation

ronaldlangeveld
Copy link
Member

@ronaldlangeveld ronaldlangeveld commented Feb 6, 2025

ref https://linear.app/ghost/issue/PLG-325/turn-sponsored-into-editable-text

  • Introduced sponsorLabel node for customisable sponsor text.
  • Updated CallToActionNode to support sponsorLabel as an editable field.
  • Adjusted CtaCard.jsx to render the sponsored label dynamically.
  • Modified tests to cover scenarios where sponsorLabel is present or absent.

ref https://linear.app/ghost/issue/PLG-325/turn-sponsored-into-editable-text

- Added `customSponsorLabel` node property that will allow us to
  customise the text of the Sponsor label
ref https://linear.app/ghost/issue/PLG-325/turn-sponsored-into-editable-text

- Added a new node that would allow us to add customise the the
  Sponsored Label
Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

The changes introduce a new property, sponsorLabel, to the CallToActionNode class, with a default HTML value of '<p><span style="white-space: pre-wrap;">SPONSORED</span></p>'. This property enhances the dataset used in rendering functions, allowing for dynamic sponsor labels in the ctaCardTemplate and emailCTATemplate, replacing hardcoded text. The renderCallToActionNode function has been updated to include the sponsorLabel, ensuring it is utilized in the rendering process. Tests have been amended to verify the sponsorLabel's presence, default value, and modifiability in both HTML and JSON exports. Additionally, the Koenig-lexical components have been updated to include new props (sponsorLabelHtmlEditor and sponsorLabelHtmlEditorInitialState) to facilitate dynamic editing of the sponsor label within the UI.

Possibly related PRs

Poem

I'm a hoppy rabbit celebrating code so bright,
With a new sponsor label shining in the light.
No more static text, it’s dynamic and alive,
In calls-to-action where customization can thrive.
I leap with joy for each line of code done right—
A bunny's cheer for our code taking flight! 🐇

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/components/ui/cards/CtaCard.jsx

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.

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ 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.

@ronaldlangeveld ronaldlangeveld changed the title PLG 325 Added editable Sponsored Label to CTA Card Feb 6, 2025
@ronaldlangeveld ronaldlangeveld marked this pull request as ready for review February 6, 2025 04:20
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: 2

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

17-17: Consider separating styling from content in the default sponsor label.

The default value couples presentation with content by including inline styles. Consider moving the styling to CSS classes for better maintainability.

-        {name: 'sponsorLabel', default: '<p><span style="white-space: pre-wrap;">SPONSORED</span></p>'},
+        {name: 'sponsorLabel', default: '<p><span class="kg-sponsor-text">SPONSORED</span></p>'},
packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (1)

236-248: Consider removing autoFocus for better accessibility.

Setting autoFocus={true} on the sponsor label editor might not be ideal for accessibility as it can be disorienting for screen reader users. Consider removing it unless there's a specific requirement.

 <KoenigNestedEditor
-    autoFocus={true}
     dataTestId={'sponsor-label-editor'}
     hasSettingsPanel={true}
     initialEditor={sponsorLabelHtmlEditor}
     initialEditorState={sponsorLabelHtmlEditorInitialState}
     nodes='basic'
     textClassName={clsx(
         'kg-prose w-full whitespace-normal bg-transparent font-sans !text-2xs text-grey-900/40 dark:text-grey-100/40'
     )}
 >
packages/koenig-lexical/test/e2e/cards/cta-card.test.js (1)

293-295: Improve the text clearing implementation.

The current implementation uses a hardcoded loop to clear text by pressing backspace 9 times. This is fragile and could break if the default text length changes.

Consider using the editor's API to clear the text directly or determine the number of backspaces needed dynamically:

-// clear the default text by hitting backspace 9 times
-for (let i = 0; i < 9; i++) {
-    await page.keyboard.press('Backspace');
-}
+const defaultText = await sponsorEditor.textContent();
+for (let i = 0; i < defaultText.length; i++) {
+    await page.keyboard.press('Backspace');
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c6e63a3 and 0e493cc.

📒 Files selected for processing (7)
  • packages/kg-default-nodes/lib/nodes/call-to-action/CallToActionNode.js (1 hunks)
  • packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (3 hunks)
  • packages/kg-default-nodes/test/nodes/call-to-action.test.js (10 hunks)
  • packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (3 hunks)
  • packages/koenig-lexical/src/nodes/CallToActionNode.jsx (5 hunks)
  • packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx (3 hunks)
  • packages/koenig-lexical/test/e2e/cards/cta-card.test.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1
🔇 Additional comments (5)
packages/kg-default-nodes/lib/nodes/call-to-action/calltoaction-renderer.js (1)

23-23: LGTM! Consistent integration of the sponsor label.

The changes correctly integrate the dynamic sponsor label across templates and dataset.

Also applies to: 51-51, 72-72

packages/koenig-lexical/src/nodes/CallToActionNode.jsx (1)

16-17: LGTM! Well-structured implementation of the sponsor label editor.

The changes follow the established patterns for HTML editors in the codebase, maintaining consistency in:

  • Property declarations
  • Editor setup
  • Dataset handling
  • JSON export
  • Props passing

Also applies to: 51-53, 62-63, 81-87, 112-113

packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (1)

233-235: LGTM!

The styling changes for the sponsor label container are clean and maintain proper color contrast in both light and dark modes.

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

31-31: LGTM!

The test coverage for the sponsorLabel property is comprehensive, including:

  • Default value verification
  • Setter/getter functionality
  • Data persistence

Also applies to: 65-65, 95-97

packages/koenig-lexical/test/e2e/cards/cta-card.test.js (1)

273-316: LGTM!

The new E2E tests provide excellent coverage of the sponsor label functionality:

  • Default state verification
  • Toggle visibility
  • Text modification
  • Content editor placeholder and text modification

Comment on lines 114 to 116
React.useEffect(() => {
htmlEditor.setEditable(isEditing);
}, [isEditing, htmlEditor]);
}, [isEditing, htmlEditor, sponsorLabelHtmlEditor]);
Copy link

@coderabbitai coderabbitai bot Feb 6, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update useEffect to handle sponsorLabelHtmlEditor editability.

The sponsorLabelHtmlEditor is included in the dependency array but its editability is not being set. Consider updating the effect to handle both editors:

 React.useEffect(() => {
     htmlEditor.setEditable(isEditing);
+    sponsorLabelHtmlEditor?.setEditable(isEditing);
 }, [isEditing, htmlEditor, sponsorLabelHtmlEditor]);
📝 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
React.useEffect(() => {
htmlEditor.setEditable(isEditing);
}, [isEditing, htmlEditor]);
}, [isEditing, htmlEditor, sponsorLabelHtmlEditor]);
React.useEffect(() => {
htmlEditor.setEditable(isEditing);
sponsorLabelHtmlEditor?.setEditable(isEditing);
}, [isEditing, htmlEditor, sponsorLabelHtmlEditor]);

Copy link
Member Author

Choose a reason for hiding this comment

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

No this is not desirable since we just want the htmlEditor to be set as isEditing upon initial render since editing Sponsored label is optional.

Copy link

Choose a reason for hiding this comment

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

@ronaldlangeveld I understand now - thank you for the clarification. You're right, and I'll retract my suggestion since the sponsor label's editability should be handled separately from the main content editor.


✏️ Learnings added
Learnt from: ronaldlangeveld
PR: TryGhost/Koenig#1437
File: packages/koenig-lexical/src/nodes/CallToActionNodeComponent.jsx:0-0
Timestamp: 2025-02-06T04:48:22.549Z
Learning: In the CallToActionNodeComponent of Koenig, only the main content editor (htmlEditor) should be set as editable in the useEffect hook. The sponsor label editor's (sponsorLabelHtmlEditor) editability is handled separately as it's an optional feature.

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.

Comment on lines +71 to +72
sponsorLabelHtmlEditor,
sponsorLabelHtmlEditorInitialState,
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add default values for new props.

The new props sponsorLabelHtmlEditor and sponsorLabelHtmlEditorInitialState are correctly added to PropTypes but are missing from defaultProps. This could cause issues if the props are not provided.

Add the following to defaultProps:

 CtaCard.defaultProps = {
     // ... existing props ...
+    sponsorLabelHtmlEditor: null,
+    sponsorLabelHtmlEditorInitialState: null,
     onRemoveMedia: () => {}
 };

Also applies to: 356-357

no issue

- disables the `koenig-lexical` and `kg-prose` classes when set to `false` in order to allow more customised styling
- defaults to `true` in order to preserve current behaviour
no issue

- provides a means to override class names added to Lexical-controlled elements
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 (1)
packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (1)

242-256: Enhance accessibility of the sponsor label editor.

Consider adding ARIA attributes to improve accessibility:

 <KoenigNestedEditor
     autoFocus={true}
     dataTestId={'sponsor-label-editor'}
+    aria-label="Sponsor label editor"
+    role="textbox"
     hasSettingsPanel={true}
     initialEditor={sponsorLabelHtmlEditor}
     initialEditorState={sponsorLabelHtmlEditorInitialState}
     initialTheme={sponsoredLabelTheme}
     nodes='basic'
     textClassName={clsx(
         'not-kg-prose w-full whitespace-normal bg-transparent font-sans !text-2xs text-grey-900/40 dark:text-grey-100/40'
     )}
     useDefaultClasses={false}
 >
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bb6bf22 and 788af79.

📒 Files selected for processing (2)
  • packages/koenig-lexical/src/components/KoenigNestedEditor.jsx (4 hunks)
  • packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/koenig-lexical/src/components/KoenigNestedEditor.jsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1
🔇 Additional comments (2)
packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (2)

25-28: LGTM! Clean theme implementation.

The theme implementation follows best practices by extending the default theme and using semantic color values with opacity.


77-78: Add missing props to defaultProps.

The new props are correctly defined in PropTypes but are missing from defaultProps.

Also applies to: 364-365

Comment on lines 242 to 256
<KoenigNestedEditor
autoFocus={true}
dataTestId={'sponsor-label-editor'}
hasSettingsPanel={true}
initialEditor={sponsorLabelHtmlEditor}
initialEditorState={sponsorLabelHtmlEditorInitialState}
initialTheme={sponsoredLabelTheme}
nodes='basic'
textClassName={clsx(
'not-kg-prose w-full whitespace-normal bg-transparent font-sans !text-2xs text-grey-900/40 dark:text-grey-100/40'
)}
useDefaultClasses={false}
>
<ReplacementStringsPlugin />
</KoenigNestedEditor>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for editor initialization.

Consider implementing error boundaries or try-catch blocks to handle potential editor initialization failures gracefully.

+const [editorError, setEditorError] = useState(null);

+// Add error handling wrapper
+const handleEditorError = (error) => {
+    console.error('Sponsor label editor failed to initialize:', error);
+    setEditorError(error);
+};

+{editorError ? (
+    <div className="text-red-500 text-sm">
+        Failed to load sponsor label editor. Please try again.
+    </div>
+) : (
     <KoenigNestedEditor
         autoFocus={true}
         dataTestId={'sponsor-label-editor'}
         hasSettingsPanel={true}
         initialEditor={sponsorLabelHtmlEditor}
         initialEditorState={sponsorLabelHtmlEditorInitialState}
         initialTheme={sponsoredLabelTheme}
         nodes='basic'
         textClassName={clsx(
             'not-kg-prose w-full whitespace-normal bg-transparent font-sans !text-2xs text-grey-900/40 dark:text-grey-100/40'
         )}
         useDefaultClasses={false}
+        onError={handleEditorError}
     >

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

♻️ Duplicate comments (2)
packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (2)

244-258: ⚠️ Potential issue

Add error handling for editor initialization.

The nested editor lacks error handling for initialization failures.

Add error handling as suggested in the previous review:

+const [editorError, setEditorError] = useState(null);

+// Add error handling wrapper
+const handleEditorError = (error) => {
+    console.error('Sponsor label editor failed to initialize:', error);
+    setEditorError(error);
+};

+{editorError ? (
+    <div className="text-red-500 text-sm">
+        Failed to load sponsor label editor. Please try again.
+    </div>
+) : (
     <KoenigNestedEditor
         autoFocus={true}
         dataTestId={'sponsor-label-editor'}
         hasSettingsPanel={true}
         initialEditor={sponsorLabelHtmlEditor}
         initialEditorState={sponsorLabelHtmlEditorInitialState}
         initialTheme={sponsoredLabelTheme}
         nodes='basic'
         textClassName={clsx(
             'not-kg-prose w-full whitespace-normal font-sans !text-xs font-semibold uppercase leading-8 tracking-normal text-grey-900/40 dark:text-grey-100/40'
         )}
         useDefaultClasses={false}
+        onError={handleEditorError}
     >

366-367: ⚠️ Potential issue

Add default values for new props.

The new props sponsorLabelHtmlEditor and sponsorLabelHtmlEditorInitialState are missing from defaultProps.

Add the following to defaultProps:

 CtaCard.defaultProps = {
     // ... existing props ...
+    sponsorLabelHtmlEditor: null,
+    sponsorLabelHtmlEditorInitialState: null,
     onRemoveMedia: () => {}
 };

Also applies to: 370-389

🧹 Nitpick comments (3)
packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (3)

26-29: Consider using a more descriptive theme name.

The theme name sponsoredLabelTheme could be more descriptive, e.g., sponsorLabelEditorTheme, to better indicate its purpose.

-const sponsoredLabelTheme = {
+const sponsorLabelEditorTheme = {
     ...defaultTheme,
     link: 'text-accent'
 };

252-254: Consider extracting text styles to a constant.

The text styles for the sponsor label editor are complex and could be reused. Consider extracting them to a constant.

+const SPONSOR_LABEL_TEXT_STYLES = 'not-kg-prose w-full whitespace-normal font-sans !text-xs font-semibold uppercase leading-8 tracking-normal text-grey-900/40 dark:text-grey-100/40';

 <KoenigNestedEditor
     // ...
-    textClassName={clsx(
-        'not-kg-prose w-full whitespace-normal font-sans !text-xs font-semibold uppercase leading-8 tracking-normal text-grey-900/40 dark:text-grey-100/40'
-    )}
+    textClassName={SPONSOR_LABEL_TEXT_STYLES}
     // ...
 >

257-257: Consider adding a comment explaining the RestrictContentPlugin configuration.

The RestrictContentPlugin configuration could benefit from a comment explaining why paragraphs are limited to 1 and why br tags are disallowed.

+// Restrict sponsor label to a single line without line breaks to maintain consistent styling
 <RestrictContentPlugin allowBr={false} paragraphs={1} />
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 788af79 and a6c024e.

📒 Files selected for processing (1)
  • packages/koenig-lexical/src/components/ui/cards/CtaCard.jsx (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node 20.11.1

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.

3 participants