Make the banner and sidebar counts live on every page

One 5-minute poll (/new-since/) now drives the new-articles banner, the
tab dot and the sidebar counts, across all subscriptions rather than the
selected feed/tag. The banner lives in the base layout with a
server-rendered baseline id and reloads the current view on click; new
articles are never inserted automatically.

Sidebar counts are patched in place by the poll, and immediately after
reading or starring (HX-Trigger: countsChanged). Ingestion, filter rules
and subscription changes now drop the cached counts instead of waiting
out the TTL.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5.5 committed 2026-11-03 07:39:36 -07:00
1 parent fed5bcc49e
commit 2a3e9f632e
18 files changed
+398 -195

No files matched your search

+4
View File
@@ -6,6 +6,7 @@ from celery import shared_task
from django.db import transaction
from django.utils import timezone
from apps.core.cache_utils import invalidate_feed_subscribers_sidebar_cache
from apps.core.models import SiteSettings
from apps.feeds.models import Subscription
from apps.rules.engine import evaluate_rules_for_article
@@ -65,6 +66,9 @@ def apply_filter_rules_for_feed(feed_id: int, article_ids: list[int]):
evaluate_rules_for_article(subscription.user, article, rules, subscription_tag_ids)
evaluated += 1
if evaluated:
# Rules can mark articles read or hide them, which changes counts.
invalidate_feed_subscribers_sidebar_cache(feed_id)
return evaluated
+14
View File
@@ -16,6 +16,20 @@ def sidebar_unread_cache_key(user_id: int) -> str:
return f"sidebar-unread:{user_id}"
def invalidate_feed_subscribers_sidebar_cache(feed_id: int) -> None:
"""Drop the cached unread counts of everyone subscribed to a feed —
called when ingestion adds articles or filter rules change their
read/hidden state, so the sidebar's next refresh shows them at once
instead of after the TTL."""
from apps.feeds.models import Subscription
user_ids = Subscription.objects.filter(feed_id=feed_id).values_list("user_id", flat=True)
try:
cache.delete_many([sidebar_unread_cache_key(user_id) for user_id in user_ids])
except Exception:
logger.warning("Sidebar cache unavailable; nothing to invalidate")
def invalidate_sidebar_unread_cache(user_id: int) -> None:
"""Call this wherever a request changes the current user's own
read/unread state (toggle_read, mark_all_read, viewing an article) so
+33 -4
View File
@@ -1,8 +1,34 @@
from apps.articles.models import STARRED_TAG_NAME, ArticleTag, SubscriptionTag, Tag
from django.db.models import Max
from apps.articles.models import STARRED_TAG_NAME, Article, ArticleTag, SubscriptionTag, Tag
from apps.articles.queries import unread_counts_by_feed
from apps.feeds.models import Subscription
def starred_count(user):
return ArticleTag.objects.filter(
user=user, tag__user=user, tag__name=STARRED_TAG_NAME, tag__is_system=True
).count()
def sidebar_counts(user):
"""The sidebar's numbers on their own, for the live-update poll
(static/js/live-updates.js) to patch into the rendered sidebar:
unread per feed, unread per tag (summed over the feeds it covers,
as in sidebar() below), and the starred total."""
unread_counts = unread_counts_by_feed(user)
tag_totals = {}
for tag_id, feed_id in SubscriptionTag.objects.filter(
user=user, tag__is_system=False
).values_list("tag_id", "subscription__feed_id"):
tag_totals[str(tag_id)] = tag_totals.get(str(tag_id), 0) + unread_counts.get(feed_id, 0)
return {
"feeds": {str(feed_id): count for feed_id, count in unread_counts.items()},
"tags": tag_totals,
"starred": starred_count(user),
}
def sidebar(request):
"""Tag/feed tree and starred count for the persistent sidebar rendered
by base.html on every authenticated page. Kept out of individual views
@@ -59,7 +85,10 @@ def sidebar(request):
for tag in tags
],
"sidebar_untagged": untagged,
"sidebar_starred_count": ArticleTag.objects.filter(
user=user, tag__user=user, tag__name=STARRED_TAG_NAME, tag__is_system=True
).count(),
"sidebar_starred_count": starred_count(user),
# The page's "newest article seen" baseline for the new-articles
# banner / tab dot; rendered into the page, not fetched, so there's
# no gap between rendering and the first poll (and a page served
# from the PWA cache still compares against what it actually shows).
"latest_article_id": Article.objects.aggregate(Max("id"))["id__max"] or 0,
}
+3
View File
@@ -4,3 +4,6 @@ from django.apps import AppConfig
class FeedsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.feeds"
def ready(self):
from . import signals # noqa: F401
+14
View File
@@ -0,0 +1,14 @@
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from apps.core.cache_utils import invalidate_sidebar_unread_cache
from .models import Subscription
@receiver([post_save, post_delete], sender=Subscription)
def drop_sidebar_counts_when_subscriptions_change(sender, instance, **kwargs):
"""The cached per-feed unread counts only cover feeds the user was
subscribed to when they were computed, so a new subscription would
show no count until the cache expired."""
invalidate_sidebar_unread_cache(instance.user_id)
+2
View File
@@ -10,6 +10,7 @@ from django.db.models import Q
from django.utils import timezone
from apps.articles.tasks import apply_filter_rules_for_feed
from apps.core.cache_utils import invalidate_feed_subscribers_sidebar_cache
from apps.core.models import SiteSettings
from .models import Feed
@@ -187,6 +188,7 @@ def fetch_feed(self, feed_id: int):
changed_article_ids = result.new_article_ids + result.updated_article_ids
if changed_article_ids:
invalidate_feed_subscribers_sidebar_cache(feed_id)
logger.info(
"Feed %s: %d new article(s), %d updated",
feed.feed_url,
+19
View File
@@ -121,6 +121,25 @@ def test_fetch_feed_task_ingests_and_saves_feed_state():
assert Article.objects.filter(feed=feed, guid="guid-1").exists()
@pytest.mark.django_db
@responses.activate
def test_fetch_feed_drops_subscribers_cached_sidebar_counts(django_user_model):
"""New articles must show in the sidebar at the next refresh, not after
the counts cache's TTL."""
from apps.articles.queries import unread_counts_by_feed
from apps.feeds.models import Subscription
user = django_user_model.objects.create_user("reader", password="pw-reader-123")
feed = Feed.objects.create(feed_url="https://example.com/feed.xml")
Subscription.objects.create(user=user, feed=feed)
assert unread_counts_by_feed(user) == {} # now cached
responses.add(responses.GET, feed.feed_url, body=GOOD_FEED_XML, status=200)
fetch_feed(feed.id)
assert unread_counts_by_feed(user) == {feed.id: 1}
@pytest.mark.django_db
def test_fetch_feed_task_skips_inactive_feed():
feed = Feed.objects.create(feed_url="https://example.com/feed.xml", is_active=False)
+102 -55
View File
@@ -188,8 +188,7 @@ def test_sidebar_shows_a_tags_total_unread_count(client, alice):
response = client.get(reverse("reader:stream"))
# The only "7" on the page — the individual feeds show 3 and 4.
content = response.content.decode()
assert '<span class="unread-count">7</span>' in content
assert sorted(_visible_counts(response.content.decode())) == ["3", "4", "7"]
@pytest.mark.django_db
@@ -226,35 +225,27 @@ def test_article_rows_carry_their_utc_instant_for_client_side_date_grouping(clie
@pytest.mark.django_db
def test_check_new_articles_reports_nothing_below_the_given_cursor(client, alice):
def test_pages_render_the_banner_placeholder_and_baseline_for_any_scope(client, alice):
"""The banner lives in the base layout with the page's baseline id
rendered in, so it works under any feed/tag selection (and on pages
that aren't the stream), not only the unscoped list."""
feed = Feed.objects.create(feed_url="https://example.com/feed.xml")
Subscription.objects.create(user=alice, feed=feed)
existing = Article.objects.create(feed=feed, guid="existing", title="Existing")
article = Article.objects.create(feed=feed, guid="g1", title="Hello")
client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("reader:check_new"), {"filter": "all", "since": existing.pk})
assert response.status_code == 200
assert response.content.decode().strip() == ""
for query in ({"filter": "all"}, {"feed": feed.pk}):
content = client.get(reverse("reader:stream"), query).content.decode()
assert 'class="new-articles-banner"' in content
assert f'data-since="{article.pk}"' in content
other_page = client.get(reverse("feeds:subscription_list")).content.decode()
assert 'class="new-articles-banner"' in other_page
@pytest.mark.django_db
def test_check_new_articles_reports_articles_created_after_the_cursor(client, alice):
feed = Feed.objects.create(feed_url="https://example.com/feed.xml")
Subscription.objects.create(user=alice, feed=feed)
existing = Article.objects.create(feed=feed, guid="existing", title="Existing")
Article.objects.create(feed=feed, guid="new-1", title="New one")
client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("reader:check_new"), {"filter": "all", "since": existing.pk})
content = response.content.decode()
assert "1 new article" in content
assert "click to show" in content
@pytest.mark.django_db
def test_check_new_articles_respects_the_active_tag_scope(client, alice):
def test_new_since_counts_new_articles_outside_the_page_s_own_feed(client, alice):
"""The banner for a page showing feed A still reports a new article in
feed B — the poll isn't scoped to the selected feed or tag."""
from apps.articles.models import SubscriptionTag, Tag
feed_a = Feed.objects.create(feed_url="https://a.example.com/feed.xml")
@@ -263,38 +254,93 @@ def test_check_new_articles_respects_the_active_tag_scope(client, alice):
Subscription.objects.create(user=alice, feed=feed_b)
tag = Tag.objects.create(user=alice, name="work")
SubscriptionTag.objects.create(user=alice, subscription=sub_a, tag=tag)
cursor = Article.objects.create(feed=feed_a, guid="cursor", title="Cursor").pk
# New in feed_b, which isn't tagged "work" — shouldn't count for this scope.
Article.objects.create(feed=feed_b, guid="untagged-new", title="Untagged new")
client.login(username="alice", password="pw-alice-123")
response = client.get(
reverse("reader:check_new"), {"filter": "all", "tag": tag.pk, "since": cursor}
)
body = client.get(reverse("reader:new_since"), {"since": cursor}).json()
assert response.content.decode().strip() == ""
# New in feed_a (tagged "work") — should count.
Article.objects.create(feed=feed_a, guid="tagged-new", title="Tagged new")
response = client.get(
reverse("reader:check_new"), {"filter": "all", "tag": tag.pk, "since": cursor}
)
assert "1 new article" in response.content.decode()
assert body["new_count"] == 1
@pytest.mark.django_db
def test_stream_exposes_the_latest_article_id_and_scope_for_the_banner(client, alice):
feed = Feed.objects.create(feed_url="https://example.com/feed.xml")
Subscription.objects.create(user=alice, feed=feed)
article = Article.objects.create(feed=feed, guid="g1", title="Hello")
def test_new_since_returns_current_sidebar_counts(client, alice):
from apps.articles.models import SubscriptionTag, Tag
feed = Feed.objects.create(feed_url="https://a.example.com/feed.xml")
sub = Subscription.objects.create(user=alice, feed=feed)
tag = Tag.objects.create(user=alice, name="work")
SubscriptionTag.objects.create(user=alice, subscription=sub, tag=tag)
for i in range(3):
Article.objects.create(feed=feed, guid=f"g{i}", title=f"T{i}")
client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("reader:stream"), {"filter": "all"})
content = response.content.decode()
counts = client.get(reverse("reader:new_since"), {"since": 0}).json()["counts"]
assert f"since={article.pk}" in content
assert "filter=all" in content
assert counts == {"feeds": {str(feed.pk): 3}, "tags": {str(tag.pk): 3}, "starred": 0}
@pytest.mark.django_db
@pytest.mark.parametrize(
"url_name, uses_article",
[("reader:toggle_read", True), ("reader:toggle_star", True), ("reader:article_inline", True)],
)
def test_actions_that_change_counts_tell_the_page_to_refresh_them(
client, alice, url_name, uses_article
):
feed = Feed.objects.create(feed_url="https://example.com/feed.xml")
Subscription.objects.create(user=alice, feed=feed)
article = Article.objects.create(feed=feed, guid="a-1", title="Hello")
client.login(username="alice", password="pw-alice-123")
url = reverse(url_name, args=[article.pk])
response = client.get(url) if url_name == "reader:article_inline" else client.post(url)
assert response["HX-Trigger"] == "countsChanged"
def _visible_counts(content):
"""Texts of the sidebar count badges that are actually shown."""
return re.findall(
r'<span class="unread-count" data-(?:feed|tag)-id="\d+">(\d+)</span>', content
)
@pytest.mark.django_db
def test_sidebar_count_is_fresh_right_after_new_articles_are_ingested(client, alice):
"""Ingestion drops the cached counts, so the next render (and the next
poll) shows new articles at once instead of after the cache TTL."""
from apps.core.cache_utils import invalidate_feed_subscribers_sidebar_cache
feed = Feed.objects.create(feed_url="https://example.com/feed.xml")
Subscription.objects.create(user=alice, feed=feed)
Article.objects.create(feed=feed, guid="a-1", title="One")
client.login(username="alice", password="pw-alice-123")
assert _visible_counts(client.get(reverse("reader:stream")).content.decode()) == ["1"]
Article.objects.create(feed=feed, guid="a-2", title="Two")
assert _visible_counts(client.get(reverse("reader:stream")).content.decode()) == ["1"]
invalidate_feed_subscribers_sidebar_cache(feed.pk)
assert _visible_counts(client.get(reverse("reader:stream")).content.decode()) == ["2"]
@pytest.mark.django_db
def test_new_subscription_shows_its_count_without_waiting_for_the_cache(client, alice):
feed_a = Feed.objects.create(feed_url="https://a.example.com/feed.xml")
feed_b = Feed.objects.create(feed_url="https://b.example.com/feed.xml")
Subscription.objects.create(user=alice, feed=feed_a)
Article.objects.create(feed=feed_a, guid="a", title="A")
Article.objects.create(feed=feed_b, guid="b", title="B")
client.login(username="alice", password="pw-alice-123")
client.get(reverse("reader:stream"))
Subscription.objects.create(user=alice, feed=feed_b)
assert sorted(_visible_counts(client.get(reverse("reader:stream")).content.decode())) == [
"1",
"1",
]
@pytest.mark.django_db
@@ -310,12 +356,12 @@ def test_sidebar_unread_count_updates_immediately_after_reading_an_article(clien
client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("reader:stream"))
assert '<span class="unread-count">1</span>' in response.content.decode()
assert _visible_counts(response.content.decode()) == ["1"]
client.get(reverse("reader:article_detail", args=[article.pk]))
response = client.get(reverse("reader:stream"))
assert "unread-count" not in response.content.decode()
assert _visible_counts(response.content.decode()) == []
@pytest.mark.django_db
@@ -327,12 +373,12 @@ def test_sidebar_unread_count_updates_immediately_after_toggle_read(client, alic
client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("reader:stream"))
assert "unread-count" not in response.content.decode()
assert _visible_counts(response.content.decode()) == []
client.post(reverse("reader:toggle_read", args=[article.pk]))
response = client.get(reverse("reader:stream"))
assert '<span class="unread-count">1</span>' in response.content.decode()
assert _visible_counts(response.content.decode()) == ["1"]
@pytest.mark.django_db
@@ -343,12 +389,12 @@ def test_sidebar_unread_count_updates_immediately_after_mark_all_read(client, al
client.login(username="alice", password="pw-alice-123")
response = client.get(reverse("reader:stream"))
assert '<span class="unread-count">1</span>' in response.content.decode()
assert _visible_counts(response.content.decode()) == ["1"]
client.post(reverse("reader:mark_all_read"))
response = client.get(reverse("reader:stream"))
assert "unread-count" not in response.content.decode()
assert _visible_counts(response.content.decode()) == []
def _stream_article_ids(client, query):
@@ -520,7 +566,8 @@ def test_new_since_without_a_cursor_returns_the_baseline_id(client, alice):
client.login(username="alice", password="pw-alice-123")
body = client.get(reverse("reader:new_since")).json()
assert body == {"latest_id": article.pk, "new_count": 0}
assert body["latest_id"] == article.pk
assert body["new_count"] == 0
@pytest.mark.django_db
@@ -546,14 +593,14 @@ def test_new_since_counts_only_new_unread_visible_articles_from_my_feeds(client,
@pytest.mark.django_db
def test_authenticated_pages_load_the_tab_badge_script_with_its_endpoint(client, alice):
def test_authenticated_pages_load_the_live_updates_script_with_its_endpoint(client, alice):
client.login(username="alice", password="pw-alice-123")
content = client.get(reverse("reader:stream")).content.decode()
assert "js/tab-badge" in content
assert "js/live-updates" in content
assert f'data-url="{reverse("reader:new_since")}"' in content
client.logout()
assert "tab-badge" not in client.get(reverse("accounts:login")).content.decode()
assert "live-updates" not in client.get(reverse("accounts:login")).content.decode()
@pytest.mark.django_db
-1
View File
@@ -6,7 +6,6 @@ app_name = "reader"
urlpatterns = [
path("", views.stream, name="stream"),
path("check-new/", views.check_new_articles, name="check_new"),
path("new-since/", views.new_since, name="new_since"),
path("mark-all-read/", views.mark_all_read, name="mark_all_read"),
path("articles/<int:article_id>/", views.article_detail, name="article_detail"),
+21 -32
View File
@@ -22,6 +22,7 @@ from apps.articles.models import (
)
from apps.articles.queries import with_user_state
from apps.core.cache_utils import invalidate_sidebar_unread_cache
from apps.core.context_processors import sidebar_counts
from apps.feeds.models import Feed
FILTER_CHOICES = [
@@ -137,7 +138,7 @@ def _resolve_active_filter(request):
def _filtered_queryset(request, active_filter):
"""The stream's fully-scoped queryset (filter tab + tag/feed scope),
unpaginated — shared by stream() and check_new_articles() so the "any
unpaginated — used by stream() so the "any
new articles?" check always matches exactly what the stream itself
would show."""
queryset = _base_queryset(request.user)
@@ -233,44 +234,25 @@ def stream(request):
"has_older_page": has_older_page and bool(articles),
"newer_qs": newer_qs,
"older_qs": older_qs,
# Lets the "new articles" banner ask, on this exact same scope,
# whether anything with a higher id has shown up since this page
# was rendered — id (not published_at) because it's monotonic
# regardless of how a feed backdates an entry's published date.
"latest_article_id": queryset.aggregate(Max("id"))["id__max"] or 0,
"new_check_qs": urlencode(scope_params),
"scope_qs": urlencode(scope_params),
}
return render(request, "reader/stream.html", context)
@login_required
def check_new_articles(request):
active_filter = _resolve_active_filter(request)
queryset, _active_tag, _active_feed = _filtered_queryset(request, active_filter)
try:
since_id = int(request.GET.get("since", 0))
except ValueError:
since_id = 0
new_count = queryset.filter(id__gt=since_id).count()
return render(request, "reader/_new_articles_banner.html", {"new_count": new_count})
@login_required
def new_since(request):
"""Feeds the browser-tab dot (static/js/tab-badge.js) on every page:
without ?since it returns the current highest article id, which the
page keeps as its baseline; with it, how many unread, non-hidden
articles from the user's subscriptions have appeared after that id.
Deliberately not scoped to the stream's current filter/tag/feed — the
tab should light up for anything new, whichever page is open."""
"""Feeds the live updates (static/js/live-updates.js) on every
authenticated page: how many unread, non-hidden articles from the
user's subscriptions have appeared after the page's baseline id
(?since), for the new-articles banner and the browser-tab dot, plus
the sidebar's current counts. Deliberately not scoped to the stream's
current filter/tag/feed — anything new, whichever page is open."""
latest_id = Article.objects.aggregate(Max("id"))["id__max"] or 0
counts = sidebar_counts(request.user)
try:
since_id = int(request.GET["since"])
except (KeyError, ValueError):
return JsonResponse({"latest_id": latest_id, "new_count": 0})
return JsonResponse({"latest_id": latest_id, "new_count": 0, "counts": counts})
new_count = (
_base_queryset(request.user)
@@ -278,7 +260,7 @@ def new_since(request):
.exclude(user_states__user=request.user, user_states__is_read=True)
.count()
)
return JsonResponse({"latest_id": latest_id, "new_count": new_count})
return JsonResponse({"latest_id": latest_id, "new_count": new_count, "counts": counts})
@login_required
@@ -318,6 +300,13 @@ def mark_all_read(request):
return redirect(f"{stream_url}?{query}" if query else stream_url)
def _counts_changed(response):
"""Tells the page's live-update script (static/js/live-updates.js) to
refresh the sidebar counts right now rather than at the next poll."""
response["HX-Trigger"] = "countsChanged"
return response
def _load_article_and_mark_read(user, article_id):
article = get_object_or_404(_base_queryset(user), pk=article_id)
@@ -353,7 +342,7 @@ def article_inline(request, article_id):
content fragment plus an out-of-band update of the row's own read/star
icons (see templates/reader/_article_inline.html)."""
article = _load_article_and_mark_read(request.user, article_id)
return render(request, "reader/_article_inline.html", {"article": article})
return _counts_changed(render(request, "reader/_article_inline.html", {"article": article}))
@login_required
@@ -369,7 +358,7 @@ def toggle_read(request, article_id):
article.is_read = state.is_read
article.is_starred, article.is_saved_for_later = _article_tag_flags(request.user, article)
return render(request, "reader/_article_actions.html", {"article": article})
return _counts_changed(render(request, "reader/_article_actions.html", {"article": article}))
@login_required
@@ -405,4 +394,4 @@ def _toggle_system_tag(request, article_id, tag_name):
article.is_read = state.is_read if state else False
article.is_starred, article.is_saved_for_later = _article_tag_flags(request.user, article)
return render(request, "reader/_article_actions.html", {"article": article})
return _counts_changed(render(request, "reader/_article_actions.html", {"article": article}))
+6
View File
@@ -113,6 +113,12 @@ form p {
display: inline;
}
.new-articles-banner[hidden],
.unread-count[hidden],
.starred-count[hidden] {
display: none;
}
.new-articles-banner {
display: block;
width: 100%;
+164
View File
@@ -0,0 +1,164 @@
// Keeps every authenticated page current without ever moving the article
// list under the reader. One poll (/new-since/) drives three things:
// - the "N new articles" banner, wherever in the sidebar tree you are;
// - a red dot on the browser tab's favicon, visible from a background tab;
// - the sidebar's unread/starred counts, patched in place.
// New articles are never inserted automatically: the banner click reloads
// the current view. A full page load resets the baseline (data-since,
// rendered into the page) — exactly when the user has seen the new articles.
// The poll deliberately keeps running in a hidden tab (that's what the dot is
// for); it also fires when the tab becomes visible again, and as soon as a
// read/star action tells us the counts changed (the countsChanged event the
// server sends via HX-Trigger).
(function () {
var POLL_MS = 300000;
var MIN_GAP_MS = 15000; // coalesce bursts (rapid reading, tab switches)
var script = document.currentScript;
var url = script && script.dataset.url;
var icon = document.querySelector('link[rel="icon"]');
var banner = document.querySelector(".new-articles-banner");
if (!url) return;
var originalHref = icon ? icon.href : null;
var baseline = parseInt(script.dataset.since, 10);
if (isNaN(baseline)) baseline = null;
var timer = null;
var inFlight = false;
var rerun = false; // a read happened while a poll was in flight: its answer may predate it
var lastPoll = 0;
var badged = null; // the dotted icon's data: URL, drawn once on first need
var showing = false;
function drawDot() {
return new Promise(function (resolve) {
var image = new Image();
image.onload = function () {
var size = 64;
var canvas = document.createElement("canvas");
canvas.width = canvas.height = size;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, size, size);
ctx.beginPath();
ctx.arc(size * 0.74, size * 0.26, size * 0.23, 0, 2 * Math.PI);
ctx.fillStyle = "#e53935";
ctx.fill();
ctx.lineWidth = size * 0.07;
ctx.strokeStyle = "#ffffff";
ctx.stroke();
resolve(canvas.toDataURL("image/png"));
};
image.onerror = function () {
resolve(null);
};
image.src = originalHref;
});
}
// Replace the <link> rather than editing href: some browsers ignore an
// in-place change to an existing favicon element.
function setIcon(href) {
var fresh = icon.cloneNode();
fresh.href = href;
icon.parentNode.replaceChild(fresh, icon);
icon = fresh;
}
function showDot(on) {
if (!icon || on === showing) return Promise.resolve();
showing = on;
if (!on) {
setIcon(originalHref);
return Promise.resolve();
}
var ready = badged ? Promise.resolve(badged) : drawDot();
return ready.then(function (href) {
badged = href;
if (href && showing) setIcon(href);
});
}
function setCount(el, value) {
var text = el.hasAttribute("data-starred-count") ? "(" + value + ")" : String(value);
el.textContent = value ? text : "";
el.hidden = !value;
}
function updateCounts(counts) {
if (!counts) return;
document.querySelectorAll(".unread-count[data-feed-id]").forEach(function (el) {
setCount(el, counts.feeds[el.dataset.feedId] || 0);
});
document.querySelectorAll(".unread-count[data-tag-id]").forEach(function (el) {
setCount(el, counts.tags[el.dataset.tagId] || 0);
});
document.querySelectorAll("[data-starred-count]").forEach(function (el) {
setCount(el, counts.starred || 0);
});
}
function updateBanner(count) {
if (!banner) return;
banner.hidden = !count;
if (count) {
banner.textContent =
count + " new article" + (count === 1 ? "" : "s") + " \u2014 click to refresh";
}
}
function schedule() {
clearTimeout(timer);
timer = setTimeout(poll, POLL_MS);
}
function poll() {
if (inFlight) {
rerun = true;
return;
}
inFlight = true;
lastPoll = Date.now();
var query = baseline === null ? "" : "?since=" + baseline;
fetch(url + query, { credentials: "same-origin", headers: { Accept: "application/json" } })
.then(function (response) {
// A redirect means the session ended (we'd be reading the login
// page) — stop polling instead of hammering it.
if (!response.ok || response.redirected) throw new Error("stop");
return response.json();
})
.then(function (data) {
inFlight = false;
if (baseline === null) baseline = data.latest_id;
updateCounts(data.counts);
updateBanner(data.new_count);
showDot(data.new_count > 0);
if (rerun) {
rerun = false;
poll();
} else {
schedule();
}
})
.catch(function (error) {
inFlight = false;
rerun = false;
if (error.message !== "stop") schedule();
});
}
function pollSoon() {
var wait = Math.max(0, MIN_GAP_MS - (Date.now() - lastPoll));
clearTimeout(timer);
timer = setTimeout(poll, wait);
}
document.addEventListener("visibilitychange", function () {
if (!document.hidden) pollSoon();
});
document.body.addEventListener("countsChanged", function () {
// Reading is interactive: refresh the sidebar now, not after the gap.
clearTimeout(timer);
timer = setTimeout(poll, 150);
});
poll();
})();
+8 -1
View File
@@ -41,7 +41,14 @@ document.addEventListener("click", function (event) {
toggleArticle(link);
return;
}
if (event.target.closest(".new-articles-banner")) {
var banner = event.target.closest(".new-articles-banner");
if (banner) {
// Reloading keeps the current filter/tag/feed in the URL; from any
// other page (settings, search) go to the stream instead.
if (location.pathname === banner.dataset.streamUrl) {
location.reload();
} else {
location.href = banner.dataset.streamUrl;
}
}
});
-85
View File
@@ -1,85 +0,0 @@
// Marks the browser tab with a red dot on its favicon when new unread
// articles have arrived since this page loaded — visible from a background
// tab, unlike the in-page "new articles" banner. Runs on every
// authenticated page; a full page load resets the baseline (and the icon),
// which is exactly when the user has seen the new articles.
(function () {
var POLL_MS = 30000;
var url = document.currentScript && document.currentScript.dataset.url;
var icon = document.querySelector('link[rel="icon"]');
if (!url || !icon) return;
var originalHref = icon.href;
var baseline = null;
var badged = null; // the dotted icon's data: URL, drawn once on first need
var showing = false;
function drawDot() {
return new Promise(function (resolve) {
var image = new Image();
image.onload = function () {
var size = 64;
var canvas = document.createElement("canvas");
canvas.width = canvas.height = size;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, size, size);
ctx.beginPath();
ctx.arc(size * 0.74, size * 0.26, size * 0.23, 0, 2 * Math.PI);
ctx.fillStyle = "#e53935";
ctx.fill();
ctx.lineWidth = size * 0.07;
ctx.strokeStyle = "#ffffff";
ctx.stroke();
resolve(canvas.toDataURL("image/png"));
};
image.onerror = function () {
resolve(null);
};
image.src = originalHref;
});
}
// Replace the <link> rather than editing href: some browsers ignore an
// in-place change to an existing favicon element.
function setIcon(href) {
var fresh = icon.cloneNode();
fresh.href = href;
icon.parentNode.replaceChild(fresh, icon);
icon = fresh;
}
function showDot(on) {
if (on === showing) return Promise.resolve();
showing = on;
if (!on) {
setIcon(originalHref);
return Promise.resolve();
}
var ready = badged ? Promise.resolve(badged) : drawDot();
return ready.then(function (href) {
badged = href;
if (href && showing) setIcon(href);
});
}
function poll() {
var query = baseline === null ? "" : "?since=" + baseline;
fetch(url + query, { credentials: "same-origin", headers: { Accept: "application/json" } })
.then(function (response) {
// A redirect means the session ended (we'd be reading the login
// page) — stop polling instead of hammering it.
if (!response.ok || response.redirected) throw new Error("stop");
return response.json();
})
.then(function (data) {
if (baseline === null) baseline = data.latest_id;
else showDot(data.new_count > 0);
setTimeout(poll, POLL_MS);
})
.catch(function (error) {
if (error.message !== "stop") setTimeout(poll, POLL_MS);
});
}
poll();
})();
+4 -2
View File
@@ -38,7 +38,9 @@
{% endif %}
<main class="{% if user.is_authenticated %}app-content{% else %}auth-content{% endif %}">
{% if not user.is_authenticated %}
{% if user.is_authenticated %}
<button type="button" class="new-articles-banner" data-stream-url="{% url 'reader:stream' %}" hidden></button>
{% else %}
<div class="auth-brand">
<img src="{% static 'img/brand-full-dark.png' %}" alt="Evection" class="brand-wordmark-dark">
<img src="{% static 'img/brand-full-light.png' %}" alt="Evection" class="brand-wordmark-light">
@@ -58,7 +60,7 @@
{% if user.is_authenticated %}
<script src="{% static 'js/theme.js' %}" defer></script>
<script src="{% static 'js/sidebar-state.js' %}" defer></script>
<script src="{% static 'js/tab-badge.js' %}" data-url="{% url 'reader:new_since' %}" defer></script>
<script src="{% static 'js/live-updates.js' %}" data-url="{% url 'reader:new_since' %}" data-since="{{ latest_article_id }}" defer></script>
{% endif %}
<script src="{% static 'js/register-sw.js' %}" defer></script>
</body>
+4 -4
View File
@@ -19,7 +19,7 @@
<li>
<a href="{% url 'reader:stream' %}?filter=starred"
class="{% if request.GET.filter == 'starred' %}active{% endif %}">
Favourites{% if sidebar_starred_count %} ({{ sidebar_starred_count }}){% endif %}
Favourites <span class="starred-count" data-starred-count{% if not sidebar_starred_count %} hidden{% endif %}>({{ sidebar_starred_count }})</span>
</a>
</li>
<li>
@@ -36,7 +36,7 @@
<span class="sidebar-tag-row">
<a href="{% url 'reader:stream' %}?tag={{ entry.tag.pk }}"
class="sidebar-tag-link{% if request.GET.tag == entry.tag.pk|stringformat:'s' %} active{% endif %}">{{ entry.tag.name }}</a>
{% if entry.unread_count %}<span class="unread-count">{{ entry.unread_count }}</span>{% endif %}
<span class="unread-count" data-tag-id="{{ entry.tag.pk }}"{% if not entry.unread_count %} hidden{% endif %}>{% if entry.unread_count %}{{ entry.unread_count }}{% endif %}</span>
</span>
</summary>
{% if entry.subscriptions %}
@@ -48,7 +48,7 @@
{% if subscription.feed.favicon_url %}<img src="{{ subscription.feed.favicon_url }}" alt="" class="feed-favicon">{% endif %}
<span>{{ subscription.display_title }}</span>
</a>
{% if subscription.unread_count %}<span class="unread-count">{{ subscription.unread_count }}</span>{% endif %}
<span class="unread-count" data-feed-id="{{ subscription.feed_id }}"{% if not subscription.unread_count %} hidden{% endif %}>{% if subscription.unread_count %}{{ subscription.unread_count }}{% endif %}</span>
</li>
{% endfor %}
</ul>
@@ -67,7 +67,7 @@
{% if subscription.feed.favicon_url %}<img src="{{ subscription.feed.favicon_url }}" alt="" class="feed-favicon">{% endif %}
<span>{{ subscription.display_title }}</span>
</a>
{% if subscription.unread_count %}<span class="unread-count">{{ subscription.unread_count }}</span>{% endif %}
<span class="unread-count" data-feed-id="{{ subscription.feed_id }}"{% if not subscription.unread_count %} hidden{% endif %}>{% if subscription.unread_count %}{{ subscription.unread_count }}{% endif %}</span>
</li>
{% endfor %}
</ul>
@@ -1,5 +0,0 @@
{% if new_count %}
<button type="button" class="new-articles-banner">
{{ new_count }} new article{{ new_count|pluralize }} — click to show
</button>
{% endif %}
-6
View File
@@ -23,11 +23,5 @@
</form>
</div>
<div id="new-articles-banner"
hx-get="{% url 'reader:check_new' %}?since={{ latest_article_id }}&{{ new_check_qs }}"
hx-trigger="every 30s"
hx-target="this"
hx-swap="innerHTML"></div>
{% include "reader/_article_list.html" %}
{% endblock %}