Add support for Twitter and Telegram

This commit is contained in:
Lachlan Kermode
2022-03-06 19:34:12 -05:00
parent b9eac1ce9a
commit 4113c04830
8 changed files with 142 additions and 13 deletions

View File

@@ -1,6 +1,8 @@
import React, { useRef } from "react";
import { useCallback } from "react";
import { typeForPath } from "../../../common/utilities";
import { TwitterTweetEmbed } from "react-twitter-embed";
import TelegramPostEmbed from "./TelegramEmbed";
const TITLE_LENGTH = 50;
// TODO should videos
@@ -53,6 +55,25 @@ const Media = ({ src, title }) => {
</div>
</div>
);
case "Telegram":
return (
<div className="card-cell media embedded">
<TelegramPostEmbed src={src} />
</div>
);
case "Tweet":
const tweetIdRegex =
/https?:\/\/twitter.com\/[0-9a-zA-Z_]{1,20}\/status\/([0-9]*)/;
const match = tweetIdRegex.exec(src);
const tweetId = match[1];
return (
<div className="card-cell media embedded">
<TwitterTweetEmbed tweetId={tweetId} />
</div>
);
default:
return null;
}

View File

@@ -0,0 +1,105 @@
/*
* Adapted from https://github.com/cudr/react-telegram-embed
*/
import React, { Component } from "react";
const styles = {
width: "100%",
frameBorder: "0",
scrolling: "no",
border: "none",
overflow: "hidden",
};
const containerStyles = {
marginLeft: -60,
};
/**
* Simple Component for Telegram embedding
* @extends Component
*/
class TelegramEmbed extends Component {
constructor(props) {
super(props);
this.state = {
src: this.props.src,
id: "",
height: "80px",
};
this.messageHandler = this.messageHandler.bind(this);
this.urlObj = document.createElement("a");
}
componentDidMount() {
window.addEventListener("message", this.messageHandler);
this.iFrame.addEventListener("load", () => {
this.checkFrame(this.state.id);
});
}
componentWillUnmount() {
window.removeEventListener("message", this.messageHandler);
}
messageHandler({ data, source }) {
if (
!data ||
typeof data !== "string" ||
source !== this.iFrame.contentWindow
) {
return;
}
const action = JSON.parse(data);
if (action.event === "resize" && action.height) {
this.setState({
height: action.height + "px",
});
}
}
checkFrame(id) {
this.iFrame.contentWindow.postMessage(
JSON.stringify({ event: "visible", frame: id }),
"*"
);
}
componentWillReceiveProps({ src }) {
if (this.state.src !== src) {
this.urlObj.href = src;
const id = `telegram-post${this.urlObj.pathname.replace(
/[^a-z0-9_]/gi,
"-"
)}`;
this.setState({ src, id }, () => this.checkFrame(id));
}
}
render() {
const { src, height } = this.state;
const { container } = this.props;
return (
<div data-sharing-id={container} style={containerStyles}>
<iframe
ref={(node) => (this.iFrame = node)}
src={src + "?embed=1"}
height={height}
id={
"telegram-post" + this.urlObj.pathname.replace(/[^a-z0-9_]/gi, "-")
}
style={styles}
/>
</div>
);
}
}
export default TelegramEmbed;