Skip to content

Instantly share code, notes, and snippets.

@ajayvignesh01
Created February 24, 2024 06:03
Show Gist options
  • Save ajayvignesh01/02b8e8f8bbec660d8644bfcea9ba3621 to your computer and use it in GitHub Desktop.
Save ajayvignesh01/02b8e8f8bbec660d8644bfcea9ba3621 to your computer and use it in GitHub Desktop.
A Tiptap extension to embed Tweets
import { NodeViewProps, NodeViewWrapper } from '@tiptap/react'
import { nodePasteRule, ReactNodeViewRenderer } from '@tiptap/react'
import { mergeAttributes, Node } from '@tiptap/core'
import { Tweet } from 'react-tweet'
export const TweetComponent = ({ node }: NodeViewProps) => {
const url = node.attrs.url
const tweetIdRegex = /\/status\/(\d+)/g
const id = tweetIdRegex.exec(url)?.[1]
return (
<NodeViewWrapper className='twitter-react-component'>
<Tweet id={id || ''} />
</NodeViewWrapper>
)
}
export const Tweet = Node.create({
name: 'twitter',
group: 'block',
atom: true,
draggable: true,
addPasteRules() {
const twitterUrl = /^https:\/\/(twitter\.com|x\.com)\/.*\/status\/.*/g
return [
nodePasteRule({
find: twitterUrl,
type: this.type,
getAttributes: (match) => {
return { url: match.input }
}
})
]
},
addAttributes() {
return {
url: {
default: 'https://twitter.com/vercel/status/1683920951807971329'
}
}
},
parseHTML() {
return [
{
tag: 'twitter'
}
]
},
renderHTML({ HTMLAttributes }) {
return ['twitter', mergeAttributes(HTMLAttributes)]
},
// TODO: WIP
// addCommands() {
// return {}
// },
addNodeView() {
return ReactNodeViewRenderer(TweetComponent)
}
})
@ajayvignesh01
Copy link
Author

Demo:

Screen.Recording.2024-02-24.at.1.02.50.AM.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment