import { Editor } from '@tiptap/react' import { DOMAIN } from 'common/envs/constants' import { useState } from 'react' import { Button } from '../button' import { RichContent } from '../editor' import { Col } from '../layout/col' import { Modal } from '../layout/modal' import { Row } from '../layout/row' import { Spacer } from '../layout/spacer' type EmbedPattern = { // Regex should have a single capture group. regex: RegExp rewrite: (text: string) => string } const embedPatterns: EmbedPattern[] = [ { regex: /^()$/, rewrite: (text: string) => text, }, { regex: /^https?:\/\/manifold\.markets\/([^\/]+\/[^\/]+)/, rewrite: (slug) => ``, }, { regex: /^https?:\/\/twitter\.com\/.*\/status\/(\d+)/, // Hack: append a leading 't', to prevent tweetId from being interpreted as a number. // If it's a number, there may be numeric precision issues. rewrite: (id) => ``, }, { regex: /^https?:\/\/www\.youtube\.com\/watch\?v=([^&]+)/, rewrite: (id) => ``, }, { regex: /^https?:\/\/www\.metaculus\.com\/questions\/(\d+)/, rewrite: (id) => ``, }, { regex: /^(https?:\/\/www\.figma\.com\/(?:file|proto)\/[^\/]+\/[^\/]+)/, rewrite: (url) => ``, }, // Twitch is a bit annoying, since it requires the `&parent=DOMAIN` to match { // Twitch: https://www.twitch.tv/videos/1445087149 regex: /^https?:\/\/www\.twitch\.tv\/videos\/(\d+)/, rewrite: (id) => ``, }, { // Twitch: https://www.twitch.tv/sirsalty regex: /^https?:\/\/www\.twitch\.tv\/([^\/]+)/, rewrite: (channel) => ``, }, { regex: /^(https?:\/\/.*)/, rewrite: (url) => ``, }, ] function embedCode(text: string) { for (const pattern of embedPatterns) { const match = text.match(pattern.regex) if (match) { return pattern.rewrite(match[1]) } } return null } export function EmbedModal(props: { editor: Editor | null open: boolean setOpen: (open: boolean) => void }) { const { editor, open, setOpen } = props const [input, setInput] = useState('') const embed = embedCode(input) return ( setInput(e.target.value)} /> {/* Preview the embed if it's valid */} {embed ? : } ) }