patx/gitman

Open notification cards and mark them read on activation

Commit 308b118 · patx · Nov 3 at 8:37PM

Changeset
308b118966fb00da660c9da6be5f012d48095e41
Parents
49a78b85562f83668fc1c3ba33bb8c03c034b499

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/README.md b/README.md
index a95789a..306a87c 100644
--- a/README.md
+++ b/README.md
@@ -58,8 +58,9 @@ Commit activity scans up to `GITMAN_ACTIVITY_REPO_SCAN_LIMIT` owned or starred r
 prioritizing the most recently updated repositories.
 
 The bell shows an unread count (99+ for larger counts). Opening the feed does not
-mark it read. Use **Mark as read** on an entry or **Mark all as read** to clear the
-current activity; read entries stay in the feed. Read state is stored per account
+mark it read. Unread notifications have a distinct background. Click anywhere on
+a notification card to open the related activity and mark that notification read;
+read entries stay in the feed. Read state is stored per account
 and shared across devices. New events remain unread, including replies posted in
 the same second as a bulk-read action and commits with backdated author dates.
 The count refreshes on page load, when returning to a tab, and once a minute while
diff --git a/app.py b/app.py
index b99e312..d1d386f 100644
--- a/app.py
+++ b/app.py
@@ -1767,7 +1767,7 @@ def list_recent_actions(limit=50, user_id=None, offset=0, *, unread_only=False,
             read_before=read_before, read_keys=read_keys, unread_only=unread_only, since=since))
         for action in actions:
             action["is_read"] = notification_is_read(action, read_before, read_keys)
-            action["read_signature"] = notification_signature(user_id, action["event_key"])
+            action["read_signature"] = notification_signature(user_id, action["event_key"] + ":" + action["target_url"])
     actions.sort(key=activity_sort_key, reverse=True)
     return actions[offset:fetch_limit]
 
@@ -5021,6 +5021,7 @@ def index():
 @app.route("/-/notifications")
 def notifications():
     user = require_login()
+    response.set_header("Cache-Control", "no-store")
     page = request_page()
     per_page = request_per_page(25)
     actions = list_recent_actions(per_page + 1, user_id=user["id"], offset=page_offset(page, per_page))
@@ -5046,13 +5047,15 @@ def read_notification():
     user = require_login()
     key = request.forms.get("notification_key", "")
     signature = request.forms.get("signature", "")
+    target = request.forms.get("target", "")
+    signed_key = key + ":" + target if target else key
     if (not re.fullmatch(r"[a-f0-9]{64}", key) or not re.fullmatch(r"[a-f0-9]{64}", signature)
-            or not hmac.compare_digest(signature, notification_signature(user["id"], key))):
+            or not hmac.compare_digest(signature, notification_signature(user["id"], signed_key))):
         abort(403, "Invalid notification.")
     with db_connect() as conn:
         conn.execute("INSERT OR IGNORE INTO notification_reads (user_id, event_key, read_at) VALUES (?, ?, ?)",
             (user["id"], key, utcnow()))
-    redirect("/-/notifications")
+    redirect(safe_next_url(target, "/-/notifications"))
 
 
 @app.route("/-/notifications/read-all", method="POST")
diff --git a/static/notifications.js b/static/notifications.js
index c8756d4..5ddc371 100644
--- a/static/notifications.js
+++ b/static/notifications.js
@@ -23,6 +23,16 @@
       loading = false;
     }
   };
+  window.addEventListener('pageshow', (event) => {
+    const navigation = performance.getEntriesByType('navigation')[0];
+    if (!event.persisted && (!navigation || navigation.type !== 'back_forward')) return;
+    if (document.querySelector('[data-notification-feed]')) {
+      window.location.reload();
+    } else {
+      checkedAt = 0;
+      refresh();
+    }
+  });
   refresh();
   setInterval(refresh, 60000);
   window.addEventListener('focus', refresh);
diff --git a/static/styles.css b/static/styles.css
index 060be33..0eff9b6 100644
--- a/static/styles.css
+++ b/static/styles.css
@@ -572,8 +572,30 @@ th { color: var(--ink); font-weight: 700; }
   line-height: 1;
   text-align: center;
 }
-.notification-unread .activity-title { font-weight: 700; }
-.notification-read-form { display: inline; margin: 0; font-size: .875rem; }
+.notification-feed > li { padding: 0; border: 0; }
+.notification-feed form { display: block; }
+.notification-card {
+  display: block;
+  width: 100%;
+  padding: 1.25rem;
+  border: 1px solid var(--surface-border);
+  border-radius: 8px;
+  background: var(--page-bg);
+  color: var(--text);
+  text-align: left;
+  font-weight: 400;
+  line-height: 1.6;
+  overflow-wrap: anywhere;
+}
+.notification-card > span { display: block; margin: 0; }
+.notification-card > span + span { margin-top: .5rem; }
+.notification-card .activity-title { color: var(--ink); }
+.notification-card.notification-unread { background: var(--code-bg); }
+.notification-card:hover, .notification-card:active {
+  background: var(--chip);
+  color: var(--text);
+}
+.notification-card:focus-visible { outline-offset: 3px; }
 .mention-option:hover small, .mention-option.active small { color: inherit; }
 
 @media (max-width: 760px) {
diff --git a/templates/activity_feed.tpl b/templates/activity_feed.tpl
index 897eb40..a0f8177 100644
--- a/templates/activity_feed.tpl
+++ b/templates/activity_feed.tpl
@@ -1,8 +1,11 @@
-    <ol class="activity-feed" data-paginated-list>
+    <ol class="activity-feed{{' notification-feed' if get('notifications_feed', False) else ''}}" data-paginated-list>
       % for action in actions:
         % repo_url = "/" + action["repo_owner_username"] + "/" + action["repo_name"] if action["repo_owner_username"] and action["repo_name"] else ""
         % show_repo_context = repo_url and action["target_url"] != repo_url
-        <li class="{{'notification-unread' if get('notifications_feed', False) and not action['is_read'] else ''}}">
+        <li>
+          % if get('notifications_feed', False):
+            % include('notification_card.tpl', action=action, show_repo_context=show_repo_context)
+          % else:
           <p class="activity-title">
             % if action["actor_url"]:
               <strong><a href="{{action['actor_url']}}">{{action["actor_label"]}}</a></strong>
@@ -18,21 +21,10 @@
             % end
             {{action["occurred_at"]}}
           </p>
-          % if get("notifications_feed", False):
-            % if action["is_read"]:
-              <small class="muted">Read</small>
-            % else:
-              <form class="notification-read-form" action="/-/notifications/read" method="post">
-                {{!csrf_field()}}
-                <input type="hidden" name="notification_key" value="{{action['event_key']}}">
-                <input type="hidden" name="signature" value="{{action['read_signature']}}">
-                <button class="link-button" type="submit">Mark as read</button>
-              </form>
-            % end
-          % end
           % if action["detail"]:
             <p class="activity-detail">{{!render_markdown_links(action["detail"])}}</p>
           % end
+          % end
         </li>
       % end
     </ol>
diff --git a/templates/base.tpl b/templates/base.tpl
index 6923443..1f2b960 100644
--- a/templates/base.tpl
+++ b/templates/base.tpl
@@ -11,7 +11,7 @@
   <link rel="icon" type="image/svg+xml" href="/static/git.svg">
   <link rel="stylesheet" href="/static/vendor/highlight.js/github.min.css">
   <link rel="stylesheet" href="/static/vendor/highlight.js/github-dark.min.css" media="(prefers-color-scheme: dark)">
-  <link rel="stylesheet" href="/static/styles.css?v=12">
+  <link rel="stylesheet" href="/static/styles.css?v=13">
 </head>
 <body>
   <header class="site-header">
@@ -65,7 +65,7 @@
   </footer>
   <script src="/static/mentions.js?v=1" defer></script>
   % if user:
-    <script src="/static/notifications.js?v=1" defer></script>
+    <script src="/static/notifications.js?v=2" defer></script>
   % end
   <script src="/static/vendor/highlight.js/highlight.min.js"></script>
   <script>
diff --git a/templates/notification_card.tpl b/templates/notification_card.tpl
new file mode 100644
index 0000000..89b4075
--- /dev/null
+++ b/templates/notification_card.tpl
@@ -0,0 +1,18 @@
+<form action="/-/notifications/read" method="post">
+  {{!csrf_field()}}
+  <input type="hidden" name="notification_key" value="{{action['event_key']}}">
+  <input type="hidden" name="signature" value="{{action['read_signature']}}">
+  <input type="hidden" name="target" value="{{action['target_url']}}">
+  <button class="notification-card{{' notification-unread' if not action['is_read'] else ''}}" type="submit" aria-label="{{'Unread notification: ' if not action['is_read'] else 'Notification: '}}{{action['actor_label']}} {{action['summary']}} {{action['target_label']}}">
+    <span class="activity-title"><strong>{{action['actor_label']}}</strong> {{action['summary']}} <strong>{{action['target_label']}}</strong></span>
+    <span class="muted">
+      % if show_repo_context:
+        in {{action['repo_owner_username']}}/{{action['repo_name']}} ·
+      % end
+      {{action['occurred_at']}}
+    </span>
+    % if action['detail']:
+      <span class="activity-detail">{{action['detail']}}</span>
+    % end
+  </button>
+</form>
diff --git a/templates/notifications.tpl b/templates/notifications.tpl
index 677be55..1e61fe2 100644
--- a/templates/notifications.tpl
+++ b/templates/notifications.tpl
@@ -1,17 +1,10 @@
 % rebase("base.tpl", title="Notifications", user=user, error=error, notice=notice)
 
-<section class="panel">
+<section class="panel" data-notification-feed>
   <div class="panel-heading">
     <div>
       <h1>Notifications</h1>
-      <p class="muted">Mentions and activity from other people in repositories you own or have starred, and on issues you follow.</p>
     </div>
-    % if actions:
-      <form class="inline-form" method="post" action="/-/notifications/read-all">
-        {{!csrf_field()}}
-        <button class="button secondary small" type="submit">Mark all as read</button>
-      </form>
-    % end
   </div>
 
   % if actions:
diff --git a/tests/test_app.py b/tests/test_app.py
index e55073a..95a0261 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -1,6 +1,7 @@
 import atexit
 import base64
 import json
+import html
 from http.cookies import SimpleCookie
 from io import BytesIO, StringIO
 import os
@@ -2956,8 +2957,11 @@ def test_mentions_notify_nonparticipants_and_link_to_existing_profiles(isolated_
     assert '<a href="/unknown-person">' not in detail
     recipient = WsgiClient(isolated_app.app)
     login_client(recipient, 'alice')
-    feed = recipient.get('/-/notifications?per_page=1').text
-    assert f'href="{target}"' in feed
+    feed_response = recipient.get('/-/notifications?per_page=1')
+    fields = notification_read_fields(feed_response)
+    assert fields['target'] == target
+    assert recipient.post('/-/notifications/read', fields).location_path == target
+    feed = feed_response.text
     assert 'Please review' in feed
     assert 'mentioned you' in feed
     assert 'data-next-url=' not in feed  # repeated mentions yield one event
@@ -3036,9 +3040,10 @@ def test_mention_autocomplete_searches_public_names_without_exposing_account_dat
 
 
 def notification_read_fields(response):
-    form = re.search(r'<form[^>]*action="/-/notifications/read"[^>]*>(.*?)</form>', response.text, re.S)
-    assert form, 'An unread entry must offer a read control'
-    return dict(re.findall(r'name="(notification_key|signature)" value="([^"]+)"', form.group(1)))
+    forms = re.findall(r'<form[^>]*action="/-/notifications/read"[^>]*>(.*?)</form>', response.text, re.S)
+    form = next((form for form in forms if 'notification-card notification-unread' in form), None)
+    assert form, 'An unread notification card must submit its signed destination'
+    return {name: html.unescape(value) for name, value in re.findall(r'name="(notification_key|signature|target)" value="([^"]+)"', form)}
 
 
 def test_notification_read_state_is_per_user_persistent_and_handles_simultaneous_events(isolated_app, monkeypatch):
@@ -3057,15 +3062,22 @@ def test_notification_read_state_is_per_user_persistent_and_handles_simultaneous
     assert json.loads(unread.text)['unread_count'] == 2
     assert b.post('/-/notifications/read-all').status_code == 303
     assert json.loads(a.get('/-/notifications/unread').text)['unread_count'] == 2
-    fields = notification_read_fields(a.get('/-/notifications?per_page=1'))
+    feed_response = a.get('/-/notifications?per_page=1')
+    assert feed_response.header('Cache-Control') == 'no-store'
+    fields = notification_read_fields(feed_response)
     assert b.post('/-/notifications/read', fields).status_code == 403
     assert a.post('/-/notifications/read', {**fields, 'signature': 'invalid'}).status_code == 403
     no_csrf = WsgiClient(isolated_app.app)
     no_csrf.cookies = {'session': a.cookies['session']}
     assert no_csrf.post('/-/notifications/read', fields).status_code == 403
-    assert a.post('/-/notifications/read', fields).status_code == 303
+    assert a.post('/-/notifications/read', {**fields, 'target': 'https://example.com/'}).status_code == 403
+    opened = a.post('/-/notifications/read', fields)
+    assert opened.status_code == 303
+    assert opened.location_path == '/alice/demo/issues/1'
     assert json.loads(a.get('/-/notifications/unread').text)['unread_count'] == 1
-    assert 'Read' in a.get('/-/notifications').text
+    feed = a.get('/-/notifications').text
+    assert feed.count('notification-card notification-unread') == 1
+    assert 'Mark as read' not in feed and 'Mark all as read' not in feed
     assert a.post('/-/notifications/read-all').status_code == 303
     other_device = WsgiClient(isolated_app.app)
     login_client(other_device, 'alice')