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

Show social media handle #4843

Merged
merged 2 commits into from
Oct 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion next-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.
35 changes: 7 additions & 28 deletions src/components/views/project/ProjectSocialItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { B, Flex, neutralColors } from '@giveth/ui-design-system';
import { IProjectSocialMedia } from '@/apollo/types/types';
import { Shadow } from '@/components/styled-components/Shadow';
import { socialMediasArray } from '../create/SocialMediaBox/SocialMedias';
import { ensureHttps, getSocialMediaHandle } from '@/helpers/url';

interface IProjectSocialMediaItem {
socialMedia: IProjectSocialMedia;
Expand All @@ -22,32 +23,6 @@ const socialMediaColor: { [key: string]: string } = {
github: '#1D1E1F',
};

const removeHttpsAndWwwFromUrl = (socialMediaUrl: string) => {
return socialMediaUrl.replace('https://', '').replace('www.', '');
};

/**
* Ensures that a given URL uses the https:// protocol.
* If the URL starts with http://, it will be replaced with https://.
* If the URL does not start with any protocol, https:// will be added.
* If the URL already starts with https://, it will remain unchanged.
*
* @param {string} url - The URL to be checked and possibly modified.
* @returns {string} - The modified URL with https://.
*/
function ensureHttps(url: string): string {
if (!url.startsWith('https://')) {
if (url.startsWith('http://')) {
// Replace http:// with https://
url = url.replace('http://', 'https://');
} else {
// Add https:// if no protocol is present
url = 'https://' + url;
}
}
return url;
}

const ProjectSocialItem = ({ socialMedia }: IProjectSocialMediaItem) => {
const item = socialMediasArray.find(item => {
return item.type.toLocaleLowerCase() === socialMedia.type.toLowerCase();
Expand All @@ -63,7 +38,7 @@ const ProjectSocialItem = ({ socialMedia }: IProjectSocialMediaItem) => {
<IconComponent
color={
socialMediaColor[
item.name.toLocaleLowerCase() || 'website'
item?.name.toLocaleLowerCase() || 'website'
]
}
/>
Expand All @@ -76,7 +51,11 @@ const ProjectSocialItem = ({ socialMedia }: IProjectSocialMediaItem) => {
],
}}
>
{removeHttpsAndWwwFromUrl(socialMedia.link)}
{/* Use the updated function to show a cleaner link or username */}
{getSocialMediaHandle(
socialMedia.link,
socialMedia.type,
)}
</B>
</Flex>
</SocialItemContainer>
Expand Down
108 changes: 108 additions & 0 deletions src/helpers/url.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,111 @@ export function removeQueryParamAndRedirect(
export const convertIPFSToHTTPS = (url: string) => {
return url.replace('ipfs://', 'https://ipfs.io/ipfs/');
};

export const getSocialMediaHandle = (
socialMediaUrl: string,
socialMediaType: string,
) => {
let cleanedUrl = socialMediaUrl
.replace(/^https?:\/\//, '')
.replace('www.', '');

// Remove trailing slash if present
if (cleanedUrl.endsWith('/')) {
cleanedUrl = cleanedUrl.slice(0, -1);
}

// Match against different social media types using custom regex
const lowerCaseType = socialMediaType.toLowerCase();

switch (lowerCaseType) {
case 'github':
return extractUsernameFromPattern(
cleanedUrl,
/github\.com\/([^\/]+)/,
);
case 'x': // Former Twitter
return extractUsernameFromPattern(cleanedUrl, /x\.com\/([^\/]+)/);
case 'facebook':
return extractUsernameFromPattern(
cleanedUrl,
/facebook\.com\/([^\/]+)/,
);
case 'instagram':
return extractUsernameFromPattern(
cleanedUrl,
/instagram\.com\/([^\/]+)/,
);
case 'linkedin':
return extractUsernameFromPattern(
cleanedUrl,
/linkedin\.com\/(?:in|company)\/([^\/]+)/,
);
case 'youtube':
return extractUsernameFromPattern(
cleanedUrl,
/youtube\.com\/channel\/([^\/]+)/,
);
case 'reddit':
return extractUsernameFromPattern(
cleanedUrl,
/reddit\.com\/r\/([^\/]+)/,
);
case 'telegram':
return extractUsernameFromPattern(cleanedUrl, /t\.me\/([^\/]+)/);
case 'discord':
return extractUsernameFromPattern(
cleanedUrl,
/discord\.gg\/([^\/]+)/,
);
case 'farcaster':
// Assuming Farcaster uses a pattern like 'farcaster.xyz/username'
return extractUsernameFromPattern(
cleanedUrl,
/farcaster\.xyz\/([^\/]+)/,
);
case 'lens':
// Assuming Lens uses a pattern like 'lens.xyz/username'
return extractUsernameFromPattern(
cleanedUrl,
/lens\.xyz\/([^\/]+)/,
);
case 'website':
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

Remove unnecessary 'website' case in switch statement.

The 'website' case in the switch statement is redundant because the default case already handles any cases not matched. Removing it simplifies the code without affecting functionality.

Apply this diff to remove the unnecessary case:

     case 'lens':
       // Assuming Lens uses a pattern like 'lens.xyz/username'
       return extractUsernameFromPattern(
         cleanedUrl,
         /lens\.xyz\/([^\/]+)/,
       );
-    case 'website':
     default:
       return cleanedUrl; // Return cleaned URL for generic websites or unsupported social media
   }
📝 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
case 'website':
case 'lens':
// Assuming Lens uses a pattern like 'lens.xyz/username'
return extractUsernameFromPattern(
cleanedUrl,
/lens\.xyz\/([^\/]+)/,
);
default:
return cleanedUrl; // Return cleaned URL for generic websites or unsupported social media
}
🧰 Tools
🪛 Biome

[error] 212-212: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

default:
return cleanedUrl; // Return cleaned URL for generic websites or unsupported social media
}
Comment on lines +160 to +215
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

Refactor switch statement to use a mapping for better maintainability.

By using an object to map social media types to their corresponding regex patterns, you can simplify the code, reduce duplication, and make it easier to maintain and extend in the future.

Apply this diff to refactor the switch statement:

+  const socialMediaPatterns: { [key: string]: RegExp } = {
+    github: /github\.com\/([^\/]+)/,
+    x: /x\.com\/([^\/]+)/, // Former Twitter
+    facebook: /facebook\.com\/([^\/]+)/,
+    instagram: /instagram\.com\/([^\/]+)/,
+    linkedin: /linkedin\.com\/(?:in|company)\/([^\/]+)/,
+    youtube: /youtube\.com\/channel\/([^\/]+)/,
+    reddit: /reddit\.com\/r\/([^\/]+)/,
+    telegram: /t\.me\/([^\/]+)/,
+    discord: /discord\.gg\/([^\/]+)/,
+    farcaster: /farcaster\.xyz\/([^\/]+)/,
+    lens: /lens\.xyz\/([^\/]+)/,
+    // Add more mappings as needed
+  };
+
+  const pattern = socialMediaPatterns[lowerCaseType];
+
+  if (pattern) {
+    return extractUsernameFromPattern(cleanedUrl, pattern);
+  } else {
+    return cleanedUrl; // Return cleaned URL for generic websites or unsupported social media
+  }
-
-  switch (lowerCaseType) {
-    case 'github':
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /github\.com\/([^\/]+)/,
-      );
-    case 'x': // Former Twitter
-      return extractUsernameFromPattern(cleanedUrl, /x\.com\/([^\/]+)/);
-    case 'facebook':
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /facebook\.com\/([^\/]+)/,
-      );
-    case 'instagram':
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /instagram\.com\/([^\/]+)/,
-      );
-    case 'linkedin':
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /linkedin\.com\/(?:in|company)\/([^\/]+)/,
-      );
-    case 'youtube':
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /youtube\.com\/channel\/([^\/]+)/,
-      );
-    case 'reddit':
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /reddit\.com\/r\/([^\/]+)/,
-      );
-    case 'telegram':
-      return extractUsernameFromPattern(cleanedUrl, /t\.me\/([^\/]+)/);
-    case 'discord':
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /discord\.gg\/([^\/]+)/,
-      );
-    case 'farcaster':
-      // Assuming Farcaster uses a pattern like 'farcaster.xyz/username'
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /farcaster\.xyz\/([^\/]+)/,
-      );
-    case 'lens':
-      // Assuming Lens uses a pattern like 'lens.xyz/username'
-      return extractUsernameFromPattern(
-        cleanedUrl,
-        /lens\.xyz\/([^\/]+)/,
-      );
-    default:
-      return cleanedUrl; // Return cleaned URL for generic websites or unsupported social media
-  }
📝 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
switch (lowerCaseType) {
case 'github':
return extractUsernameFromPattern(
cleanedUrl,
/github\.com\/([^\/]+)/,
);
case 'x': // Former Twitter
return extractUsernameFromPattern(cleanedUrl, /x\.com\/([^\/]+)/);
case 'facebook':
return extractUsernameFromPattern(
cleanedUrl,
/facebook\.com\/([^\/]+)/,
);
case 'instagram':
return extractUsernameFromPattern(
cleanedUrl,
/instagram\.com\/([^\/]+)/,
);
case 'linkedin':
return extractUsernameFromPattern(
cleanedUrl,
/linkedin\.com\/(?:in|company)\/([^\/]+)/,
);
case 'youtube':
return extractUsernameFromPattern(
cleanedUrl,
/youtube\.com\/channel\/([^\/]+)/,
);
case 'reddit':
return extractUsernameFromPattern(
cleanedUrl,
/reddit\.com\/r\/([^\/]+)/,
);
case 'telegram':
return extractUsernameFromPattern(cleanedUrl, /t\.me\/([^\/]+)/);
case 'discord':
return extractUsernameFromPattern(
cleanedUrl,
/discord\.gg\/([^\/]+)/,
);
case 'farcaster':
// Assuming Farcaster uses a pattern like 'farcaster.xyz/username'
return extractUsernameFromPattern(
cleanedUrl,
/farcaster\.xyz\/([^\/]+)/,
);
case 'lens':
// Assuming Lens uses a pattern like 'lens.xyz/username'
return extractUsernameFromPattern(
cleanedUrl,
/lens\.xyz\/([^\/]+)/,
);
case 'website':
default:
return cleanedUrl; // Return cleaned URL for generic websites or unsupported social media
}
const socialMediaPatterns: { [key: string]: RegExp } = {
github: /github\.com\/([^\/]+)/,
x: /x\.com\/([^\/]+)/, // Former Twitter
facebook: /facebook\.com\/([^\/]+)/,
instagram: /instagram\.com\/([^\/]+)/,
linkedin: /linkedin\.com\/(?:in|company)\/([^\/]+)/,
youtube: /youtube\.com\/channel\/([^\/]+)/,
reddit: /reddit\.com\/r\/([^\/]+)/,
telegram: /t\.me\/([^\/]+)/,
discord: /discord\.gg\/([^\/]+)/,
farcaster: /farcaster\.xyz\/([^\/]+)/,
lens: /lens\.xyz\/([^\/]+)/,
// Add more mappings as needed
};
const pattern = socialMediaPatterns[lowerCaseType];
if (pattern) {
return extractUsernameFromPattern(cleanedUrl, pattern);
} else {
return cleanedUrl; // Return cleaned URL for generic websites or unsupported social media
}
🧰 Tools
🪛 Biome

[error] 212-212: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

};

// Function to extract username from URL based on the regex pattern
export const extractUsernameFromPattern = (
url: string,
regex: RegExp,
): string => {
const match = url.match(regex);
if (match && match[1]) {
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

Simplify condition using optional chaining.

You can simplify the condition if (match && match[1]) by using optional chaining, making the code cleaner and more concise.

Apply this diff to use optional chaining:

 export const extractUsernameFromPattern = (
   url: string,
   regex: RegExp,
 ): string => {
   const match = url.match(regex);
-  if (match && match[1]) {
+  if (match?.[1]) {
     return `@${match[1]}`; // Return '@username'
   }
   return url; // Fallback to original URL if no match is found
 };
📝 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
if (match && match[1]) {
export const extractUsernameFromPattern = (
url: string,
regex: RegExp,
): string => {
const match = url.match(regex);
if (match?.[1]) {
return `@${match[1]}`; // Return '@username'
}
return url; // Fallback to original URL if no match is found
};
🧰 Tools
🪛 Biome

[error] 224-224: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

return `@${match[1]}`; // Return '@username'
}
return url; // Fallback to original URL if no match is found
};

/**
* Ensures that a given URL uses the https:// protocol.
* If the URL starts with http://, it will be replaced with https://.
* If the URL does not start with any protocol, https:// will be added.
* If the URL already starts with https://, it will remain unchanged.
*
* @param {string} url - The URL to be checked and possibly modified.
* @returns {string} - The modified URL with https://.
*/
export function ensureHttps(url: string): string {
if (!url.startsWith('https://')) {
if (url.startsWith('http://')) {
// Replace http:// with https://
url = url.replace('http://', 'https://');
} else {
// Add https:// if no protocol is present
url = 'https://' + url;
}
}
return url;
}
Loading