tiltlr-blog
Version:
A lightweight JavaScript library to embed Medium blog posts on any website
85 lines (70 loc) • 2.38 kB
JavaScript
class TiltlrBlog extends HTMLElement {
constructor() {
super();
this.posts = [];
this.limit = 5; // Default limit
}
connectedCallback() {
const username = this.getAttribute('username');
if (!username) {
this.innerHTML = '<p>Error: Please provide a Medium username</p>';
return;
}
// Get the limit attribute if provided
const limitAttr = this.getAttribute('limit');
if (limitAttr && !isNaN(parseInt(limitAttr))) {
this.limit = parseInt(limitAttr);
}
this.fetchPosts(username);
}
async fetchPosts(username) {
try {
const rssUrl = `https://medium.com/feed/@${username}`;
const apiUrl = `https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(rssUrl)}`;
const response = await fetch(apiUrl);
const data = await response.json();
if (data.status !== 'ok') {
throw new Error('Failed to fetch posts');
}
this.posts = data.items.slice(0, this.limit);
this.render();
} catch (error) {
this.innerHTML = `<p>Error fetching posts: ${error.message}</p>`;
}
}
formatDate(dateString) {
const options = { year: 'numeric', month: 'long', day: 'numeric' };
return new Date(dateString).toLocaleDateString(undefined, options);
}
render() {
const container = document.createElement('div');
container.className = 'tiltlr-container';
this.posts.forEach(post => {
// Extract thumbnail
let thumbnail = '';
const imgRegex = /<img[^>]+src="([^">]+)"/g;
const match = imgRegex.exec(post.content);
if (match && match[1]) {
thumbnail = match[1];
}
const card = document.createElement('div');
card.className = 'tiltlr-card';
card.innerHTML = `
<a href="${post.link}" target="_blank" rel="noopener">
<div class="tiltlr-card-image">
${thumbnail ? `<img src="${thumbnail}" alt="${post.title}">` : ''}
</div>
<div class="tiltlr-card-content">
<h2>${post.title}</h2>
<p class="tiltlr-card-date">${this.formatDate(post.pubDate)}</p>
</div>
</a>
`;
container.appendChild(card);
});
this.innerHTML = '';
this.appendChild(container);
}
}
// Define the custom element
customElements.define('tiltlr-blog', TiltlrBlog);