Skip to content

Fix "Related Posts" persistence when sidebar is closed#3249

Merged
alecgeatches merged 10 commits intodevelopfrom
fix/related-posts-persistence
Apr 15, 2025
Merged

Fix "Related Posts" persistence when sidebar is closed#3249
alecgeatches merged 10 commits intodevelopfrom
fix/related-posts-persistence

Conversation

@alecgeatches
Copy link
Contributor

@alecgeatches alecgeatches commented Apr 10, 2025

Description

In develop, when the "Related Posts" sidebar tab is closed and re-opened, the set of related posts reloads each time. Additionally, some of the fields (section, tags) are not persisted between reopens:

Screen.Recording.2025-04-10.at.12.17.13.PM.mov

This component has been modified to use a store for persistence:

Screen.Recording.2025-04-10.at.12.18.05.PM.mov

How has this been tested?

This has been tested manually in the editor. To test:

  1. Log into a site with the wp-parsely plugin activated and connected to Parse.ly credentials.
  2. Open a post with content.
  3. Click the upper-right hand Parse.ly logo, and unfurl the "Related Posts" section.
  4. Select values for the metric, period, section, and tags options if desired.
  5. Close the pane by clicking the Parse.ly logo and reopen it.
  6. Verify that the posts are not reloaded, and settings remain the same.

Summary by CodeRabbit

  • New Features

    • Introduced centralized state management for related posts, ensuring posts load efficiently with enhanced filter and time period options.
    • Improved error handling during content fetching to update the display accurately when no posts are available.
  • Refactor

    • Updated the component to use store-driven state management instead of local state, streamlining post updates and initial content loading.
    • Added a new Redux store to manage related posts state, including actions and selectors for better state handling.

@alecgeatches alecgeatches self-assigned this Apr 10, 2025
@alecgeatches alecgeatches requested a review from a team as a code owner April 10, 2025 18:24
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 10, 2025

📝 Walkthrough

Walkthrough

The changes modify the related posts component by shifting from local state management to using the WordPress data hooks useSelect and useDispatch with the new RelatedPostsStore. The fetchPosts function now accepts additional parameters and executes conditionally on the firstRun flag during component initialization. Additionally, error handling is updated to clear posts on failure. A new Redux store is introduced to manage the related posts state, complete with actions, reducers, and selectors, and it is registered with the WordPress data system. The test suite is updated to reset the store state before each test.

Changes

File(s) Change Summary
src/content-helper/editor-sidebar/related-posts/component.tsx Updated the component to use useSelect and useDispatch for state management; refactored fetchPosts to accept parameters for period, metric, filters, and retries; implemented retry logic and error handling; added firstRun flag to control initial fetch and conditional rendering; updated event handlers to dispatch actions and trigger fetches accordingly.
src/content-helper/editor-sidebar/related-posts/store.ts Introduced a new Redux store (RelatedPostsStore) with state interface, actions, reducers, selectors, and action creators; manages first run status, loading state, filters, and posts; registered the store with the WordPress data system.
tests/js/content-helper/structure.test.tsx Added imports for dispatch and RelatedPostsStore; introduced a beforeEach hook to reset the related posts store state before each test to ensure test isolation.

Suggested labels

Changelog: Changed

Suggested reviewers

  • acicovic

Possibly related PRs

  • PCH Related Posts: Add advanced search #3117: Refactors the Related Posts component and store to manage multiple filters (author, section, tags) via a Redux store and updates fetching logic accordingly, closely related to this PR's changes in filter management and store usage.

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 913965a and cee02eb.

⛔ Files ignored due to path filters (2)
  • build/content-helper/editor-sidebar.asset.php is excluded by !build/**
  • build/content-helper/editor-sidebar.js is excluded by !build/**
📒 Files selected for processing (3)
  • src/content-helper/editor-sidebar/related-posts/component.tsx (7 hunks)
  • src/content-helper/editor-sidebar/related-posts/store.ts (1 hunks)
  • tests/js/content-helper/structure.test.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/js/content-helper/structure.test.tsx
  • src/content-helper/editor-sidebar/related-posts/store.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{js,ts,tsx,jsx}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the code to ensure it is well-structured and adheres to best ...

**/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/content-helper/editor-sidebar/related-posts/component.tsx
🔇 Additional comments (9)
src/content-helper/editor-sidebar/related-posts/component.tsx (9)

9-9: Import updated to support the store-based approach.

The addition of useDispatch alongside useSelect enables the component to both retrieve and update state from a central store, essential for the persistence functionality required by this PR.


36-36: Importing the newly created Redux store for related posts.

This import connects the component to the centralized state store, enabling state persistence when the sidebar is closed and reopened.


143-156: Well-implemented store selectors replacing local state.

The component now uses WordPress data architecture to maintain state across component lifecycles. This is the key improvement that enables persistence when the sidebar is closed and reopened.


158-163: Action dispatchers properly set up for state management.

Good implementation of the WordPress data pattern for dispatching actions to update store state.


189-199: Metric change handler updated to work with store-based approach.

The handler now correctly:

  1. Updates settings
  2. Tracks telemetry
  3. Fetches posts with the new parameters

This implementation maintains the same functionality while integrating with the store-based state management.


212-222: Period change handler updated to work with store-based approach.

The implementation follows the same pattern as the metric change handler, maintaining consistency across the codebase.


226-257: Improved post fetching with explicit parameters and error handling.

The fetchPosts function has been significantly improved:

  1. It now accepts explicit parameters for better function signature clarity
  2. Properly updates store state through action dispatchers
  3. Includes retry logic with timeout
  4. Clears posts on failure for proper UI feedback

The JSDoc comment is well-updated with the new parameters and versioning information.


281-296: Filter handling updated to work with store-based approach.

The implementation now correctly:

  1. Creates a local variable to prepare the updated filters
  2. Updates the store state through the setFilters action
  3. Fetches posts with the current parameters and updated filters

The approach is consistent with other handlers in the component.


372-372: Improved empty state UX by considering first run status.

The addition of the ! firstRun condition prevents showing the "No related posts found" message during initial loading, which provides a better user experience.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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.

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 (4)
src/content-helper/editor-sidebar/related-posts/store.ts (4)

1-3: Add a JSDoc block for the file overview.
Although this file introduces a new WordPress data store, it lacks an overarching JSDoc comment explaining its purpose. Consider adding a top-level doc block describing what the store manages and including an @since tag per WordPress standards.


8-13: Augment the PostsState interface with JSDoc.
Each property in PostsState would benefit from doc comments and an @since tag. This ensures clarity on when and why each property was introduced.

+/**
+ * Represents the state for Related Posts.
+ *
+ * @since 1.0.0
+ */
 interface PostsState {
   isFirstRun: boolean;
   isLoading: boolean;
   filters: PostFilters;
   posts: PostData[];
 }

48-75: Provide a doc block for the store definition.
When creating and registering a store in WordPress, add a JSDoc block at the creation point to describe its purpose, scope, and an @since tag to match WordPress coding standards.

+/**
+ * The Redux store for managing the state of Related Posts in the editor sidebar.
+ *
+ * @since 1.0.0
+ */
 export const RelatedPostsStore = createReduxStore( 'wp-parsely/related-posts', {
   ...
 } );

77-101: Document each action creator with JSDoc.
To comply with WordPress standards, provide doc comments (including @since) for each action creator (setFirstRun, setLoading, etc.). This helps maintain clarity and consistency across the codebase.

 actions: {
+  /**
+   * Sets whether this is the first run.
+   *
+   * @since 1.0.0
+   * @param {boolean} isFirstRun Whether it is the first run.
+   * @return {SetFirstRunAction} Action object for setting first run.
+   */
   setFirstRun( isFirstRun: boolean ): SetFirstRunAction { ...
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44e7223 and 2c39636.

⛔ Files ignored due to path filters (2)
  • build/content-helper/editor-sidebar.asset.php is excluded by !build/**
  • build/content-helper/editor-sidebar.js is excluded by !build/**
📒 Files selected for processing (2)
  • src/content-helper/editor-sidebar/related-posts/component.tsx (7 hunks)
  • src/content-helper/editor-sidebar/related-posts/store.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{js,ts,tsx,jsx}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the code to ensure it is well-structured and adheres to best ...

**/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • src/content-helper/editor-sidebar/related-posts/component.tsx
  • src/content-helper/editor-sidebar/related-posts/store.ts
🧬 Code Graph Analysis (2)
src/content-helper/editor-sidebar/related-posts/component.tsx (2)
src/content-helper/editor-sidebar/related-posts/store.ts (9)
  • RelatedPostsStore (48-119)
  • isFirstRun (106-108)
  • isLoading (109-111)
  • getPosts (112-114)
  • getFilters (115-117)
  • setLoading (83-88)
  • setPosts (89-94)
  • setFirstRun (77-82)
  • setFilters (95-100)
src/content-helper/common/utils/constants.ts (1)
  • PostFilters (52-56)
src/content-helper/editor-sidebar/related-posts/store.ts (2)
src/content-helper/common/utils/constants.ts (1)
  • PostFilters (52-56)
src/content-helper/common/utils/post.tsx (1)
  • PostData (18-30)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: E2E against WordPress latest
🔇 Additional comments (5)
src/content-helper/editor-sidebar/related-posts/component.tsx (5)

9-9: Adoption of useDispatch and useSelect looks good.
These hooks correctly connect the component to the new store for state management.


143-156: Ensure correct re-render behavior with useSelect.
You're returning selectors in an arrow function with an empty dependency array. By default, useSelect subscribes to store updates, so this is valid. However, confirm there's no need to memoize or short-circuit re-renders if the data changes frequently.


225-253: Well-structured async fetch with retries.
The doc block is handled well with @since 3.17.0, and the logic includes retries. Verify that different failure cases (e.g., authentication errors) are handled upstream or remain intentionally unhandled here.


277-293: Filters update logic is clear and complies with coding guidelines.
The updateFilters function uses a well-defined flow, updates the store, and calls fetchPosts. Ensure consistent doc blocks and @since tags remain updated over time.


368-372: Good conditional check to avoid early empty-state message.
The logic for not showing the "No related posts found." message on the first run helps avoid confusing the user before the initial fetch.

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 (5)
tests/js/content-helper/structure.test.tsx (1)

126-130: Add a period at the end of the comment and verify compliance with WordPress guidelines.

The code correctly resets the store in each test for consistency. However, the inline comment should end with a period to meet the requirement requiring each line comment to conclude with a period.

-    // Reset RelatedPostsStore so that <RelatedPostsPanel /> is in the initial state each test
+    // Reset RelatedPostsStore so that <RelatedPostsPanel /> is in the initial state each test.
src/content-helper/editor-sidebar/related-posts/store.ts (4)

1-12: Ensure doc block consistency and completeness.

While the doc block for the file-level explanation includes a @since tag, confirm that all JSDoc comments end with periods and consider whether each doc block needs clarifying, final statements to align with the WordPress coding standard.


13-45: Add JSDoc tags for action interfaces.

Each of these interfaces (e.g., SetFirstRunAction, SetLoadingAction) benefits from a short description and a @since tag to reflect their introduction, aligning with the plugin’s documentation rules for exported or significantly used interfaces.


46-55: Optional: document the defaultState object.

Although this is an internal constant, adding a short doc block (with @since and a final period) can improve clarity regarding default values, especially for new contributors.


57-147: Add JSDoc comments for all action creators.

Currently, only reset() includes a doc block with @since. For completeness and consistency, each action (e.g., setFirstRun, setLoading, setPosts, setFilters) should have a JSDoc comment and a @since annotation describing when it was introduced and what it does. This supports better discoverability and adheres to WordPress coding standards.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c39636 and 913965a.

📒 Files selected for processing (2)
  • src/content-helper/editor-sidebar/related-posts/store.ts (1 hunks)
  • tests/js/content-helper/structure.test.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{js,ts,tsx,jsx}`: "Perform a detailed review of the provided code with following key aspects in mind: - Review the code to ensure it is well-structured and adheres to best ...

**/*.{js,ts,tsx,jsx}: "Perform a detailed review of the provided code with following key aspects in mind:

  • Review the code to ensure it is well-structured and adheres to best practices.
  • Verify compliance with WordPress coding standards.
  • Ensure the code is well-documented.
  • Check for security vulnerabilities and confirm the code is secure.
  • Optimize the code for performance, removing any unnecessary elements.
  • Validate JSDoc comments for accuracy, currency, and adherence to WordPress coding standards.
  • Ensure each line comment concludes with a period.
  • Confirm every JSDoc comment includes a @SInCE tag indicating the next version of the plugin to include the code.
  • Guarantee compatibility with the latest version of WordPress, avoiding deprecated functions or features."
  • tests/js/content-helper/structure.test.tsx
  • src/content-helper/editor-sidebar/related-posts/store.ts
🧬 Code Graph Analysis (2)
tests/js/content-helper/structure.test.tsx (1)
src/content-helper/editor-sidebar/related-posts/store.ts (1)
  • RelatedPostsStore (62-147)
src/content-helper/editor-sidebar/related-posts/store.ts (2)
src/content-helper/common/utils/constants.ts (1)
  • PostFilters (52-56)
src/content-helper/common/utils/post.tsx (1)
  • PostData (18-30)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: E2E against WordPress latest
🔇 Additional comments (3)
tests/js/content-helper/structure.test.tsx (2)

25-27: No concerns regarding these imports.

These imports correctly reference the newly introduced store for resetting state as needed during testing.


32-32: Importing dispatch from @wordpress/data is appropriate.

This enables resetting and dispatching actions on the store, ensuring the test environment is consistently managed.

src/content-helper/editor-sidebar/related-posts/store.ts (1)

149-149: Good practice registering the store.

Registering the store ensures it is recognized by the WordPress data system. This looks correct and aligns with best practices.

@alecgeatches
Copy link
Contributor Author

alecgeatches commented Apr 10, 2025

@acicovic This is ready for review! Note that I ran into some test failures after implementing the store:

 FAIL tests/js/content-helper/structure.test.tsx (6.282 s)
  PCH Editor Sidebar Related Post panel
    ✓ should display spinner when starting (140 ms)
    ✕ should show contact us message when Parse.ly Site ID is not set (29 ms)
    ✕ should show contact us message when Parse.ly API Secret is not set (26 ms)
    ✕ should show error message when API returns the error (27 ms)
    ✕ should show error message and hint when API fetch is failed (25 ms)
    ✕ should show a single post with description and proper attributes (1085 ms)
    ✕ should show 5 posts by default (1066 ms)

These have been addressed, but essentially every test was waiting for the "Loading..." message to appear, but with the store in place this only happens on the first render. There were some other inconsistencies that relied on the previous non-stateful behavior. I tried a few different approaches but what ended up working was adding a reset() action into the store and calling it directly in 913965a.

Let me know if you have any questions or thoughts!

@acicovic acicovic added this to the 3.18.0 milestone Apr 15, 2025
@acicovic acicovic added the Feature: PCI Ticket/PR related to Content Intelligence label Apr 15, 2025
Copy link
Collaborator

@acicovic acicovic left a comment

Choose a reason for hiding this comment

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

Great work!

I really like the before/after presentation, as well as all the details you've given which makes it easier to review the PR and understand why some changes took place.

Noting that I've pushed 6cc87b3, a nitpick commit which doesn't change any functionality.

We're good to merge this, unless you have comments about my own commit. Note that some import reordering was made by VSCode, not me. Thanks!

@alecgeatches
Copy link
Contributor Author

Noting that I've pushed 6cc87b3, a nitpick commit which doesn't change any functionality.

Thank you @acicovic! I've noted those changes.

@alecgeatches alecgeatches merged commit fdbb644 into develop Apr 15, 2025
41 checks passed
@alecgeatches alecgeatches deleted the fix/related-posts-persistence branch April 15, 2025 16:39
github-actions bot added a commit that referenced this pull request Apr 15, 2025
…tence Fix "Related Posts" persistence when sidebar is closed" (fdbb644)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Feature: PCI Ticket/PR related to Content Intelligence

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants