Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mark as read #364

Merged
merged 4 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions assets/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,10 @@
"num": {"type": "int", "example": "4"}
}
},
"errorInvalidResponse": "The server sent an invalid response",
"@errorInvalidResponse": {
"description": "Error message when an API call returned an invalid response."
},
"errorNetworkRequestFailed": "Network request failed",
"@errorNetworkRequestFailed": {
"description": "Error message when a network request fails."
Expand Down Expand Up @@ -323,6 +327,28 @@
"@serverUrlValidationErrorUnsupportedScheme": {
"description": "Error message when URL has an unsupported scheme."
},
"markAsReadLabel": "Mark {num, plural, =1{1 message} other{{num} messages}} as read",
"@markAsReadLabel": {
"description": "Button text to mark messages as read.",
"placeholders": {
"num": {"type": "int", "example": "4"}
}
},
"markAsReadComplete": "Marked {num, plural, =1{1 message} other{{num} messages}} as read.",
"@markAsReadComplete": {
"description": "Message when marking messages as read has completed.",
"placeholders": {
"num": {"type": "int", "example": "4"}
}
},
"markAsReadInProgress": "Marking messages as read...",
"@markAsReadInProgress": {
"description": "Progress message when marking messages as read."
},
"errorMarkAsReadFailedTitle": "Mark as read failed",
"@errorMarkAsReadFailedTitle": {
"description": "Error title when mark as read action failed."
},
"userRoleOwner": "Owner",
"@userRoleOwner": {
"description": "Label for UserRole.owner"
Expand Down
8 changes: 8 additions & 0 deletions lib/api/model/narrow.dart
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,14 @@ class ApiNarrowPmWith extends ApiNarrowDm {
ApiNarrowPmWith._(super.operand, {super.negated});
}

// TODO: generalize into ApiNarrowIs
class ApiNarrowIsUnread extends ApiNarrowElement {
@override String get operator => 'is';
@override String get operand => 'unread';

ApiNarrowIsUnread({super.negated});
}

class ApiNarrowMessageId extends ApiNarrowElement {
@override String get operator => 'id';

Expand Down
11 changes: 5 additions & 6 deletions lib/model/internal_link.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,16 @@ String? decodeHashComponent(String str) {
// When you want to point the server to a location in a message list, you
// you do so by passing the `anchor` param.
Uri narrowLink(PerAccountStore store, Narrow narrow, {int? nearMessageId}) {
final apiNarrow = narrow.apiEncode();
// TODO(server-7)
final apiNarrow = resolveDmElements(
narrow.apiEncode(), store.connection.zulipFeatureLevel!);
final fragment = StringBuffer('narrow');
for (ApiNarrowElement element in apiNarrow) {
fragment.write('/');
if (element.negated) {
fragment.write('-');
}

if (element is ApiNarrowDm) {
final supportsOperatorDm = store.connection.zulipFeatureLevel! >= 177; // TODO(server-7)
element = element.resolve(legacy: !supportsOperatorDm);
}

fragment.write('${element.operator}/');

switch (element) {
Expand All @@ -87,6 +84,8 @@ Uri narrowLink(PerAccountStore store, Narrow narrow, {int? nearMessageId}) {
fragment.write('${element.operand.join(',')}-$suffix');
case ApiNarrowDm():
assert(false, 'ApiNarrowDm should have been resolved');
case ApiNarrowIsUnread():
fragment.write(element.operand.toString());
case ApiNarrowMessageId():
fragment.write(element.operand.toString());
}
Expand Down
46 changes: 46 additions & 0 deletions lib/model/unreads.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,54 @@ class Unreads extends ChangeNotifier {

final int selfUserId;

// TODO(#346): account for muted topics and streams
// TODO(#370): maintain this count incrementally, rather than recomputing from scratch
int countInAllMessagesNarrow() {
int c = 0;
for (final messageIds in dms.values) {
c = c + messageIds.length;
}
for (final topics in streams.values) {
for (final messageIds in topics.values) {
c = c + messageIds.length;
Comment on lines +128 to +135
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should get tests.

They can be pretty simple, using the existing helpers in unreads_test.dart: prepare, fillMessages, then check(model.countIn…).equals(3) or whatever.

In principle I guess we should have added a test for countInDmNarrow when we added that method, oops. That'll be easy to add now, though.

}
}
return c;
}

// TODO(#346): account for muted topics and streams
// TODO(#370): maintain this count incrementally, rather than recomputing from scratch
int countInStreamNarrow(int streamId) {
final topics = streams[streamId];
if (topics == null) return 0;
int c = 0;
for (final messageIds in topics.values) {
c = c + messageIds.length;
}
return c;
}

// TODO(#346): account for muted topics and streams
int countInTopicNarrow(int streamId, String topic) {
final topics = streams[streamId];
return topics?[topic]?.length ?? 0;
}

int countInDmNarrow(DmNarrow narrow) => dms[narrow]?.length ?? 0;

int countInNarrow(Narrow narrow) {
switch (narrow) {
case AllMessagesNarrow():
return countInAllMessagesNarrow();
case StreamNarrow():
return countInStreamNarrow(narrow.streamId);
case TopicNarrow():
return countInTopicNarrow(narrow.streamId, narrow.topic);
case DmNarrow():
return countInDmNarrow(narrow);
}
}

void handleMessageEvent(MessageEvent event) {
final message = event.message;
if (message.flags.contains(MessageFlag.read)) {
Expand Down
185 changes: 181 additions & 4 deletions lib/widgets/message_list.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ import 'dart:math';

import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/zulip_localizations.dart';
import 'package:intl/intl.dart';

import '../api/model/model.dart';
import '../api/model/narrow.dart';
import '../api/route/messages.dart';
import '../model/message_list.dart';
import '../model/narrow.dart';
import '../model/store.dart';
import 'action_sheet.dart';
import 'compose_box.dart';
import 'content.dart';
import 'dialog.dart';
import 'icons.dart';
import 'page.dart';
import 'profile.dart';
Expand Down Expand Up @@ -274,10 +278,10 @@ class _MessageListState extends State<MessageList> with PerAccountStoreAwareStat
final valueKey = key as ValueKey;
final index = model!.findItemWithMessageId(valueKey.value);
if (index == -1) return null;
return length - 1 - index;
return length - 1 - (index - 1);
},
controller: scrollController,
itemCount: length,
itemCount: length + 1,
// Setting reverse: true means the scroll starts at the bottom.
// Flipping the indexes (in itemBuilder) means the start/bottom
// has the latest messages.
Expand All @@ -286,7 +290,9 @@ class _MessageListState extends State<MessageList> with PerAccountStoreAwareStat
// TODO on new message when scrolled up, anchor scroll to what's in view
reverse: true,
itemBuilder: (context, i) {
final data = model!.items[length - 1 - i];
if (i == 0) return MarkAsReadWidget(narrow: widget.narrow);

final data = model!.items[length - 1 - (i - 1)];
switch (data) {
case MessageListHistoryStartItem():
return const Center(
Expand All @@ -305,7 +311,7 @@ class _MessageListState extends State<MessageList> with PerAccountStoreAwareStat
case MessageListMessageItem():
return MessageItem(
key: ValueKey(data.message.id),
trailing: i == 0 ? const SizedBox(height: 8) : const SizedBox(height: 11),
trailing: i == 1 ? const SizedBox(height: 8) : const SizedBox(height: 11),
item: data);
}
});
Expand Down Expand Up @@ -345,6 +351,60 @@ class ScrollToBottomButton extends StatelessWidget {
}
}

class MarkAsReadWidget extends StatelessWidget {
const MarkAsReadWidget({super.key, required this.narrow});

final Narrow narrow;

void _handlePress(BuildContext context) async {
if (!context.mounted) return;
try {
await markNarrowAsRead(context, narrow);
} catch (e) {
if (!context.mounted) return;
final zulipLocalizations = ZulipLocalizations.of(context);
await showErrorDialog(context: context,
title: zulipLocalizations.errorMarkAsReadFailedTitle,
message: e.toString());
}
// TODO: clear Unreads.oldUnreadsMissing when `narrow` is [AllMessagesNarrow]
// In the rare case that the user had more than 50K total unreads
// on the server, the client won't have known about all of them;
// this was communicated to the client via `oldUnreadsMissing`.
//
// However, since we successfully marked **everything** as read,
// we know that we now have a correct data set of unreads.
}

@override
Widget build(BuildContext context) {
final zulipLocalizations = ZulipLocalizations.of(context);
final store = PerAccountStoreWidget.of(context);
final unreadCount = store.unreads.countInNarrow(narrow);
return AnimatedCrossFade(
duration: const Duration(milliseconds: 300),
crossFadeState: (unreadCount > 0) ? CrossFadeState.showSecond : CrossFadeState.showFirst,
firstChild: const SizedBox.shrink(),
secondChild: SizedBox(width: double.infinity,
// Design referenced from:
// https://www.figma.com/file/1JTNtYo9memgW7vV6d0ygq/Zulip-Mobile?type=design&node-id=132-9684&mode=design&t=jJwHzloKJ0TMOG4M-0
child: ColoredBox(
// TODO(#368): this should pull from stream color
color: Colors.transparent,
child: Padding(
padding: const EdgeInsets.all(10),
child: FilledButton.icon(
style: FilledButton.styleFrom(
padding: const EdgeInsets.all(10),
textStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.w200),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
),
onPressed: () => _handlePress(context),
icon: const Icon(Icons.playlist_add_check),
label: Text(zulipLocalizations.markAsReadLabel(unreadCount)))))));
}
}

class RecipientHeader extends StatelessWidget {
const RecipientHeader({super.key, required this.message});

Expand Down Expand Up @@ -635,3 +695,120 @@ final _kMessageTimestampStyle = TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: const HSLColor.fromAHSL(0.4, 0, 0, 0.2).toColor());

Future<void> markNarrowAsRead(BuildContext context, Narrow narrow) async {
final store = PerAccountStoreWidget.of(context);
final connection = store.connection;
if (connection.zulipFeatureLevel! < 155) { // TODO(server-6)
return await _legacyMarkNarrowAsRead(context, narrow);
}

// Compare web's `mark_all_as_read` in web/src/unread_ops.js
// and zulip-mobile's `markAsUnreadFromMessage` in src/action-sheets/index.js .
final zulipLocalizations = ZulipLocalizations.of(context);
final scaffoldMessenger = ScaffoldMessenger.of(context);
// Use [AnchorCode.oldest], because [AnchorCode.firstUnread]
// will be the oldest non-muted unread message, which would
// result in muted unreads older than the first unread not
// being processed.
Anchor anchor = AnchorCode.oldest;
int responseCount = 0;
int updatedCount = 0;

final apiNarrow = switch (narrow) {
// Since there's a database index on is:unread, it's a fast
// search query and thus worth using as an optimization
// when processing all messages.
AllMessagesNarrow() => [ApiNarrowIsUnread()],
_ => narrow.apiEncode(),
};
while (true) {
final result = await updateMessageFlagsForNarrow(connection,
anchor: anchor,
// [AnchorCode.oldest] is an anchor ID lower than any valid
// message ID; and follow-up requests will have already
// processed the anchor ID, so we just want this to be
// unconditionally false.
includeAnchor: false,
// There is an upper limit of 5000 messages per batch
// (numBefore + numAfter <= 5000) enforced on the server.
// See `update_message_flags_in_narrow` in zerver/views/message_flags.py .
// zulip-mobile uses `numAfter` of 5000, but web uses 1000
// for more responsive feedback. See zulip@f0d87fcf6.
numBefore: 0,
numAfter: 1000,
narrow: apiNarrow,
op: UpdateMessageFlagsOp.add,
flag: MessageFlag.read);
if (!context.mounted) {
scaffoldMessenger.clearSnackBars();
return;
}
responseCount++;
updatedCount += result.updatedCount;

if (result.foundNewest) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, web has an interesting wrinkle here:

                if (unread.old_unreads_missing) {
                    // In the rare case that the user had more than
                    // 50K total unreads on the server, the client
                    // won't have known about all of them; this was
                    // communicated to the client via
                    // unread.old_unreads_missing.
                    //
                    // However, since we know we just marked
                    // **everything** as read, we know that we now
                    // have a correct data set of unreads.
                    unread.clear_old_unreads_missing();

Seems right. I'd be fine with just leaving a TODO for it, though.

if (responseCount > 1) {
// We previously showed an in-progress [SnackBar], so say we're done.
// There may be a backlog of [SnackBar]s accumulated in the queue
// so be sure to clear them out here.
scaffoldMessenger
..clearSnackBars()
..showSnackBar(SnackBar(behavior: SnackBarBehavior.floating,
content: Text(zulipLocalizations.markAsReadComplete(updatedCount))));
}
return;
}

if (result.lastProcessedId == null) {
// No messages were in the range of the request.
// This should be impossible given that `foundNewest` was false
// (and that our `numAfter` was positive.)
await showErrorDialog(context: context,
title: zulipLocalizations.errorMarkAsReadFailedTitle,
message: zulipLocalizations.errorInvalidResponse);
return;
}
anchor = NumericAnchor(result.lastProcessedId!);

// The task is taking a while, so tell the user we're working on it.
// No need to say how many messages, as the [MarkAsUnread] widget
// should follow along.
// TODO: Ideally we'd have a progress widget here that showed up based
// on actual time elapsed -- so it could appear before the first
// batch returns, if that takes a while -- and that then stuck
// around continuously until the task ends. For now we use a
// series of [SnackBar]s, which may feel a bit janky.
// There is complexity in tracking the status of each [SnackBar],
// due to having no way to determine which is currently active,
// or if there is an active one at all. Resetting the [SnackBar] here
// results in the same message popping in and out and the user experience
// is better for now if we allow them to run their timer through
// and clear the backlog later.
scaffoldMessenger.showSnackBar(SnackBar(behavior: SnackBarBehavior.floating,
content: Text(zulipLocalizations.markAsReadInProgress)));
}
}

Future<void> _legacyMarkNarrowAsRead(BuildContext context, Narrow narrow) async {
final store = PerAccountStoreWidget.of(context);
final connection = store.connection;
switch (narrow) {
case AllMessagesNarrow():
await markAllAsRead(connection);
case StreamNarrow(:final streamId):
await markStreamAsRead(connection, streamId: streamId);
case TopicNarrow(:final streamId, :final topic):
await markTopicAsRead(connection, streamId: streamId, topicName: topic);
case DmNarrow():
final unreadDms = store.unreads.dms[narrow];
// Silently ignore this race-condition as the outcome
// (no unreads in this narrow) was the desired end-state
// of pushing the button.
if (unreadDms == null) return;
await updateMessageFlags(connection,
messages: unreadDms,
op: UpdateMessageFlagsOp.add,
flag: MessageFlag.read);
}
}
Loading