Created
February 24, 2024 06:03
-
-
Save ajayvignesh01/02b8e8f8bbec660d8644bfcea9ba3621 to your computer and use it in GitHub Desktop.
A Tiptap extension to embed Tweets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo:
Screen.Recording.2024-02-24.at.1.02.50.AM.mov