Skip to content

Commit

Permalink
Render video if it's valid Youtube URL
Browse files Browse the repository at this point in the history
  • Loading branch information
GxqoRR committed Oct 18, 2023
1 parent e12e248 commit 8f7a0e4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
25 changes: 24 additions & 1 deletion components/text.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import styles from './text.module.css'
import ReactMarkdown from 'react-markdown'
import YouTube from 'react-youtube'
import gfm from 'remark-gfm'
import { LightAsync as SyntaxHighlighter } from 'react-syntax-highlighter'
import atomDark from 'react-syntax-highlighter/dist/cjs/styles/prism/atom-dark'
Expand Down Expand Up @@ -105,6 +106,21 @@ export default memo(function Text ({ nofollow, imgproxyUrls, children, tab, ...o
return <ZoomableImage srcSet={srcSet} tab={tab} src={src} {...props} {...outerProps} />
}, [imgproxyUrls, outerProps, tab])

const renderYoutubeUrl = useCallback((url) => {
if (url) {
const regExp = /^https?:\/\/(www\.)?(youtube\.com|youtu\.be)\/(watch\?v=|embed\/)?([^&#\?]+)/;
const match = url.match(regExp);
if (match && match[4]) {
return <YouTube videoId={match[4]} className={styles.videoContainer} opts={{
height: '100%',
width: '100%',
}} />;
}
}

return null;
}, []);

return (
<div className={styles.text}>
<ReactMarkdown
Expand All @@ -129,7 +145,14 @@ export default memo(function Text ({ nofollow, imgproxyUrls, children, tab, ...o
// we don't render it as an image since it was probably a concious choice to include text.
const text = children[0]
if (!!text && !/^https?:\/\//.test(text)) {
return <a target='_blank' rel={`noreferrer ${nofollow ? 'nofollow' : ''} noopener`} href={href}>{text}</a>
// Render video if it's a valid Youtube url, otherwise null
const video = renderYoutubeUrl(href);
return (
<>
<a target='_blank' rel={`noreferrer ${nofollow ? 'nofollow' : ''} noopener`} href={href}>{text}</a>
{video}
</>
);
}

// assume the link is an image which will fallback to link if it's not
Expand Down
7 changes: 7 additions & 0 deletions components/text.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,11 @@ img.fullScreen {

.text h6 {
font-size: .85rem;
}

.videoContainer {
aspect-ratio: 16/9;
margin-bottom: .5rem;
margin-top: .5rem;
max-width: 640px;
}

0 comments on commit 8f7a0e4

Please sign in to comment.