Skip to content

Conversation

tindevw
Copy link
Contributor

@tindevw tindevw commented Mar 5, 2025

Description

Added a ShareButton component and implemented it in events, so people can share the link to different platforms or get it copied to clipboard.

Result

Description:
Added a sharebutton to events under "Food allergies". First after-photo in Safari. Second in Firefox as a link.

Before

Screenshot 2025-03-05 at 21 58 15

After

Screenshot 2025-03-05 at 21 58 47 Screenshot 2025-03-05 at 21 41 27

If you've made visual changes, please check the boxes below and include images showing the changes. Descriptions are appreciated.

  • Changes look good on both light and dark theme.
  • Changes look good with different viewports (mobile, tablet, etc.).
  • Changes look good with slower Internet connections.

Caution

Make sure your images do not contain any real user information.

Testing

  • I have thoroughly tested my changes.

Please describe what and how the changes have been tested, and provide instructions to reproduce if necessary.


Resolves ABA-1177

@tindevw tindevw added review-needed Pull requests that need review new-feature Pull requests that introduce a new feature labels Mar 5, 2025
Copy link

linear bot commented Mar 5, 2025

Copy link

vercel bot commented Mar 5, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
lego-bricks-storybook ⬜️ Ignored (Inspect) Visit Preview Mar 19, 2025 8:10pm

Copy link
Member

@eikhr eikhr left a comment

Choose a reason for hiding this comment

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

Looks very good! Very nice feature:)

I added some small comments and I would love to have a share button on JobListings as well!

@eikhr eikhr force-pushed the add-ShareButton branch from 6ff06a5 to 65d7ac3 Compare March 5, 2025 21:51
@eikhr
Copy link
Member

eikhr commented Mar 5, 2025

I rebased this for you because my vite PR created a bunch of merge conflicts. To start working locally again just do git reset --hard origin/add-ShareButton (will delete all local changes and replace with the version from github)

Copy link
Member

@ivarnakken ivarnakken left a comment

Choose a reason for hiding this comment

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

Very cool!

Comment on lines 315 to 320
{loggedIn && (
<ShareButton
title={event?.title || 'Sjekk ut dette arrangementet!'}
url={`${appConfig?.webUrl}/events/${event?.id}`}
/>
)}
Copy link
Member

Choose a reason for hiding this comment

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

I suggest moving this down to comments and reactions, as I feel that's common. The sidebar should really only contain information and details regarding the event, while the bottom section contains "user interactions".

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Looks a bit out of place
Screenshot 2025-03-12 at 20 44 55
This is before:
image

Copy link
Member

Choose a reason for hiding this comment

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

I like having it in the sidebar, but an alternative might be to the right of "Kommentarer":
Screenshot 2025-04-04 at 17 39 44

@tindevw
Copy link
Contributor Author

tindevw commented Mar 12, 2025

Updated changes:

Events:
Screenshot 2025-03-12 at 20 51 09

Joblisting:
image

Which icon looks better?

image
image

tindevw and others added 2 commits March 12, 2025 21:16
Co-authored-by: viljeno <[email protected]>
@tindevw tindevw requested review from ivarnakken and eikhr March 12, 2025 20:21
Copy link
Contributor

@itsisak itsisak left a comment

Choose a reason for hiding this comment

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

LGTM!

Copy link
Contributor

coderabbitai bot commented Mar 19, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new ShareButton component and integrates it into the event and job listing detail pages. The ShareButton component allows users to share content by checking for Web Share API support; if available, it uses navigator.share, otherwise it copies the URL to the clipboard and dispatches a toast notification. The component is configured with dynamic titles and URLs for each respective page.

Changes

File(s) Summary
lego-webapp/components/ShareButton/index.tsx Added a new ShareButton component that accepts title and url props. Implements the handleShare function which checks for Web Share API support, calls navigator.share if available or uses navigator.clipboard.writeText as a fallback, and dispatches a toast notification. Utilizes components from @webkom/lego-bricks and lucide-react.
lego-webapp/pages/events/@eventIdOrSlug/+Page.tsx, lego-webapp/pages/joblistings/@joblistingIdOrSlug/+Page.tsx Imported and integrated the ShareButton component. In the events page, it is rendered after a visual separator with the title "Del arrangement" and a URL built using the event ID. In the job listings page, it appears in the ContentSidebar before admin controls with the title "Del jobbannonse" and a URL based on the job listing ID.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant SB as ShareButton Component
    participant API as Web APIs

    U->>SB: Click Share Button
    SB->>API: Check if navigator.canShare(url)
    alt Web Share API Supported
        SB->>API: Call navigator.share({ title, url })
    else API Not Supported
        SB->>API: Call navigator.clipboard.writeText(url)
    end
    SB->>SB: Dispatch toast notification
Loading

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 92215c0 and ab80425.

📒 Files selected for processing (3)
  • lego-webapp/components/ShareButton/index.tsx (1 hunks)
  • lego-webapp/pages/events/@eventIdOrSlug/+Page.tsx (2 hunks)
  • lego-webapp/pages/joblistings/@joblistingIdOrSlug/+Page.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
lego-webapp/components/ShareButton/index.tsx

[error] 17-19: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
lego-webapp/pages/joblistings/@joblistingIdOrSlug/+Page.tsx (1)

240-243: ShareButton implementation looks good.

The ShareButton is appropriately placed in the sidebar with a clear title and correctly constructs the URL using the job listing's ID.

lego-webapp/pages/events/@eventIdOrSlug/+Page.tsx (1)

312-315: ShareButton implementation looks good.

The ShareButton is appropriately placed in the sidebar after a divider line. The title is clear and the URL is correctly constructed using the event's ID.

lego-webapp/components/ShareButton/index.tsx (2)

6-9: Props type definition looks good.

The Props interface clearly defines the required properties for the ShareButton component.


29-36: Button implementation is correct.

The button is well-structured with appropriate layout, icon, and text. Previous reviewer comments about using only an icon were addressed by retaining the text as requested.

Comment on lines +13 to +27
const handleShare = async () => {
if (navigator?.canShare?.({ title, url })) {
navigator.share({ title, url });
} else {
{
navigator.clipboard.writeText(url);
}
dispatch(
addToast({
message: 'Link er kopiert til utklippstavlen',
type: 'success',
}),
);
}
};
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 unnecessary block statement and add error handling.

The share functionality works as expected, but there's an unnecessary block statement and error handling should be added for clipboard and share operations.

const handleShare = async () => {
  if (navigator?.canShare?.({ title, url })) {
-    navigator.share({ title, url });
+    try {
+      await navigator.share({ title, url });
+    } catch (error) {
+      console.error('Error sharing:', error);
+      await copyToClipboard();
+    }
  } else {
-    {
-      navigator.clipboard.writeText(url);
-    }
-    dispatch(
-      addToast({
-        message: 'Link er kopiert til utklippstavlen',
-        type: 'success',
-      }),
-    );
+    await copyToClipboard();
+  }
+};
+
+const copyToClipboard = async () => {
+  try {
+    await navigator.clipboard.writeText(url);
+    dispatch(
+      addToast({
+        message: 'Link er kopiert til utklippstavlen',
+        type: 'success',
+      }),
+    );
+  } catch (error) {
+    console.error('Error copying to clipboard:', error);
+    dispatch(
+      addToast({
+        message: 'Kunne ikke kopiere link',
+        type: 'error',
+      }),
+    );
  }
};
📝 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 handleShare = async () => {
if (navigator?.canShare?.({ title, url })) {
navigator.share({ title, url });
} else {
{
navigator.clipboard.writeText(url);
}
dispatch(
addToast({
message: 'Link er kopiert til utklippstavlen',
type: 'success',
}),
);
}
};
const handleShare = async () => {
if (navigator?.canShare?.({ title, url })) {
try {
await navigator.share({ title, url });
} catch (error) {
console.error('Error sharing:', error);
await copyToClipboard();
}
} else {
await copyToClipboard();
}
};
const copyToClipboard = async () => {
try {
await navigator.clipboard.writeText(url);
dispatch(
addToast({
message: 'Link er kopiert til utklippstavlen',
type: 'success',
}),
);
} catch (error) {
console.error('Error copying to clipboard:', error);
dispatch(
addToast({
message: 'Kunne ikke kopiere link',
type: 'error',
}),
);
}
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 17-19: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

Comment on lines +14 to +15
if (navigator?.canShare?.({ title, url })) {
navigator.share({ title, url });
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

Consider browser compatibility for Web Share API.

While you're correctly checking for navigator.canShare support, some browsers might partially implement the API but have limitations. Consider adding a fallback for unsupported share data types.


🌐 Web query:

Which browsers support the Web Share API and what are their limitations?

💡 Result:

The Web Share API is supported across most modern browsers, but with varying levels of compatibility and limitations. Here's a detailed breakdown:

Browser Support

  • Chrome:

    • ✅ Full support: v89+ (desktop), all versions (Android)
    • ◐ Partial support: v89–v131 (desktop)
    • ❌ No support: v4–v88 [1][4]
  • Edge:

    • ✅ Full support: v95+
    • ◐ Partial support: v81–94
    • ❌ No support: v12–80 [1][4][10]
  • Safari:

    • ✅ Full support: v12.1+ (macOS), v12.2+ (iOS)
    • ❌ No support: older versions [1][4][7]
  • Opera:

    • ✅ Full support: v114+ (desktop), v72–80 (Mobile)
    • ❌ No support: v9.5–113 [1][4]
  • Mobile Browsers:

    • Chrome for Android: All versions
    • Firefox for Android: All versions
    • Samsung Internet: v8.2+ [1][4]
Browser Desktop Support Mobile Support
Chrome v89+ (partial/full) All versions (full)
Edge v95+ (full) Not specified
Safari v12.1+ (macOS) v12.2+ (iOS)
Firefox ✅ All (Android)
Opera v114+ (full) v72–80 (Mobile)

Key Limitations

  1. Secure Context Requirement:

    • Requires HTTPS in production. Localhost/testing environments may not work unless using tools like JSFiddle [3][7][10].
  2. Desktop Browser Gaps:

    • Poor desktop support except Chrome and Edge (partial/full). Firefox desktop lacks support entirely [3][4][7].
  3. User Interaction Dependency:

    • Must be triggered by transient activation (e.g., button click). Background/script-initiated sharing fails [8][10].
  4. Variable Share Targets:

    • Available apps depend on the OS/device. Developers can’t customize the list or track which app was used [3][7].
  5. Third-Party Iframe Restrictions:

    • Embedded iframes need explicit permissions via <iframe allow="web-share">. Otherwise, NotAllowedError occurs [5][6].
  6. File Sharing Constraints:

    • Requires validation via navigator.canShare({ files }) first. Large files or unsupported types may fail silently [7][12].

For unsupported browsers (e.g., Firefox desktop), developers must implement fallback sharing UIs. Compatibility checks with navigator.canShare() are recommended before invoking the API [7][10].

Citations:


Web Share API: Enhance Fallbacks for Partial & Unsupported Environments

In lego-webapp/components/ShareButton/index.tsx (lines 14–15), you’re correctly checking for the existence of navigator?.canShare before calling navigator.share. However, as our latest research indicates, browser support for the Web Share API is nuanced:

  • Variability Across Browsers:

    • Chrome & Edge: Generally provide full or partial support, though you might encounter differences based on the version.
    • Safari: Supports the API on modern macOS and iOS versions.
    • Firefox Desktop: Does not support the API at all, so users on Firefox will not be able to share via this mechanism.
  • Limitations & Fallback Needs:

    • Even when navigator.canShare is available, certain share data types (especially files) may not be fully supported.
    • The API requires a secure context (HTTPS) and user interaction, which might not cover all scenarios.
    • A fallback mechanism—such as a copy-to-clipboard for URLs or a custom sharing modal—can help address these discrepancies and improve the user experience in unsupported or partially supported environments.

Please consider implementing a graceful fallback for cases where the API’s capabilities are limited or absent. This will ensure a more consistent sharing experience across all browsers.

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

♻️ Duplicate comments (1)
lego-webapp/components/ShareButton/index.tsx (1)

13-27: ⚠️ Potential issue

Refactor sharing functionality with proper error handling.

The current implementation has several issues:

  1. The unnecessary block statement around the clipboard operation
  2. Lack of error handling for share and clipboard operations
  3. Not properly awaiting async operations

This was previously identified in a past review but hasn't been addressed.

const handleShare = async () => {
  if (navigator?.canShare?.({ title, url })) {
-    navigator.share({ title, url });
+    try {
+      await navigator.share({ title, url });
+    } catch (error) {
+      console.error('Error sharing:', error);
+      await copyToClipboard();
+    }
  } else {
-    {
-      navigator.clipboard.writeText(url);
-    }
-    dispatch(
-      addToast({
-        message: 'Link er kopiert til utklippstavlen',
-        type: 'success',
-      }),
-    );
+    await copyToClipboard();
+  }
+};
+
+const copyToClipboard = async () => {
+  try {
+    await navigator.clipboard.writeText(url);
+    dispatch(
+      addToast({
+        message: 'Link er kopiert til utklippstavlen',
+        type: 'success',
+      }),
+    );
+  } catch (error) {
+    console.error('Error copying to clipboard:', error);
+    dispatch(
+      addToast({
+        message: 'Kunne ikke kopiere link',
+        type: 'error',
+      }),
+    );
  }
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 17-19: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

🧹 Nitpick comments (1)
lego-webapp/components/ShareButton/index.tsx (1)

1-2: Remove unused import.

The Share2 icon is imported but never used in the component.

-import { Button, Flex, Icon } from '@webkom/lego-bricks';
-import { Share2, ShareIcon } from 'lucide-react';
+import { Button, Flex, Icon } from '@webkom/lego-bricks';
+import { ShareIcon } from 'lucide-react';
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ab80425 and ca404e5.

📒 Files selected for processing (1)
  • lego-webapp/components/ShareButton/index.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
lego-webapp/components/ShareButton/index.tsx

[error] 17-19: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
lego-webapp/components/ShareButton/index.tsx (2)

14-15: Enhance Web Share API compatibility checks.

Relying solely on navigator?.canShare may not be sufficient for all browsers. Some browsers might partially implement the API or have limitations with certain share data types.

Consider testing your implementation across different browsers, especially Firefox Desktop which doesn't support the Web Share API at all. The current implementation falls back to clipboard copy when sharing isn't supported, which is good, but it might be worth enhancing the checking mechanism.

For more reliable detection, you could combine checking for both feature existence AND ability to share the specific content:

-if (navigator?.canShare?.({ title, url })) {
+if (navigator?.share && navigator.canShare?.({ title, url })) {

This ensures both the API is available AND the specific content can be shared via the API.


29-36: LGTM: Clean component rendering.

The component rendering is clean and properly structured, using Flex for layout and appropriate spacing.

@ivarnakken
Copy link
Member

I think it should be together with the other social interactions; comments and reactions. The sidebar is already too cluttered. Imo. we don't need the text either, only the icon alone is sufficient

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new-feature Pull requests that introduce a new feature review-needed Pull requests that need review
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants