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 post delete mutation for posts in the admin-x-activitypub app #22330

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mike182uk
Copy link
Member

refs AP-806

Added post delete mutation for posts in the admin-x-activitypub app

Copy link
Contributor

coderabbitai bot commented Mar 3, 2025

Warning

Rate limit exceeded

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

⌛ How to resolve this issue?

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

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

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between da2d8ae and f59aa81.

📒 Files selected for processing (9)
  • apps/admin-x-activitypub/src/api/activitypub.ts (5 hunks)
  • apps/admin-x-activitypub/src/components/feed/ArticleModal.tsx (8 hunks)
  • apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (6 hunks)
  • apps/admin-x-activitypub/src/components/modals/ViewProfileModal.tsx (1 hunks)
  • apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (5 hunks)
  • apps/admin-x-activitypub/src/utils/posts.ts (1 hunks)
  • apps/admin-x-activitypub/src/views/Inbox/Inbox.tsx (1 hunks)
  • apps/admin-x-activitypub/src/views/Profile/Profile.tsx (2 hunks)
  • apps/admin-x-activitypub/test/unit/utils/posts.test.ts (1 hunks)

Walkthrough

The changes introduce a new exported interface Account and a boolean property authoredByMe to the Post interface, indicating if the post was authored by the current user. The fetchJSON method in the ActivityPubAPI class has been updated to accept a DELETE HTTP method, enabling deletion requests. A new delete method is added to construct a URL for deleting a post by its ID. The FeedItem component is enhanced to allow users to delete posts through a confirmation dialog and a new menu item. A new hook, useDeleteMutationForUser, is introduced to manage post deletions and optimistically update the cache. Additionally, the mapPostToActivity function now includes an authored property based on the authoredByMe flag.

Possibly related PRs

Suggested labels

browser-tests

Suggested reviewers

  • djordjevlais

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

@mike182uk mike182uk force-pushed the mike-ap-806-wire-up-the-delete-buttons-to-the-deleteid-api branch from a4716b4 to 11cd1a5 Compare March 3, 2025 16:27
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: 2

🧹 Nitpick comments (3)
apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (1)

819-882: Comprehensive implementation with room for improvement in cache management

The implementation is solid, handling optimistic updates and error recovery for feed and inbox. However, despite defining query keys for outboxQueryKey, likedQueryKey, and profilePostsQueryKey, the code doesn't update these caches optimistically, which could lead to stale data.

Consider updating all defined caches to maintain consistent state across the application. Here's a suggestion for extending the optimistic updates:

onMutate: (id) => {
    // Find the post in the feed query cache
    const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(feedQueryKey);
    queryClient.setQueryData(feedQueryKey, (current?: {pages: {posts: Activity[]}[]}) => {
        if (!current) {
            return current;
        }

        return {
            ...current,
            pages: current.pages.map((page: {posts: Activity[]}) => {
                return {
                    ...page,
                    posts: page.posts.filter((item: Activity) => item.id !== id)
                };
            })
        };
    });

    // Find the post in the inbox query cache
    const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(inboxQueryKey);
    queryClient.setQueryData(inboxQueryKey, (current?: {pages: {posts: Activity[]}[]}) => {
        if (!current) {
            return current;
        }

        return {
            ...current,
            pages: current.pages.map((page: {posts: Activity[]}) => {
                return {
                    ...page,
                    posts: page.posts.filter((item: Activity) => item.id !== id)
                };
            })
        };
    });

+   // Also update outbox, liked, and profile posts caches
+   const previousOutbox = queryClient.getQueryData<{pages: {data: Activity[]}[]}[]>(outboxQueryKey);
+   queryClient.setQueryData(outboxQueryKey, (current?: {pages: {data: Activity[]}[]}) => {
+       if (!current) {
+           return current;
+       }
+
+       return {
+           ...current,
+           pages: current.pages.map((page: {data: Activity[]}) => {
+               return {
+                   ...page,
+                   data: page.data.filter((item: Activity) => item.id !== id)
+               };
+           })
+       };
+   });
+
+   // Similar updates for likedQueryKey and profilePostsQueryKey
+   
    return {
        previousFeed,
        previousInbox,
+       previousOutbox,
+       // Add other previous states
    };
},
onError: (_err, _variables, context) => {
    queryClient.setQueryData(feedQueryKey, context?.previousFeed);
    queryClient.setQueryData(inboxQueryKey, context?.previousInbox);
+   queryClient.setQueryData(outboxQueryKey, context?.previousOutbox);
+   // Restore other caches
}
apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (2)

218-224: Improve user confirmation UX for delete operation

The current confirmation dialog is minimal and only shows the post ID, which isn't user-friendly. Consider showing a more descriptive message that includes some content from the post.

const handleDelete = (postId: string) => {
-   const confirm = window.confirm(`Delete post\n\n${postId}\n\n?`);
+   // Get a readable post identifier (title or first few characters of content)
+   const postIdentifier = object.name || 
+       (object.content ? stripHtml(object.content).substring(0, 50) + '...' : 'this post');
+   const confirm = window.confirm(`Are you sure you want to delete "${postIdentifier}"?\n\nThis action cannot be undone.`);

    if (confirm) {
        deletePostMutation.mutate(postId);
    }
};

259-265: Remove TODO comment

The TODO comment about deleting posts can now be removed since you've implemented the functionality.

- // TODO: If this is your own Note/Article, you should be able to delete it
- // menuItems.push({
- //     id: 'delete',
- //     label: 'Delete',
- //     destructive: true,
- //     onClick: handleDelete
- // });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 453cf69 and 11cd1a5.

📒 Files selected for processing (4)
  • apps/admin-x-activitypub/src/api/activitypub.ts (4 hunks)
  • apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (4 hunks)
  • apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (1 hunks)
  • apps/admin-x-activitypub/src/utils/posts.ts (1 hunks)
🔇 Additional comments (7)
apps/admin-x-activitypub/src/utils/posts.ts (1)

107-107: LGTM! Appropriate handling of author status.

The explicit comparison === true ensures that the property is boolean, avoiding potential issues with falsy values. This change properly supports the post deletion feature being implemented.

apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (2)

195-195: LGTM! Good initialization of the delete mutation hook.

The hook is properly initialized with 'index' as the handle parameter.


251-257: LGTM! Appropriate conditional rendering of delete option

The delete menu item is correctly displayed only when the post is authored by the current user, ensuring proper access control.

apps/admin-x-activitypub/src/api/activitypub.ts (4)

104-104: LGTM! Clear interface extension.

Adding the authoredByMe boolean property to the Post interface is a clean way to track post ownership.


137-137: Type update correctly expands HTTP method support

The update to include 'DELETE' as a valid method type is appropriate and follows TypeScript best practices.


151-155: Proper handling of HTTP 204 No Content responses

The implementation correctly handles 204 status code responses by returning null, which is appropriate for successful deletion operations that don't return content.


307-310: Well-implemented delete method

The delete method follows the established pattern in the class, using the appropriate URL structure and HTTP method. The implementation is clean and consistent with the codebase's style.

Comment on lines 837 to 838
const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(feedQueryKey);
queryClient.setQueryData(feedQueryKey, (current?: {pages: {posts: Activity[]}[]}) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix type assertion in getQueryData

The type assertion <{pages: {posts: Activity[]}[]}[]> doesn't match the structure returned by the query. This could lead to runtime type errors.

- const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(feedQueryKey);
+ const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}>(feedQueryKey);
📝 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
const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(feedQueryKey);
queryClient.setQueryData(feedQueryKey, (current?: {pages: {posts: Activity[]}[]}) => {
const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}>(feedQueryKey);
queryClient.setQueryData(feedQueryKey, (current?: {pages: {posts: Activity[]}[]}) => {

Comment on lines 855 to 856
const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(inboxQueryKey);
queryClient.setQueryData(inboxQueryKey, (current?: {pages: {posts: Activity[]}[]}) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix type assertion in getQueryData

Same issue as previous comment - the type assertion doesn't match the structure returned by the query.

- const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(inboxQueryKey);
+ const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}>(inboxQueryKey);
📝 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
const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(inboxQueryKey);
queryClient.setQueryData(inboxQueryKey, (current?: {pages: {posts: Activity[]}[]}) => {
const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}>(inboxQueryKey);
queryClient.setQueryData(inboxQueryKey, (current?: {pages: {posts: Activity[]}[]}) => {

@mike182uk mike182uk force-pushed the mike-ap-806-wire-up-the-delete-buttons-to-the-deleteid-api branch 3 times, most recently from 7f85b92 to b36ce55 Compare March 4, 2025 10:41
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

♻️ Duplicate comments (2)
apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (2)

837-837: ⚠️ Potential issue

Fix type assertion in getQueryData

The type assertion <{pages: {posts: Activity[]}[]}[]> doesn't match the expected structure returned by the query.

- const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(QUERY_KEYS.feed);
+ const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}>(QUERY_KEYS.feed);

856-856: ⚠️ Potential issue

Fix type assertion in getQueryData for inbox

The type assertion has the same issue as the previous one.

- const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(QUERY_KEYS.inbox);
+ const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}>(QUERY_KEYS.inbox);
🧹 Nitpick comments (2)
apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (2)

218-225: Replace window.confirm with a proper modal for better UX.

The confirmation currently uses a basic window.confirm() dialog, which doesn't align with the design system used throughout the application. This is correctly identified by your TODO comment.

Consider implementing a modal dialog using the design system's components for a more consistent user experience.

const handleDelete = (postId: string) => {
-    // @TODO: Show confirmation modal
-    const confirm = window.confirm(`Delete post\n\n${postId}\n\n?`);
-
-    if (confirm) {
+    // Use a design-system modal component instead of window.confirm
+    showModal({
+        title: 'Delete post',
+        description: `Are you sure you want to delete this post?`,
+        confirmLabel: 'Delete',
+        cancelLabel: 'Cancel',
+        destructive: true,
+        onConfirm: () => {
         deleteMutation.mutate(postId);
-    }
+        }
+    });
};

260-266: Remove commented-out code that's now implemented.

The commented-out code is now obsolete since you've implemented the delete functionality. It should be removed to maintain code cleanliness.

-// TODO: If this is your own Note/Article, you should be able to delete it
-// menuItems.push({
-//     id: 'delete',
-//     label: 'Delete',
-//     destructive: true,
-//     onClick: handleDelete
-// });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 11cd1a5 and b36ce55.

📒 Files selected for processing (4)
  • apps/admin-x-activitypub/src/api/activitypub.ts (4 hunks)
  • apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (4 hunks)
  • apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (2 hunks)
  • apps/admin-x-activitypub/src/utils/posts.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/admin-x-activitypub/src/utils/posts.ts
  • apps/admin-x-activitypub/src/api/activitypub.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Setup
🔇 Additional comments (5)
apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (3)

15-15: Appropriate import for the new delete functionality.

Good job adding the import for the delete mutation hook which will be used to implement post deletion.


195-195: The deletion capability is properly initialized.

Creating the mutation with the 'index' handle parameter is appropriate. This allows the component to perform deletion operations against the ActivityPub API.


252-258: Conditional menu item correctly checks post ownership.

The delete menu item is appropriately shown only for posts authored by the current user, which ensures users can only delete their own content.

apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (2)

67-73: Thread query key properly handles null ID case.

Good modification to handle the case when a thread ID is null. This allows for more flexible thread querying operations, which will be useful when managing thread-related operations.


825-913: Well-implemented deletion mutation with optimistic updates

The implementation follows best practices for React Query mutations:

  1. It provides optimistic updates to immediately reflect the deletion in the UI
  2. It handles all relevant caches (feed, inbox, thread)
  3. It implements proper error handling with cache restoration

This creates a smooth user experience while maintaining data consistency.

However, consider adding a success callback parameter to allow components to show success notifications:

export function useDeleteMutationForUser(handle: string) {
    const queryClient = useQueryClient();

    return useMutation({
        async mutationFn(id: string) {
            const siteUrl = await getSiteUrl();
            const api = createActivityPubAPI(handle, siteUrl);

            return api.delete(id);
        },
+       onSuccess: () => {
+           // Show success toast or trigger callback if provided
+           showToast({
+               title: 'Post deleted successfully',
+               type: 'success'
+           });
+       },
        onMutate: (id) => {
            // ... existing optimistic update code
        },
        onError: (_err, _variables, context) => {
            if (!context) {
                return;
            }

            queryClient.setQueryData(context.previousFeed.key, context.previousFeed.data);
            queryClient.setQueryData(context.previousInbox.key, context.previousInbox.data);
            queryClient.setQueryData(context.previousThreads.key, context.previousThreads.data);
+           
+           // Show error toast
+           showToast({
+               title: 'Failed to delete post',
+               type: 'error'
+           });
        }
    });
}

Comment on lines 875 to 912
const threadQueryKey = QUERY_KEYS.thread(null);
const previousThreads = queryClient.getQueryData<{posts: Activity[]}>(threadQueryKey);
Copy link
Contributor

@coderabbitai coderabbitai bot Mar 4, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Thread cache update should be more specific

Using a null ID for the thread query key is too broad - it might affect all thread queries rather than just the specific thread containing the deleted post. Consider using specific thread IDs when possible.


🏁 Script executed:

#!/bin/bash
# Check how the thread query key is used in the codebase
rg -A 5 "QUERY_KEYS.thread"

Length of output: 1278


Thread cache update should target a specific thread

The current implementation uses QUERY_KEYS.thread(null), which creates an overly broad cache key and may inadvertently update all thread queries rather than just the thread associated with the deleted post. For consistency and to prevent unexpected cache invalidation, please update this usage to use the appropriate thread ID (as seen elsewhere with QUERY_KEYS.thread(id)).

  • Update the cache key to use the specific thread ID instead of null in this file (apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts, lines 875-876).

Copy link
Member Author

Choose a reason for hiding this comment

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

Post can appear in multiple threads which is why we can't target a single thread here

Copy link
Contributor

Choose a reason for hiding this comment

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

@mike182uk Thank you for clarifying that approach. I understand now - since posts can appear in multiple threads, using QUERY_KEYS.thread(null) is actually the correct strategy here as it allows you to update all thread caches that might contain the deleted post rather than targeting just a single thread.

This is a good implementation choice given the requirements. I'll note this information for future reviews.


✏️ Learnings added
Learnt from: mike182uk
PR: TryGhost/Ghost#22330
File: apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts:911-912
Timestamp: 2025-03-04T17:19:50.786Z
Learning: In the ActivityPub app, posts can appear in multiple threads, so when updating thread caches (e.g., when deleting a post), using QUERY_KEYS.thread(null) is the appropriate approach to update all thread caches rather than targeting a specific thread.

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.

@mike182uk mike182uk force-pushed the mike-ap-806-wire-up-the-delete-buttons-to-the-deleteid-api branch from b36ce55 to 2c34fad Compare March 4, 2025 15:30
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: 2

🧹 Nitpick comments (3)
apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (1)

933-934: Profile posts cache update is too broad

Similar to the thread query issue, using QUERY_KEYS.profilePosts(null) creates a broad cache key that may affect all profile posts queries rather than just those for the specific user. Consider using the handle of the user performing the deletion to target only their profile posts.

- const profilePostsQueryKey = QUERY_KEYS.profilePosts(null);
+ const profilePostsQueryKey = QUERY_KEYS.profilePosts(handle);
apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (2)

232-239: Replace window.confirm with a proper modal dialog

The TODO comment indicates the intention to use a confirmation modal, but the current implementation uses window.confirm, which doesn't match the design system of the application.

Consider implementing a proper confirmation dialog using the application's design system components for a consistent user experience. For example, using a modal component from @tryghost/admin-x-design-system would be more consistent with the rest of the application.


274-280: Remove commented-out code

The commented-out code for the delete menu item is now redundant since you've implemented the functionality above. It should be removed to keep the codebase clean.

- // TODO: If this is your own Note/Article, you should be able to delete it
- // menuItems.push({
- //     id: 'delete',
- //     label: 'Delete',
- //     destructive: true,
- //     onClick: handleDelete
- // });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b36ce55 and 2c34fad.

📒 Files selected for processing (8)
  • apps/admin-x-activitypub/src/api/activitypub.ts (4 hunks)
  • apps/admin-x-activitypub/src/components/feed/ArticleModal.tsx (3 hunks)
  • apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (6 hunks)
  • apps/admin-x-activitypub/src/components/modals/ViewProfileModal.tsx (1 hunks)
  • apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (3 hunks)
  • apps/admin-x-activitypub/src/utils/posts.ts (1 hunks)
  • apps/admin-x-activitypub/src/views/Inbox/Inbox.tsx (1 hunks)
  • apps/admin-x-activitypub/src/views/Profile/Profile.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/admin-x-activitypub/src/utils/posts.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Unit tests (Node 22.13.1)
  • GitHub Check: Unit tests (Node 20.11.1)
  • GitHub Check: Unit tests (Node 18.12.1)
  • GitHub Check: Lint
🔇 Additional comments (20)
apps/admin-x-activitypub/src/components/modals/ViewProfileModal.tsx (1)

172-172: Added post deletion capability based on authorship.

The new allowDelete prop appropriately controls whether deletion functionality is available based on the post's authorship status. This ensures users can only delete posts they've authored.

apps/admin-x-activitypub/src/views/Inbox/Inbox.tsx (1)

93-93: Deletion permissions properly restricted to post authors.

The allowDelete prop implementation correctly restricts deletion functionality to posts authored by the current user, maintaining proper authorization boundaries.

apps/admin-x-activitypub/src/components/feed/ArticleModal.tsx (3)

861-862: Appropriate disabling of delete capability for thread parents.

Setting allowDelete to false for thread parents is correct since users shouldn't be able to delete parent posts in a thread that they didn't author. This maintains thread integrity.


882-883: Comprehensive permission check for post deletion.

The implementation correctly considers both authorship (object.authored) and thread context (threadParents.length === 0). This ensures users can only delete their own posts and only when they aren't replies in a thread, which prevents orphaned replies.


950-951: Thread reply deletion permissions properly implemented.

Setting allowDelete based on item.object.authored ensures users can only delete their own replies in a thread, maintaining proper authorization boundaries while allowing for normal thread management.

apps/admin-x-activitypub/src/api/activitypub.ts (4)

104-104: Implementation of authoredByMe property is correct

Adding the authoredByMe boolean to the Post interface will help determine whether the current user has permission to delete a post.


137-137: Method signature correctly updated to include DELETE method

The fetchJSON method signature has been properly updated to include DELETE alongside the existing GET and POST HTTP methods.


152-154: Good handling of 204 No Content responses

Returning null for 204 (No Content) responses is appropriate, as these responses don't contain a response body to parse as JSON.


307-310: Implementation of delete method follows established patterns

The delete method implementation is concise and follows the same pattern as other API methods in this class, ensuring consistency in the codebase.

apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (6)

50-55: Query key structure for handling null parameters is appropriate

The modification to profilePosts query key function to handle null parameters is well implemented, supporting the cache update needs in the delete mutation.


72-77: Query key structure for handling null parameters is appropriate

Similar to the profilePosts modification, the thread query key function has been updated to handle null parameters correctly.


841-841: Fix type assertion in getQueryData

The type assertion <{pages: {posts: Activity[]}[]}[]> doesn't match the structure returned by the query. This could lead to runtime type errors.

- const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(QUERY_KEYS.feed);
+ const previousFeed = queryClient.getQueryData<{pages: {posts: Activity[]}[]}>(QUERY_KEYS.feed);

860-860: Fix type assertion in getQueryData

Same issue as previous comment - the type assertion doesn't match the structure returned by the query.

- const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}[]>(QUERY_KEYS.inbox);
+ const previousInbox = queryClient.getQueryData<{pages: {posts: Activity[]}[]}>(QUERY_KEYS.inbox);

879-880: Thread cache update should target a specific thread

The current implementation uses QUERY_KEYS.thread(null), which creates an overly broad cache key and may inadvertently update all thread queries rather than just the thread associated with the deleted post. For consistency and to prevent unexpected cache invalidation, please update this usage to use the appropriate thread ID (as seen elsewhere with QUERY_KEYS.thread(id)).


829-992: Well implemented delete mutation function with optimistic updates

The useDeleteMutationForUser function is well structured, following the established pattern in the codebase for mutation functions. It properly:

  1. Initializes the mutation function with the appropriate API call
  2. Implements optimistic updates for all relevant caches
  3. Provides context for error handling and rollback
  4. Returns proper types

Despite the minor issues noted in other comments, this implementation is solid and will handle deletion workflow effectively.

apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (5)

15-15: Import for delete mutation hook is appropriately added

The import for useDeleteMutationForUser is correctly added to support the new deletion functionality.


172-172: New prop for deletion permissions is well designed

The optional allowDelete property in the FeedItemProps interface is a good approach for conditionally enabling delete functionality based on post ownership.


187-200: Component parameter list with default value is correctly implemented

The component signature is properly updated to include the new allowDelete prop with a sensible default value of false.


209-209: Delete mutation hook is properly initialized

The deleteMutation is correctly initialized using the useDeleteMutationForUser hook with the 'index' handle.


266-272: Delete menu item implementation is well integrated

The conditional rendering of the delete menu item based on the allowDelete prop is well implemented and integrates smoothly with the existing menu structure.

Comment on lines 187 to 188
allowDelete={true} // TODO: Only true if the user is the author
layout='feed'
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

TODO comment identifies a permission inconsistency.

The TODO comment correctly identifies that the current implementation doesn't properly restrict deletion permissions for liked content. Users should only be able to delete content they authored, not all content they've liked.

Implement the condition as suggested in the TODO:

-allowDelete={true} // TODO: Only true if the user is the author
+allowDelete={activity.object?.authoredByMe === true}
📝 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
allowDelete={true} // TODO: Only true if the user is the author
layout='feed'
allowDelete={activity.object?.authoredByMe === true}
layout='feed'

@@ -146,6 +146,7 @@
>
<FeedItem
actor={activity.actor}
allowDelete={true}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Unconditional deletion permission requires validation.

Setting allowDelete to true unconditionally for posts in the user's profile might be appropriate since users should be able to delete their own posts. However, this differs from the pattern in other components where deletion is conditionally based on the authored property, which could lead to inconsistent behavior.

To ensure this approach is intentional, let's check if other components follow this pattern:


🏁 Script executed:

#!/bin/bash
# Find all places where allowDelete is set and check if there are inconsistencies in its usage

rg -A 5 -B 5 "allowDelete" --type tsx

Length of output: 65


Let's re-run the search with a query that correctly targets TSX files. The previous command failed because --type tsx isn’t recognized by rg. We can instead use the built-in type for TypeScript React files. Please verify by running the following shell script:

This should help confirm if other components conditionally set allowDelete (perhaps based on the authored property) or if the behavior in apps/admin-x-activitypub/src/views/Profile/Profile.tsx is consistent with the rest of the codebase.


🏁 Script executed:

#!/bin/bash
rg -A 5 -B 5 "allowDelete" -t typescriptreact

Length of output: 85


Let's run an updated search script that targets TSX files using a filename glob pattern. This script will search for both allowDelete and authored patterns to check if other components use conditional deletion permission.


🏁 Script executed:

#!/bin/bash
echo "Searching for 'allowDelete' in TSX files:"
rg -A 5 -B 5 "allowDelete" -g "*.tsx"

echo -e "\nSearching for 'authored' in TSX files:"
rg -A 5 -B 5 "authored" -g "*.tsx"

Length of output: 17911


Subject: Inconsistent Deletion Permission in Profile.tsx

We found that the Profile view sets allowDelete unconditionally to true (line 149), whereas other components (like in Inbox, ArticleModal, and ViewProfileModal) conditionally enable deletion based on the post’s authored property. There's even a TODO comment in Profile.tsx suggesting this needs review. Please verify if this design is intentional. If not, consider updating Profile.tsx to align with the conditional check—e.g., using activity.object.authored—to ensure users can delete only their own posts.

@mike182uk mike182uk force-pushed the mike-ap-806-wire-up-the-delete-buttons-to-the-deleteid-api branch 3 times, most recently from 751c53a to da2d8ae Compare March 4, 2025 20:54
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 751c53a and da2d8ae.

📒 Files selected for processing (9)
  • apps/admin-x-activitypub/src/api/activitypub.ts (5 hunks)
  • apps/admin-x-activitypub/src/components/feed/ArticleModal.tsx (8 hunks)
  • apps/admin-x-activitypub/src/components/feed/FeedItem.tsx (6 hunks)
  • apps/admin-x-activitypub/src/components/modals/ViewProfileModal.tsx (1 hunks)
  • apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (5 hunks)
  • apps/admin-x-activitypub/src/utils/posts.ts (1 hunks)
  • apps/admin-x-activitypub/src/views/Inbox/Inbox.tsx (1 hunks)
  • apps/admin-x-activitypub/src/views/Profile/Profile.tsx (2 hunks)
  • apps/admin-x-activitypub/test/unit/utils/posts.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • apps/admin-x-activitypub/src/components/modals/ViewProfileModal.tsx
  • apps/admin-x-activitypub/src/utils/posts.ts
  • apps/admin-x-activitypub/src/views/Inbox/Inbox.tsx
  • apps/admin-x-activitypub/src/api/activitypub.ts
  • apps/admin-x-activitypub/src/components/feed/ArticleModal.tsx
  • apps/admin-x-activitypub/src/components/feed/FeedItem.tsx
  • apps/admin-x-activitypub/src/views/Profile/Profile.tsx
🔇 Additional comments (16)
apps/admin-x-activitypub/test/unit/utils/posts.test.ts (1)

42-42: Good addition of authoredByMe property

The addition of the authoredByMe property to the post test fixture is appropriate and aligns with the implementation of deletion functionality. This ensures the test properly validates the mapping of this property.

apps/admin-x-activitypub/src/hooks/use-activity-pub-queries.ts (15)

2-2: Good addition of Account type import

The Account type import is correctly added to support the new deletion functionality, as it's referenced in the implementation of the useDeleteMutationForUser function.


51-56: Well-structured and type-safe query key handling

The updated profilePosts function now properly handles null values, following a consistent pattern that returns an appropriate key array. This allows for targeting either specific profile posts or all profile posts collectively.


73-78: Consistent query key pattern implementation

The thread query key handling follows the same pattern as the profilePosts function, correctly handling both null and string ID cases. This is good for code consistency and facilitates global cache invalidation.


650-652: Good inclusion of authorship information

Setting the authored property ensures that newly created notes are correctly marked as being authored by the current user, which is essential for determining deletion permissions in the UI.


833-842: Well-implemented mutation hook for post deletion

The useDeleteMutationForUser function is well-structured, accepting the user handle and creating a mutation that calls the appropriate API method. The mutation function correctly handles both post ID and optional parent ID parameters.


843-876: Comprehensive feed cache updates for post deletion

The feed cache update logic thoroughly:

  1. Removes the deleted post from the feed
  2. Updates the parent post's reply count when appropriate
  3. Uses proper type narrowing with !current checks

This approach ensures consistent user experience after deletion.


877-910: Inbox cache update follows consistent pattern

The inbox cache update logic follows the same pattern as the feed update, maintaining code consistency while providing proper optimistic updates for the inbox.


911-938: Thread cache invalidation is properly implemented

The thread cache update correctly:

  1. Uses the global thread query key (null)
  2. Properly removes the deleted post from all relevant threads
  3. Updates parent posts' reply counts

This follows the established pattern to ensure all instances of a post are removed from cached thread data.


915-916: Thread cache update targets all thread data appropriately

Using QUERY_KEYS.thread(null) is the correct approach since a post can appear in multiple threads. This allows the operation to update all thread caches rather than targeting a specific thread.


939-959: Well-handled outbox cache update

The outbox cache update properly:

  1. Uses the correct query key based on the user handle
  2. Filters out the deleted post from each page of data
  3. Maintains the overall structure of the outbox data

This ensures that the user's outbox is immediately updated after post deletion.


960-983: Smart approach for liked posts cache update

The liked posts cache update includes tracking whether the post was removed from the liked collection, which is then used to determine if the account's liked count needs to be updated. This attention to detail ensures data consistency.


984-1004: Comprehensive profile posts cache update

The profile posts cache update uses the global query key to update all profile posts caches, ensuring that the deleted post is removed from all relevant profile views regardless of which profile they appear in.


1005-1025: Conditional account cache update based on like status

The account cache update is only performed if the post was removed from the liked collection, which is an efficient approach that avoids unnecessary updates. The like count is also properly bounded to avoid negative values.


1026-1057: Well-structured context object for error handling

The return object for the mutation context is well-organized, containing all previous cache states needed for restoration in case of error. The conditional inclusion of previous account data based on whether it was updated is a nice optimization.


1058-1073: Robust error handling with complete cache restoration

The onError handler thoroughly restores all cache states to their previous values if the mutation fails, providing a seamless rollback. The null check for context and conditional restoration of account data show careful attention to edge cases.

@mike182uk mike182uk force-pushed the mike-ap-806-wire-up-the-delete-buttons-to-the-deleteid-api branch from da2d8ae to f59aa81 Compare March 4, 2025 21:06
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.

1 participant