Skip to content

Experimented gallery lightbox feature in ActivityPub articles#22642

Closed
minimaluminium wants to merge 1 commit intomainfrom
ap-article-gallery-zoom-AP-969
Closed

Experimented gallery lightbox feature in ActivityPub articles#22642
minimaluminium wants to merge 1 commit intomainfrom
ap-article-gallery-zoom-AP-969

Conversation

@minimaluminium
Copy link
Member

ref AP-969

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 26, 2025

Walkthrough

The changes enhance the ArticleModal component by integrating image gallery functionality. A new GalleryImage interface is introduced to define image properties such as src, width, height, and an optional alt text. The component now manages state for images, currentIndex, and dialogOpen through hooks. It listens for messages from an iframe to register images and to open a lightbox view by updating the current image index and toggling the dialog. Additionally, keyboard navigation is enabled via a useEffect hook to allow image traversal using the left and right arrow keys. A script within the iframe registers images and sets up click event listeners to communicate with the parent window, thereby ensuring that image interactions update the component state accordingly.

Possibly Related PRs

Suggested Reviewers

  • sagzy

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.

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

Oops! Something went wrong! :(

ESLint: 8.44.0

ESLint couldn't find the plugin "eslint-plugin-react-hooks".

(The package "eslint-plugin-react-hooks" was not found when loaded as a Node module from the directory "/apps/admin-x-activitypub".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react-hooks@latest --save-dev

The plugin "eslint-plugin-react-hooks" was referenced from the config file in "apps/admin-x-activitypub/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 plan to trigger planning for file edits and PR creation.
  • @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.

@minimaluminium minimaluminium marked this pull request as draft March 26, 2025 05:36
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 (2)
apps/admin-x-activitypub/src/components/feed/ArticleModal.tsx (2)

122-137: Missing Escape key handling for closing the lightbox.

While left and right arrow keys are implemented, users typically expect to close lightboxes using the Escape key.

Add Escape key support:

useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
        if (!dialogOpen) {
            return;
        }

        if (e.key === 'ArrowLeft') {
            goToPrevious();
        } else if (e.key === 'ArrowRight') {
            goToNext();
+       } else if (e.key === 'Escape') {
+           setDialogOpen(false);
        }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
}, [dialogOpen, goToNext, goToPrevious, images]);

408-434: Add navigation buttons to the lightbox.

Currently, the lightbox only supports keyboard navigation. Consider adding visible navigation buttons for better usability, especially on touch devices.

<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
    <DialogContent className="max-h-[90vh] max-w-[90vw] overflow-hidden bg-black/90 p-0">
        {currentImage && (
            <div className="relative flex h-full items-center justify-center">
+               {/* Previous button */}
+               {images.length > 1 && (
+                   <button 
+                       className="absolute left-4 top-1/2 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full bg-black/50 text-white hover:bg-black/70"
+                       onClick={(e) => {
+                           e.stopPropagation();
+                           goToPrevious();
+                       }}
+                   >
+                       <Icon name="arrow-left" />
+                   </button>
+               )}
                <div className="flex flex-col items-center">
                    <img
                        alt={currentImage.alt || ''}
                        className="max-h-[80vh] max-w-full object-contain"
                        src={currentImage.src}
                    />

                    {/* Caption and counter */}
                    <div className="w-full p-4 text-center">
                        {currentImage.alt && (
                            <p className="mb-2 text-sm text-white">{currentImage.alt}</p>
                        )}
                        {images.length > 1 && (
                            <p className="text-xs text-white/70">
                                {(currentIndex ?? 0) + 1} / {images.length}
                            </p>
                        )}
                    </div>
                </div>
+               {/* Next button */}
+               {images.length > 1 && (
+                   <button 
+                       className="absolute right-4 top-1/2 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full bg-black/50 text-white hover:bg-black/70"
+                       onClick={(e) => {
+                           e.stopPropagation();
+                           goToNext();
+                       }}
+                   >
+                       <Icon name="arrow-right" />
+                   </button>
+               )}
+               {/* Close button */}
+               <button 
+                   className="absolute right-4 top-4 flex h-10 w-10 items-center justify-center rounded-full bg-black/50 text-white hover:bg-black/70"
+                   onClick={() => setDialogOpen(false)}
+               >
+                   <Icon name="close" />
+               </button>
            </div>
        )}
    </DialogContent>
</Dialog>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc5eeb5 and 7a5c5a9.

📒 Files selected for processing (1)
  • apps/admin-x-activitypub/src/components/feed/ArticleModal.tsx (5 hunks)
🔇 Additional comments (5)
apps/admin-x-activitypub/src/components/feed/ArticleModal.tsx (5)

28-29: Good import addition for lightbox functionality.

The Dialog components from @tryghost/shade are properly imported for the new gallery lightbox feature.


50-55: Good interface definition for gallery images.

The GalleryImage interface is well-structured with appropriate types for image properties.


92-94: State hooks properly set up for the gallery feature.

The useState hooks for managing gallery state (images array, current index, and dialog visibility) are correctly implemented.


113-119: Navigation functions well implemented.

The goToPrevious and goToNext functions correctly handle image navigation with proper boundary handling and state updates.


139-139: Good implementation of current image access.

The current image is correctly determined based on the currentIndex with proper type casting.

Comment on lines +96 to +111
useEffect(() => {
// Listen for messages from the iframe
const handleMessage = (event: MessageEvent) => {
// You might want to check event.origin for security

if (event.data.type === 'REGISTER_IMAGES') {
setImages(event.data.payload);
} else if (event.data.type === 'OPEN_LIGHTBOX') {
setCurrentIndex(event.data.payload.index);
setDialogOpen(true);
}
};

window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, []);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing origin validation in message handler.

The comment on line 99 indicates that origin checking should be implemented for security, but this hasn't been done.

Add validation to prevent potential cross-site scripting attacks:

const handleMessage = (event: MessageEvent) => {
-    // You might want to check event.origin for security
+    // Only accept messages from our own domain
+    if (event.origin !== window.location.origin) {
+        return;
+    }

    if (event.data.type === 'REGISTER_IMAGES') {
📝 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
useEffect(() => {
// Listen for messages from the iframe
const handleMessage = (event: MessageEvent) => {
// You might want to check event.origin for security
if (event.data.type === 'REGISTER_IMAGES') {
setImages(event.data.payload);
} else if (event.data.type === 'OPEN_LIGHTBOX') {
setCurrentIndex(event.data.payload.index);
setDialogOpen(true);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, []);
useEffect(() => {
// Listen for messages from the iframe
const handleMessage = (event: MessageEvent) => {
// Only accept messages from our own domain
if (event.origin !== window.location.origin) {
return;
}
if (event.data.type === 'REGISTER_IMAGES') {
setImages(event.data.payload);
} else if (event.data.type === 'OPEN_LIGHTBOX') {
setCurrentIndex(event.data.payload.index);
setDialogOpen(true);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, []);

Comment on lines +264 to +292
<script>
// When the iframe loads, register all images
function registerImages() {
const allImages = Array.from(document.querySelectorAll('.kg-gallery-card img')).map((img, index) => ({
src: img.src,
alt: img.alt,
index: index
}));

window.parent.postMessage({
type: 'REGISTER_IMAGES',
payload: allImages
}, '*');
}

// Call this when the iframe content loads
window.addEventListener('load', registerImages);

// Add click listeners to your images
document.querySelectorAll('.kg-gallery-card img').forEach((img, index) => {
img.addEventListener('click', (e) => {
e.preventDefault();
window.parent.postMessage({
type: 'OPEN_LIGHTBOX',
payload: { index: index }
}, '*');
});
});
</script>
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

Consider more robust image registration approach.

The current implementation has a few limitations:

  1. It only targets .kg-gallery-card img elements
  2. It may miss images loaded after the script runs
  3. Event listeners might not be cleaned up properly

Consider a more robust implementation:

<script>
+ const registeredImages = [];
+ const registeredImageNodes = new WeakMap();

// When the iframe loads, register all images
function registerImages() {
-  const allImages = Array.from(document.querySelectorAll('.kg-gallery-card img')).map((img, index) => ({
+  // Target all gallery images with a more inclusive selector
+  const allImages = Array.from(document.querySelectorAll('.kg-gallery-card img, .kg-image-card img, .kg-gallery-image img')).map((img, index) => ({
    src: img.src,
    alt: img.alt,
+   width: img.naturalWidth || 0,
+   height: img.naturalHeight || 0,
    index: index
  }));
+  
+  // Store reference to registered images
+  registeredImages.length = 0;
+  registeredImages.push(...allImages);

  window.parent.postMessage({
    type: 'REGISTER_IMAGES',
    payload: allImages
  }, '*');
+
+  // Set up click handlers after registration
+  setupImageClickHandlers();
}

+ // Function to set up click handlers
+ function setupImageClickHandlers() {
+   const imageElements = document.querySelectorAll('.kg-gallery-card img, .kg-image-card img, .kg-gallery-image img');
+   
+   imageElements.forEach((img, index) => {
+     // Remove previous handler if exists
+     if (registeredImageNodes.has(img)) {
+       img.removeEventListener('click', registeredImageNodes.get(img));
+     }
+     
+     const clickHandler = (e) => {
+       e.preventDefault();
+       window.parent.postMessage({
+         type: 'OPEN_LIGHTBOX',
+         payload: { index: index }
+       }, '*');
+     };
+     
+     img.addEventListener('click', clickHandler);
+     registeredImageNodes.set(img, clickHandler);
+     img.style.cursor = 'pointer';
+   });
+ }

// Call this when the iframe content loads
window.addEventListener('load', registerImages);

- // Add click listeners to your images
- document.querySelectorAll('.kg-gallery-card img').forEach((img, index) => {
-   img.addEventListener('click', (e) => {
-     e.preventDefault();
-     window.parent.postMessage({
-       type: 'OPEN_LIGHTBOX',
-       payload: { index: index }
-     }, '*');
-   });
- });

+ // Setup a MutationObserver to detect dynamically added images
+ const observer = new MutationObserver(() => {
+   registerImages();
+ });
+ 
+ // Start observing
+ observer.observe(document.body, {
+   childList: true,
+   subtree: true
+ });
</script>
📝 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
<script>
// When the iframe loads, register all images
function registerImages() {
const allImages = Array.from(document.querySelectorAll('.kg-gallery-card img')).map((img, index) => ({
src: img.src,
alt: img.alt,
index: index
}));
window.parent.postMessage({
type: 'REGISTER_IMAGES',
payload: allImages
}, '*');
}
// Call this when the iframe content loads
window.addEventListener('load', registerImages);
// Add click listeners to your images
document.querySelectorAll('.kg-gallery-card img').forEach((img, index) => {
img.addEventListener('click', (e) => {
e.preventDefault();
window.parent.postMessage({
type: 'OPEN_LIGHTBOX',
payload: { index: index }
}, '*');
});
});
</script>
<script>
const registeredImages = [];
const registeredImageNodes = new WeakMap();
// When the iframe loads, register all images
function registerImages() {
// Target all gallery images with a more inclusive selector
const allImages = Array.from(
document.querySelectorAll(
'.kg-gallery-card img, .kg-image-card img, .kg-gallery-image img'
)
).map((img, index) => ({
src: img.src,
alt: img.alt,
width: img.naturalWidth || 0,
height: img.naturalHeight || 0,
index: index
}));
// Store reference to registered images
registeredImages.length = 0;
registeredImages.push(...allImages);
window.parent.postMessage(
{
type: 'REGISTER_IMAGES',
payload: allImages
},
'*'
);
// Set up click handlers after registration
setupImageClickHandlers();
}
// Function to set up click handlers
function setupImageClickHandlers() {
const imageElements = document.querySelectorAll(
'.kg-gallery-card img, .kg-image-card img, .kg-gallery-image img'
);
imageElements.forEach((img, index) => {
// Remove previous handler if exists
if (registeredImageNodes.has(img)) {
img.removeEventListener('click', registeredImageNodes.get(img));
}
const clickHandler = (e) => {
e.preventDefault();
window.parent.postMessage(
{
type: 'OPEN_LIGHTBOX',
payload: { index: index }
},
'*'
);
};
img.addEventListener('click', clickHandler);
registeredImageNodes.set(img, clickHandler);
img.style.cursor = 'pointer';
});
}
// Call this when the iframe content loads
window.addEventListener('load', registerImages);
// Setup a MutationObserver to detect dynamically added images
const observer = new MutationObserver(() => {
registerImages();
});
// Start observing
observer.observe(document.body, {
childList: true,
subtree: true
});
</script>

@ErisDS
Copy link
Member

ErisDS commented Aug 4, 2025

Cleaning up older PRs 💅

@ErisDS ErisDS closed this Aug 4, 2025
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