refactor(utils): add getHostname, memoize getCommentMediaInfo

This commit is contained in:
plebeius.eth
2023-10-18 11:33:40 +02:00
parent fd92f54158
commit 7fcbe3fbb6
3 changed files with 16 additions and 12 deletions

View File

@@ -19,7 +19,7 @@ const FeedPost: FC<FeedPostProps> = ({ post, index }) => {
const { t } = useTranslation();
const [expandoVisible, setExpandoVisible] = useState(false);
const subplebbit = useSubplebbit({ subplebbitAddress });
const commentMediaInfo = utils.getCommentMediaInfo(post);
const commentMediaInfo = utils.getCommentMediaInfoMemo(post);
const iframeThumbnail = commentMediaInfo?.patternThumbnailUrl || commentMediaInfo?.thumbnail;
const hasThumbnail =
link &&
@@ -66,13 +66,7 @@ const FeedPost: FC<FeedPostProps> = ({ post, index }) => {
<span className={styles.domain}>
(
<a href={link} target='_blank' rel='noreferrer'>
{(() => {
try {
return new URL(link).hostname.replace(/^www\./, '');
} catch (e) {
return 'Invalid URL';
}
})()}
{utils.getHostname(link)}
</a>
)
</span>

View File

@@ -12,7 +12,7 @@ const Thumbnail: FC<ThumbnailProps> = ({ commentCid }) => {
const comment = useComment({ commentCid });
const subplebbitAddress = comment.subplebbitAddress;
const { cid, linkHeight, linkWidth } = comment;
const commentMediaInfo = utils.getCommentMediaInfo(comment);
const commentMediaInfo = utils.getCommentMediaInfoMemo(comment);
const iframeThumbnail = commentMediaInfo?.patternThumbnailUrl || commentMediaInfo?.thumbnail;
let displayWidth, displayHeight, hasLinkDimensions;

View File

@@ -58,9 +58,9 @@ const getCommentMediaInfo = (comment: Comment) => {
}
};
export const getCommentLinkMediaType = memoize(getCommentMediaInfo, { max: 1000 });
const getCommentMediaInfoMemo = memoize(getCommentMediaInfo, { max: 1000 });
export const getFormattedTime = (unixTimestamp: number): string => {
const getFormattedTime = (unixTimestamp: number): string => {
const currentTime = Date.now() / 1000;
const timeDifference = currentTime - unixTimestamp;
const t = i18next.t;
@@ -95,9 +95,19 @@ export const getFormattedTime = (unixTimestamp: number): string => {
return t('time_x_years_ago', { count: Math.floor(timeDifference / 31104000) });
};
const getHostname = (url: string) => {
try {
return new URL(url).hostname.replace(/^www\./, '')
} catch (e) {
console.log(e);
return '';
}
}
const utils = {
getCommentMediaInfoMemo,
getFormattedTime,
getCommentMediaInfo,
getHostname,
};
export default utils;