Last active
February 26, 2020 15:43
-
-
Save vincentritter/2723d9133b5613e94f24feec9bed4bc2 to your computer and use it in GitHub Desktop.
Conversation.js integration using Preact and Fetch API - as used on my site.
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 { render, h, Component } from 'preact' | |
import dayjs from 'dayjs' | |
import relativeTime from 'dayjs/plugin/relativeTime' | |
import LazyLoad from "vanilla-lazyload"; | |
var lazyLoader = new LazyLoad({elements_selector: ".lazy-convo"}); | |
dayjs.extend(relativeTime) | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
items: [], | |
url: this.props.url | |
} | |
} | |
componentDidMount = () => { | |
this._fetch_items() | |
} | |
_fetch_items = async () => { | |
fetch(`https://micro.blog/conversation.js?url=${this.state.url}&format=jsonfeed`).then((response) => { | |
if (response.status === 200) { | |
response.json().then((result) => { | |
if (result.items !== null && result.items.length > 0) { | |
this.setState({ items: result.items }) | |
setTimeout(() => { | |
lazyLoader.update() | |
}, 150) | |
} | |
}) | |
} | |
}) | |
} | |
_render_items = () => { | |
const items = this.state.items.map(item => { | |
const date = dayjs().to(dayjs(item.date_published)) | |
return ( | |
<div class="convo_item"> | |
<a class="convo_profile" href={item.author.url} target="_blank"> | |
<img | |
src="data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20%20%27%2F%3E" | |
class="lazy-convo" | |
width="50" | |
height="50" | |
data-src={item.author.avatar} | |
/> | |
<p>{item.author.name}</p> | |
</a> | |
<div class="convo_content" dangerouslySetInnerHTML={{ __html: item.content_html }}></div> | |
<a class="convo_meta" href={item.url} target="_blank">{date}</a> | |
</div> | |
) | |
}) | |
return items | |
} | |
render() { | |
if (this.state.items.length > 0) { | |
return ( | |
<div class="convo"> | |
<h4>Conversation:</h4> | |
{this._render_items()} | |
</div> | |
) | |
} | |
} | |
} | |
const convo_div = document.querySelector('#convo') | |
if (convo_div !== null) { | |
const url = convo_div.getAttribute('url') | |
if (url !== null) { | |
render(<App url={url} />, convo_div); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment