Infine, per ora sto usando questo:
<script type="text/discourse-plugin" version="0.11.3">
api.onPageChange(() => {
if (window.location.pathname === "/") {
const container = document.querySelector(".latest-topic-list");
if (!container) return;
// Evita inizializzazioni multiple
if (window.latestRepliesInitialized) return;
window.latestRepliesInitialized = true;
// Configurazioni
const POLLING_INTERVAL = 2000; // 2 secondi
const COMMENTS_TO_SHOW = 15;
const CACHE_DURATION = 30 * 60 * 1000; // 30 minuti
// Chiavi della cache
const CACHE_KEY = "discourse_latest_replies_data";
const CACHE_TIMESTAMP_KEY = "discourse_latest_replies_timestamp";
const CACHE_LAST_ID_KEY = "discourse_latest_replies_last_id";
// Memorizza l'ultimo ID di post visto per il confronto
let lastSeenPostId = parseInt(localStorage.getItem(CACHE_LAST_ID_KEY) || "0");
let pollingIntervalId = null;
console.log(`Inizializzazione plugin ultimi commenti (ultimo ID in cache: ${lastSeenPostId})`);
// Funzione per caricare i commenti
function loadLatestReplies(silent = false, forceRefresh = false) {
// Controlla prima la cache, se non è un aggiornamento forzato
if (!forceRefresh) {
const cachedData = localStorage.getItem(CACHE_KEY);
const cacheTimestamp = localStorage.getItem(CACHE_TIMESTAMP_KEY);
const now = Date.now();
// Se abbiamo dati in cache validi
if (cachedData && cacheTimestamp && now - parseInt(cacheTimestamp) < CACHE_DURATION) {
try {
const results = JSON.parse(cachedData);
console.log(`Utilizzo dati in cache (${results.length} commenti, cache di ${Math.round((now - parseInt(cacheTimestamp)) / 1000 / 60)} minuti fa)`);
renderLatestReplies(results, false);
// Se non è silenzioso, non serve fare altro
if (!silent) {
return;
}
// Se è silenzioso, continuiamo per verificare gli aggiornamenti
} catch (e) {
console.error("Errore nell'elaborazione della cache:", e);
// Se c'è un errore nella cache, continuiamo per recuperare dati freschi
}
} else if (cachedData) {
console.log("Cache scaduta, recupero dati freschi");
} else {
console.log("Nessuna cache trovata, recupero dati freschi");
}
} else {
console.log("Forzamento aggiornamento, ignorando la cache");
}
// Se non è silenzioso, mostra l'indicatore di caricamento
if (!silent) {
// Se esiste già un contenitore dei commenti, non mostrare l'indicatore
const existingContainer = document.querySelector(".latest-replies-container");
if (!existingContainer) {
let loadingIndicator = document.getElementById("latest-replies-loading");
if (!loadingIndicator) {
loadingIndicator = document.createElement("div");
loadingIndicator.id = "latest-replies-loading";
loadingIndicator.innerHTML = `
<div style="text-align: center; padding: 20px;">
<span class="spinner small"></span>
<span style="margin-left: 10px;">Caricamento commenti recenti...</span>
</div>
`;
container.parentNode.insertBefore(loadingIndicator, container.nextSibling);
}
}
}
// Recupera i dati più recenti
fetch("/posts.json?order=created")
.then(res => res.json())
.then(data => {
// Log per diagnosi
if (!silent) {
console.log("Dati ricevuti dall'API:", data.latest_posts.length);
}
const replies = data.latest_posts
.filter(p => p.post_number > 1 && !p.topic_slug.includes("private-message"))
.slice(0, COMMENTS_TO_SHOW);
// Verifica se ci sono nuovi post
const maxId = replies.length > 0 ? Math.max(...replies.map(post => post.id)) : 0;
const hasNewPosts = maxId > lastSeenPostId;
// Log per diagnosi
if (hasNewPosts && !silent) {
console.log(`Nuovi post rilevati. Ultimo ID: ${lastSeenPostId}, Nuovo massimo ID: ${maxId}`);
}
// Aggiorna l'ultimo ID visto
if (maxId > lastSeenPostId) {
lastSeenPostId = maxId;
localStorage.setItem(CACHE_LAST_ID_KEY, lastSeenPostId.toString());
}
// Se non ci sono nuovi post e si tratta di un controllo silenzioso, non fare nulla
if (!hasNewPosts && silent && !forceRefresh) {
return;
}
// Recupera i dettagli dei topic
const topicPromises = replies.map(post => {
// Verifica se abbiamo il topic in cache
const topicCacheKey = `discourse_topic_${post.topic_id}`;
const cachedTopic = localStorage.getItem(topicCacheKey);
if (cachedTopic && !forceRefresh) {
try {
return Promise.resolve(JSON.parse(cachedTopic));
} catch (e) {
console.error(`Errore nell'elaborazione della cache del topic ${post.topic_id}:`, e);
// Se c'è un errore nella cache, recuperiamo dal server
}
}
return fetch(`/t/${post.topic_id}.json`)
.then(res => res.json())
.then(topic => {
// Memorizza il topic in cache
localStorage.setItem(topicCacheKey, JSON.stringify(topic));
return topic;
})
.catch(error => {
console.error(`Errore nel recupero del topic ${post.topic_id}:`, error);
return { category_id: null, category_name: null, tags: [] };
});
});
Promise.all(topicPromises)
.then(topics => {
const results = replies.map((post, index) => {
const topic = topics[index];
return {
post,
category: topic.category_id ? topic.category_name : null,
tags: topic.tags || []
};
});
// Memorizza i risultati in cache
localStorage.setItem(CACHE_KEY, JSON.stringify(results));
localStorage.setItem(CACHE_TIMESTAMP_KEY, Date.now().toString());
// Renderizza i risultati
renderLatestReplies(results, hasNewPosts || forceRefresh);
})
.catch(error => {
console.error("Errore nell'elaborazione dei topic:", error);
});
})
.catch(error => {
console.error("Errore nel recupero degli ultimi commenti:", error);
// Rimuovi l'indicatore di caricamento in caso di errore
if (!silent) {
const loadingElement = document.getElementById("latest-replies-loading");
if (loadingElement) loadingElement.remove();
}
});
}
// Funzione per renderizzare i risultati
function renderLatestReplies(results, animate = false) {
// Rimuovi l'indicatore di caricamento
const loadingElement = document.getElementById("latest-replies-loading");
if (loadingElement) loadingElement.remove();
// Se non ci sono risultati, non fare nulla
if (!results || results.length === 0) {
console.log("Nessun commento trovato da visualizzare");
return;
}
const rows = results.map(({ post, category, tags }) => {
const url = `/t/${post.topic_slug}/${post.topic_id}/${post.post_number}`;
const avatarUrl = post.avatar_template.replace("{size}", "45");
const excerpt = post.excerpt?.replace(/<\/?[^>]+(>|$)/g, "")?.slice(0, 120) + (post.excerpt?.length > 120 ? '...' : '') || '';
const categoryHtml = category
? `<span style="font-size: 0.85em; color: #666;">Categoria: <strong>${category}</strong></span><br>`
: '';
const tagsHtml = tags.length
? `<span style="font-size: 0.85em; color: #666;">Tag: ${tags.map(tag => `<span style="background:#eee; padding:2px 6px; border-radius:3px; margin-right:4px;">${tag}</span>`).join("")}</span>`
: '';
const animationClass = animate ? 'new-comment' : '';
return `
<tr class="topic-list-item ${animationClass}" data-post-id="${post.id}">
<td class="main-link clearfix">
<div style="display: flex; align-items: center; gap: 16px; padding: 8px 0;">
<div style="flex-shrink: 0;">
<a class="avatar-link" href="/u/${post.username}">
<img loading="lazy" width="45" height="45" src="${avatarUrl}" class="avatar" alt="${post.username}">
</a>
</div>
<div style="display: flex; flex-direction: column; justify-content: center; padding-top: 8px; padding-bottom: 8px;">
<span class="link-top-line" style="margin-bottom: 6px;">
<a href="${url}" class="title raw-link">${excerpt}</a>
</span>
<div class="link-bottom-line">
${categoryHtml}
${tagsHtml}
</div>
</div>
</div>
</td>
</tr>
`;
}).join("");
// Aggiungi lo stile di animazione se non esiste ancora
if (!document.getElementById('latest-replies-style')) {
const style = document.createElement('style');
style.id = 'latest-replies-style';
style.textContent = `
@keyframes highlightNew {
0% { background-color: rgba(255, 255, 0, 0.3); }
100% { background-color: transparent; }
}
.new-comment {
animation: highlightNew 2s ease-out;
}
`;
document.head.appendChild(style);
}
// Rimuovi il contenitore esistente, se presente
const existingContainer = document.querySelector(".latest-replies-container");
if (existingContainer) {
existingContainer.remove();
}
// Crea il contenitore della sezione ultimi commenti
const latestRepliesContainer = document.createElement("div");
latestRepliesContainer.className = "latest-replies-container";
latestRepliesContainer.style.marginTop = "2em";
// Aggiungi pulsante di aggiornamento manuale e indicatore di stato
const cacheTime = new Date(parseInt(localStorage.getItem(CACHE_TIMESTAMP_KEY) || Date.now()));
const formattedTime = cacheTime.toLocaleTimeString();
latestRepliesContainer.innerHTML = `
<table class="topic-list latest-topic-list">
<thead>
<tr>
<th class="default">
Ultimi Commenti
<span id="comments-status" style="font-size: 0.8em; font-weight: normal; margin-left: 10px;">
</span>
<button id="refresh-comments" class="btn btn-flat no-text btn-icon" style="float: right;" title="Aggiorna commenti">
<svg class="fa d-icon d-icon-sync svg-icon svg-string" width="16" height="16" aria-hidden="true"><use xlink:href="#sync"></use></svg>
</button>
</th>
</tr>
</thead>
<tbody id="latest-replies-tbody">
${rows}
</tbody>
</table>
`;
container.parentNode.insertBefore(latestRepliesContainer, container.nextSibling);
container.dataset.modified = "true";
// Aggiungi evento click al pulsante di aggiornamento
document.getElementById("refresh-comments").addEventListener("click", function() {
// Aggiorna il testo di stato
const statusElement = document.getElementById("comments-status");
if (statusElement) {
statusElement.textContent = "(aggiornamento...)";
}
// Forza l'aggiornamento
loadLatestReplies(false, true);
});
console.log(`Renderizzati ${results.length} commenti`);
}
// Avvia il caricamento iniziale (usando la cache)
loadLatestReplies(false, false);
// Configura il polling ad alta frequenza
pollingIntervalId = setInterval(() => {
// Aggiorna solo se l'utente è sulla pagina iniziale
if (window.location.pathname === "/") {
loadLatestReplies(true, false); // Silenzioso, usa la cache se disponibile
}
}, POLLING_INTERVAL);
console.log(`Polling configurato ogni ${POLLING_INTERVAL}ms`);
// Pulisci l'intervallo quando l'utente lascia la pagina
api.onPageChange((url) => {
if (url !== "/") {
console.log("Uscita dalla pagina iniziale, pulizia risorse");
if (pollingIntervalId) {
clearInterval(pollingIntervalId);
pollingIntervalId = null;
}
window.latestRepliesInitialized = false;
}
});
}
});
</script>
Funziona come previsto. Aggiunge automaticamente i nuovi commenti e poi li salva nella cache. So che non è l’ideale. Presto proverò a creare un plugin.
L’obiettivo qui è: invece di una categoria con lo stile della pagina “ultimi topic”, mi piacerebbe avere una categoria con gli “ultimi commenti”.