Add channel message filter for spam and repeated messages

Client-side filter for channel messages, with no model download:
- User rules on message text and/or sender name (contains, whole word,
  exact), normalised for case, accents, zero-width and look-alike letters.
- Automatic checks: repeated characters, same-sender repeats within 10
  minutes, and the same sentence (>= 6 words) from 3+ senders within 30
  minutes. Windows use send times, so synced history is not a flood.
- On-device n-gram classifier trained by Mark as spam / Not spam taps.

Filtered messages are kept, never notify or count as unread, are not
auto-translated or used for channel previews, and are concealed in reply
quotes. They show as a calm, collapsible placeholder that animates open
and closed, or can be hidden completely. Includes a Filtered messages
list, per-channel toggle, settings screen, translations for all locales
and documentation.
This commit is contained in:
zjs81 committed 2026-11-05 23:35:27 -07:00
1 parent 5ef2c2cd7d
commit 1332c35884
75 files changed
+12527 -254

No files matched your search

+511 -39
View File
@@ -28,11 +28,13 @@ import '../l10n/l10n.dart';
import '../models/channel.dart';
import '../models/channel_message.dart';
import '../models/image_codec_support.dart' show aeicRatePointForUi;
import '../models/message_filter.dart';
import '../services/app_settings_service.dart'
show AppSettingsService, ChannelNotificationMode;
import '../services/chat_text_scale_service.dart';
import '../services/image_chunk_transport.dart';
import '../services/image_codec_service.dart';
import '../services/message_filter/message_filter_service.dart';
import '../services/received_image_store.dart';
import '../services/translation_service.dart';
import '../utils/image_save.dart';
@@ -42,6 +44,8 @@ import '../widgets/received_image_message.dart';
import '../widgets/channel_notification_mode_sheet.dart';
import '../widgets/chat_day_separator.dart';
import '../widgets/empty_state.dart';
import '../widgets/filter_rule_dialog.dart';
import '../widgets/filtered_message_ghost.dart';
import '../widgets/chat_composer.dart';
import '../widgets/chat_send_pipeline.dart';
import '../widgets/chat_zoom_wrapper.dart';
@@ -61,6 +65,7 @@ import '../theme/mesh_theme.dart';
import '../widgets/future_timestamp_indicator.dart';
import '../widgets/mesh_ui.dart';
import 'app_settings_screen.dart';
import 'channel_chat_transcript_grouping.dart';
import 'channel_message_path_screen.dart';
import 'map_screen.dart';
import 'region_management_screen.dart';
@@ -117,6 +122,11 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
int _imageStoreVersion = 0;
ModalRoute<dynamic>? _route;
/// Filtered messages the user tapped open on this screen. Session-only by
/// design: leaving the chat hides them again.
final Set<String> _revealedFilteredIds = <String>{};
int _revealVersion = 0;
@override
void initState() {
super.initState();
@@ -144,9 +154,26 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
_channelSkipNextBottomSnap = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
// Estimate from visible list entries: filtered messages collapse
// into ghost rows (or vanish in hide mode), so raw message counts
// would undershoot.
var unreadEntries = unread;
var totalEntries = messages.length;
final layout = _transcriptLayout;
if (layout != null && layout.length > 0) {
final entryIndex = layout.ids.indexOf(
layout.entryIdFor(anchor!.messageId),
);
if (entryIndex >= 0) {
// Entries are newest first, so the anchor has entryIndex
// newer entries below it.
unreadEntries = entryIndex + 1;
totalEntries = layout.length;
}
}
_scrollController.jumpToEstimatedOffset(
unreadCount: unread,
totalMessages: messages.length,
unreadCount: unreadEntries,
totalMessages: totalEntries,
onJumped: () {
if (!mounted) return;
_scrollToMessage(anchor!.messageId, quiet: true);
@@ -179,7 +206,8 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
var n = 0;
ChannelMessage? oldest;
for (final m in messages.reversed) {
if (m.isOutgoing) continue;
// Filtered messages never count as unread (see the connector).
if (m.isOutgoing || m.isFiltered) continue;
n++;
oldest = m;
if (n >= unreadCount) break;
@@ -261,7 +289,10 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
}
Future<void> _scrollToMessage(String messageId, {bool quiet = false}) async {
final key = _messageKeys[messageId];
// A message hidden by the filter is represented by its ghost row (or the
// nearest visible row in hide mode).
final key =
_messageKeys[_transcriptLayout?.entryIdFor(messageId) ?? messageId];
if (key == null) {
// The auto unread-jump can resolve a frame after navigating away;
// a deactivated context can't host a snackbar.
@@ -447,11 +478,20 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
);
} else if (value == 'clearChat') {
_confirmClearChat();
} else if (value == 'messageFilter') {
_toggleChannelFiltering();
}
},
// Region lives here (and on a tap of the title) so the channel
// name keeps its room in the app bar.
itemBuilder: (context) => [
if (_messageFilter case final filter?
when filter.settings.enabled)
CheckedPopupMenuItem(
value: 'messageFilter',
checked: filter.isChannelFiltered(_messageFilterChannelId),
child: Text(context.l10n.messageFilter_channelToggle),
),
PopupMenuItem(
value: 'region',
child: Row(
@@ -508,7 +548,10 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
final messages = connector.getChannelMessages(
widget.channel,
);
final newest = messages.isEmpty ? null : messages.last;
// A filtered message must not trigger holiday effects.
final newest = connector.latestVisibleChannelMessage(
widget.channel,
);
_holidayWatcher.onNewest(
context,
id: newest?.messageId,
@@ -586,9 +629,10 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
} else {
messageKey = GlobalKey();
}
final dividerId = _unreadDividerMessageId;
final isUnreadAnchor =
_unreadDividerMessageId != null &&
row.id == _unreadDividerMessageId;
dividerId != null &&
row.id == layout.entryIdFor(dividerId);
return Container(
key: messageKey,
child: Builder(
@@ -598,16 +642,30 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
(service) => service.scale,
);
final message = row.message;
final bubble = message != null
? _buildMessageBubble(
message,
textScale,
urlImagesEnabled,
)
: _buildImageBubble(
row.image!,
textScale,
);
final ghost = row.ghost;
final Widget bubble;
if (ghost != null) {
bubble = _buildFilteredGhost(
ghost,
textScale,
expanded: row.ghostExpanded,
urlImagesEnabled: urlImagesEnabled,
);
} else if (message != null) {
bubble = _buildMessageBubble(
message,
textScale,
urlImagesEnabled,
showFilterBanner:
layout.filterActive &&
message.isFiltered,
);
} else {
bubble = _buildImageBubble(
row.image!,
textScale,
);
}
final startsDay =
index == rowCount - 1 ||
!isSameChatDay(
@@ -658,7 +716,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
var found = false;
for (final m in messages) {
if (m.messageId == message.messageId) found = true;
if (found && !m.isOutgoing) count++;
if (found && !m.isOutgoing && !m.isFiltered) count++;
}
connector.setChannelUnreadCount(widget.channel.index, count);
}
@@ -666,8 +724,9 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
Widget _buildMessageBubble(
ChannelMessage message,
double textScale,
bool urlImagesEnabled,
) {
bool urlImagesEnabled, {
bool showFilterBanner = false,
}) {
final settingsService = context.watch<AppSettingsService>();
final publicIpfsGateway = settingsService.settings.publicIpfsGateway;
final enableTracing = settingsService.settings.enableMessageTracing;
@@ -781,6 +840,18 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
),
if (gifId == null) const SizedBox(height: 2),
],
if (showFilterBanner)
FilteredMessageBanner(
reason: messageFilterReasonLabel(
context.l10n,
message.filterReason,
message.filterDetail,
),
color: textColor,
textScale: textScale,
onNotSpam: () => _markNotSpam(message),
onHide: () => _hideFilteredMessage(message),
),
if (message.replyToMessageId != null) ...[
_buildReplyPreview(message, textScale),
const SizedBox(height: 8),
@@ -1153,11 +1224,52 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
final connector = context.read<MeshCoreConnector>();
final isOwnNode = message.replyToSenderName == connector.selfName;
final colorScheme = Theme.of(context).colorScheme;
final contentPreview = _buildReplyContent(
message.replyToText ?? '',
textScale,
color: colorScheme.onSurface.withValues(alpha: 0.7),
);
final previewColor = colorScheme.onSurface.withValues(alpha: 0.7);
// The quoted text was copied when the reply arrived; if the quoted message
// is hidden by the filter, don't spell it out until it is revealed.
final quotedId = message.replyToMessageId;
final quoted = quotedId == null
? null
: connector
.getChannelMessages(widget.channel)
.where((m) => m.messageId == quotedId)
.lastOrNull;
final concealed =
quoted != null &&
isReplyPreviewConcealed(
quotedIsFiltered: quoted.isFiltered,
filterActive:
_messageFilter?.isChannelFiltered(_messageFilterChannelId) ??
false,
quotedRevealed: _revealedFilteredIds.contains(quoted.messageId),
);
final contentPreview = concealed
? Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.visibility_off_outlined,
size: 16 * textScale,
color: previewColor,
),
const SizedBox(width: 6),
Flexible(
child: Text(
context.l10n.messageFilter_ghostSingle,
style: TextStyle(
fontSize: 13 * textScale,
fontStyle: FontStyle.italic,
color: previewColor,
),
),
),
],
)
: _buildReplyContent(
message.replyToText ?? '',
textScale,
color: previewColor,
);
return GestureDetector(
onTap: () => _scrollToMessage(message.replyToMessageId!),
@@ -1701,9 +1813,32 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
store?.addListener(_onImageStoreChanged);
_imageStoreVersion++;
}
MessageFilterService? filter;
try {
filter = context.watch<MessageFilterService>();
} on ProviderNotFoundException {
filter = null;
}
final displayMode =
filter?.settings.displayMode ?? FilterDisplayMode.placeholder;
final filterActive =
filter?.isChannelFiltered(_messageFilterChannelId) ?? true;
// Spam / Not spam replace a message in place (same list, length and
// ends), so the memo also keys on which messages are filtered.
final filterVersion = Object.hash(
displayMode,
filterActive,
_revealVersion,
_filteredMessagesSignature(messages),
);
final cached = _transcriptLayout;
if (cached != null &&
cached.matches(messages, _imageStoreVersion, widget.channel.index)) {
cached.matches(
messages,
_imageStoreVersion,
widget.channel.index,
filterVersion,
)) {
return cached;
}
final images = store == null
@@ -1714,6 +1849,10 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
images: images,
imageVersion: _imageStoreVersion,
channelIndex: widget.channel.index,
filterVersion: filterVersion,
displayMode: displayMode,
filterActive: filterActive,
revealedIds: _revealedFilteredIds,
);
// Prune stale keys (deleted/cleared messages) to avoid unbounded growth.
final liveIds = layout.ids.toSet();
@@ -1724,6 +1863,19 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
void _onImageStoreChanged() => _imageStoreVersion++;
/// Cheap fingerprint of which messages are filtered, so the layout memo
/// notices a message being marked spam or not spam in place.
static int _filteredMessagesSignature(List<ChannelMessage> messages) {
var hash = 0;
var count = 0;
for (final m in messages) {
if (!m.isFiltered) continue;
count++;
hash = Object.hash(hash, m.messageId);
}
return Object.hash(count, hash);
}
/// Bubble for one AEIC image, following the GIF-message precedent: minimal
/// chrome, the renderer owns every state (receiving / decoding / failed) and
/// the mandatory AI-reconstruction label.
@@ -2286,6 +2438,14 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
isOutgoing: message.isOutgoing,
) &&
(message.translatedText?.trim().isEmpty ?? true);
// Filter actions apply to incoming messages in a channel the filter
// covers; structured payloads (GIFs, markers) are never filtered.
final filter = _messageFilter;
final showFilterActions =
!message.isOutgoing &&
filter != null &&
filter.isChannelFiltered(_messageFilterChannelId) &&
(message.isFiltered || !_isStructuredPayload(message.text));
showMeshSheet(
context,
@@ -2377,6 +2537,44 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
_markAsUnread(message);
},
),
if (showFilterActions) ...[
const Divider(height: 1),
if (message.isFiltered)
ListTile(
leading: const Icon(Icons.visibility_outlined),
title: Text(context.l10n.messageFilter_notSpam),
onTap: () {
Navigator.pop(sheetContext);
_markNotSpam(message);
},
)
else
ListTile(
leading: const Icon(Icons.visibility_off_outlined),
title: Text(context.l10n.messageFilter_markSpam),
onTap: () {
Navigator.pop(sheetContext);
_markSpam(message);
},
),
if (message.senderName.trim().isNotEmpty)
ListTile(
leading: const Icon(Icons.person_off_outlined),
title: Text(context.l10n.messageFilter_filterSender),
onTap: () {
Navigator.pop(sheetContext);
_filterSender(message.senderName);
},
),
ListTile(
leading: const Icon(Icons.filter_alt_outlined),
title: Text(context.l10n.messageFilter_filterLikeThis),
onTap: () {
Navigator.pop(sheetContext);
_filterMessagesLike(message);
},
),
],
const Divider(height: 1),
ListTile(
leading: Icon(
@@ -2400,6 +2598,172 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
);
}
// ---- message filter -------------------------------------------------------
/// The message filter, or null when it is not registered (screen tests).
MessageFilterService? get _messageFilter {
try {
return context.read<MessageFilterService>();
} on ProviderNotFoundException {
return null;
}
}
String get _messageFilterChannelId =>
MeshCoreConnector.messageFilterChannelId(widget.channel);
/// GIFs and other structured payloads (same test as the connector's
/// outbound check), which the filter never looks at.
static bool _isStructuredPayload(String text) {
final trimmed = text.trimLeft();
return trimmed.startsWith('g:') || trimmed.startsWith('m:');
}
void _setRevealed(Iterable<String> ids, {required bool revealed}) {
setState(() {
if (revealed) {
_revealedFilteredIds.addAll(ids);
} else {
_revealedFilteredIds.removeAll(ids);
}
_revealVersion++;
});
}
/// "Hide" on a revealed message collapses its whole run back into one
/// ghost row, not just that message.
void _hideFilteredMessage(ChannelMessage message) {
final layout = _transcriptLayout;
final messages = context.read<MeshCoreConnector>().getChannelMessages(
widget.channel,
);
final ids = layout == null
? [message.messageId]
: layout.revealedRunIdsFor(message.messageId, messages);
_setRevealed(ids, revealed: false);
}
Future<void> _markSpam(ChannelMessage message) async {
final connector = context.read<MeshCoreConnector>();
// Collapse it straight away, even if it had been revealed before.
_setRevealed([message.messageId], revealed: false);
await connector.markChannelMessageSpam(widget.channel, message);
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.messageFilter_markedSpam),
);
}
Future<void> _markNotSpam(ChannelMessage message) async {
final connector = context.read<MeshCoreConnector>();
_setRevealed([message.messageId], revealed: false);
await connector.markChannelMessageNotSpam(widget.channel, message);
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.messageFilter_markedNotSpam),
);
}
Future<void> _filterSender(String senderName) async {
final filter = _messageFilter;
if (filter == null) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(dialogContext.l10n.messageFilter_filterSender),
content: Text(
dialogContext.l10n.messageFilter_filterSenderConfirm(senderName),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(dialogContext.l10n.common_cancel),
),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: Text(dialogContext.l10n.messageFilter_filterSender),
),
],
),
);
if (confirmed != true) return;
await filter.addRule(
FilterRule(
id: MessageFilterService.newRuleId(),
pattern: senderName,
field: FilterRuleField.sender,
match: FilterRuleMatch.exact,
),
);
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.messageFilter_ruleSaved),
);
}
Future<void> _filterMessagesLike(ChannelMessage message) async {
final filter = _messageFilter;
if (filter == null) return;
final rule = await showFilterRuleDialog(
context,
initialPattern: message.text,
initialField: FilterRuleField.text,
);
if (rule == null) return;
await filter.addRule(rule);
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.messageFilter_ruleSaved),
);
}
Future<void> _toggleChannelFiltering() async {
final filter = _messageFilter;
if (filter == null) return;
final channelId = _messageFilterChannelId;
await filter.setChannelExcluded(
channelId,
filter.isChannelFiltered(channelId),
);
}
/// One entry for a run of hidden messages (newest first): a ghost header
/// that animates the run's messages open and closed underneath it. Opening
/// lasts for this visit to the chat.
Widget _buildFilteredGhost(
List<ChannelMessage> run,
double textScale, {
required bool expanded,
required bool urlImagesEnabled,
}) {
final newest = run.first;
return FilteredMessageRun(
count: run.length,
expanded: expanded,
buildMessages: (context) => [
for (final message in run.reversed)
_buildMessageBubble(
message,
textScale,
urlImagesEnabled,
showFilterBanner: true,
),
],
reason: messageFilterReasonLabel(
context.l10n,
newest.filterReason,
newest.filterDetail,
),
textScale: textScale,
onToggle: () =>
_setRevealed([for (final m in run) m.messageId], revealed: !expanded),
);
}
void _showEmojiPicker(ChannelMessage message) {
showMeshSheet(
context,
@@ -2822,7 +3186,7 @@ class _SwipeReplyBubbleState extends State<_SwipeReplyBubble> {
/// One row of the channel transcript.
///
/// Exactly one of [message] / [image] is non-null. Images cannot be
/// Exactly one of [message] / [image] / [ghost] is non-null. Images cannot be
/// `ChannelMessage`s: they arrive as GRP_DATA chunks with no text frame behind
/// them, are keyed on (sender prefix, img id, channel) rather than a message id,
/// and are persisted by [ReceivedImageStore] instead of the channel message
@@ -2832,15 +3196,34 @@ class _ChannelChatRow {
final ChannelMessage? message;
final ReceivedImageEntry? image;
const _ChannelChatRow({this.message, this.image});
/// A run of consecutive messages hidden by the message filter, newest
/// first, shown as one ghost row.
final List<ChannelMessage>? ghost;
/// [ghost] is a revealed run: its messages are shown under the header.
final bool ghostExpanded;
const _ChannelChatRow({
this.message,
this.image,
this.ghost,
this.ghostExpanded = false,
});
/// Local arrival time, used for ordering and day separators so a sender
/// clock running ahead cannot pin a row to the bottom (#584).
DateTime get receivedAt => message?.receivedAt ?? image!.firstSeen;
/// clock running ahead cannot pin a row to the bottom (#584). A ghost run
/// never spans two days, so its newest member stands for it.
DateTime get receivedAt =>
message?.receivedAt ?? ghost?.first.receivedAt ?? image!.firstSeen;
/// Stable identity for the scroll-to-message [GlobalKey] map. The `aeic:`
/// prefix keeps a stream id from ever colliding with a message id.
String get id => message?.messageId ?? 'aeic:${image!.streamId}';
/// and `ghost:` prefixes keep these from ever colliding with a message id.
String get id {
final run = ghost;
// Same id open or closed, so the run keeps its State and can animate.
if (run != null) return 'ghost:${run.first.messageId}';
return message?.messageId ?? 'aeic:${image!.streamId}';
}
}
/// Memoised ordering of a channel transcript, newest first.
@@ -2848,6 +3231,10 @@ class _ChannelChatRow {
/// Rows hold positions, not message objects: the connector replaces messages
/// in place (status, repeats, reactions) without changing their order or id,
/// so [rowAt] always reads the current object from the live list.
///
/// Messages hidden by the message filter are grouped by [groupFilteredRows]:
/// each visible entry is one row, or one ghost standing in for a run of
/// hidden messages (none at all in hide mode).
class _TranscriptLayout {
final List<ChannelMessage> _source;
final int _sourceLength;
@@ -2855,14 +3242,26 @@ class _TranscriptLayout {
final String? _lastId;
final int _imageVersion;
final int _channelIndex;
final int _filterVersion;
/// Newest first. `>= 0` is a message index; `< 0` is image `-(i + 1)`.
final List<int> _order;
final List<ReceivedImageEntry> _images;
/// Row ids, aligned with [_order].
/// Visible entries, newest first; their rows index into [_order].
final List<TranscriptEntry> _entries;
/// Whether filtered messages are being hidden in this channel. When false
/// they render as ordinary bubbles, without the filter banner.
final bool filterActive;
/// Entry ids, aligned with the visible entries.
final List<String> ids;
/// Row id (message id) -> id of the entry that shows it, for rows that are
/// not entries themselves (inside a ghost, or dropped in hide mode).
final Map<String, String> _entryIdByRowId;
/// Two messages can collide on messageId (same ms + name/text hash). Only
/// the first occurrence owns the shared GlobalKey used for
/// scroll-to-message; duplicates get a local key so no two widgets share
@@ -2876,9 +3275,13 @@ class _TranscriptLayout {
this._lastId,
this._imageVersion,
this._channelIndex,
this._filterVersion,
this._order,
this._images,
this._entries,
this.filterActive,
this.ids,
this._entryIdByRowId,
this.keyedIndices,
);
@@ -2887,6 +3290,10 @@ class _TranscriptLayout {
required List<ReceivedImageEntry> images,
required int imageVersion,
required int channelIndex,
required int filterVersion,
required FilterDisplayMode displayMode,
required bool filterActive,
required Set<String> revealedIds,
}) {
DateTime timeOf(int code) =>
code >= 0 ? messages[code].receivedAt : images[-code - 1].firstSeen;
@@ -2901,12 +3308,38 @@ class _TranscriptLayout {
// the reversed ListView.
mergeSort<int>(order, compare: (a, b) => timeOf(a).compareTo(timeOf(b)));
final reversed = order.reversed.toList(growable: false);
final ids = <String>[
final rowInfos = <TranscriptRowInfo>[
for (final code in reversed)
code >= 0
? messages[code].messageId
: 'aeic:${images[-code - 1].streamId}',
? TranscriptRowInfo(
id: messages[code].messageId,
receivedAt: messages[code].receivedAt,
isFiltered: messages[code].isFiltered,
)
: TranscriptRowInfo(
id: 'aeic:${images[-code - 1].streamId}',
receivedAt: images[-code - 1].firstSeen,
isImage: true,
),
];
final entries = groupFilteredRows(
rowInfos,
mode: displayMode,
revealedIds: revealedIds,
filterActive: filterActive,
sameDay: isSameChatDay,
);
final ids = <String>[for (final entry in entries) entry.id];
final entryIdByRowId = <String, String>{};
final entryByRow = entryIndexByRow(entries, rowInfos.length);
for (var row = 0; row < rowInfos.length; row++) {
final entry = entryByRow[row];
if (entry == null) continue;
final rowId = rowInfos[row].id;
final entryId = ids[entry];
// First occurrence wins, matching the GlobalKey ownership below.
if (rowId != entryId) entryIdByRowId.putIfAbsent(rowId, () => entryId);
}
final seen = <String>{};
final keyed = <int>{};
for (var i = 0; i < ids.length; i++) {
@@ -2919,26 +3352,65 @@ class _TranscriptLayout {
messages.isEmpty ? null : messages.last.messageId,
imageVersion,
channelIndex,
filterVersion,
reversed,
images,
entries,
filterActive,
ids,
entryIdByRowId,
keyed,
);
}
int get length => _order.length;
int get length => _entries.length;
bool matches(List<ChannelMessage> messages, int imageVersion, int channel) {
bool matches(
List<ChannelMessage> messages,
int imageVersion,
int channel,
int filterVersion,
) {
return identical(messages, _source) &&
messages.length == _sourceLength &&
imageVersion == _imageVersion &&
channel == _channelIndex &&
filterVersion == _filterVersion &&
(messages.isEmpty ? null : messages.first.messageId) == _firstId &&
(messages.isEmpty ? null : messages.last.messageId) == _lastId;
}
/// Id of the visible entry that shows the row with [rowId]: the row itself,
/// its ghost, or (hide mode) the nearest visible row.
String entryIdFor(String rowId) => _entryIdByRowId[rowId] ?? rowId;
/// Ids of every message in the revealed run containing [messageId], so
/// "Hide" on one of them collapses the whole run; just [messageId] when it
/// is not part of a revealed run.
List<String> revealedRunIdsFor(
String messageId,
List<ChannelMessage> messages,
) {
for (final entry in _entries) {
if (!entry.expanded) continue;
final ids = [
for (final row in entry.rows)
if (_order[row] >= 0) messages[_order[row]].messageId,
];
if (ids.contains(messageId)) return ids;
}
return [messageId];
}
_ChannelChatRow rowAt(int index, List<ChannelMessage> messages) {
final code = _order[index];
final entry = _entries[index];
if (entry.isGhost) {
return _ChannelChatRow(
ghost: [for (final row in entry.rows) messages[_order[row]]],
ghostExpanded: entry.expanded,
);
}
final code = _order[entry.row];
return code >= 0
? _ChannelChatRow(message: messages[code])
: _ChannelChatRow(image: _images[-code - 1]);
@@ -0,0 +1,198 @@
/// Pure grouping of a channel transcript into visible entries, collapsing
/// messages hidden by the message filter.
///
/// Kept free of widgets and connector state so the rules (runs, hide mode,
/// revealed messages, images, anchors) can be unit tested directly.
library;
import 'package:flutter/foundation.dart' show immutable, listEquals;
import '../models/message_filter.dart';
/// What the grouping needs to know about one transcript row.
@immutable
class TranscriptRowInfo {
/// Row identity: a message id, or an `aeic:` image stream id.
final String id;
/// The message filter tagged this row.
final bool isFiltered;
/// Image rows are never filtered, whatever [isFiltered] says.
final bool isImage;
/// Local arrival time; a ghost run never spans two chat days when the
/// grouping is given a `sameDay` test.
final DateTime receivedAt;
const TranscriptRowInfo({
required this.id,
required this.receivedAt,
this.isFiltered = false,
this.isImage = false,
});
}
/// One visible entry of the transcript: a single row, or a ghost standing in
/// for a run of consecutive hidden rows. A revealed run stays ONE entry (with
/// [expanded] set) so its id never changes and the chat can animate it open
/// and closed in place.
@immutable
class TranscriptEntry {
/// Indices into the row list given to [groupFilteredRows], in the same
/// (newest-first) order. Exactly one for a plain row.
final List<int> rows;
/// Whether this entry is a run of filtered messages.
final bool isGhost;
/// For a ghost: the run is revealed (its messages are shown under the
/// "tap to hide" header).
final bool expanded;
/// Stable identity: the row id, or `ghost:<newest member id>` for a run in
/// either state.
final String id;
const TranscriptEntry._(this.rows, this.isGhost, this.id, this.expanded);
factory TranscriptEntry.row(int row, String id) =>
TranscriptEntry._(List<int>.unmodifiable([row]), false, id, false);
factory TranscriptEntry.ghost(
List<int> rows,
String newestId, {
bool expanded = false,
}) => TranscriptEntry._(
List<int>.unmodifiable(rows),
true,
'ghost:$newestId',
expanded,
);
/// The single row of a non-ghost entry.
int get row => rows.first;
@override
bool operator ==(Object other) =>
other is TranscriptEntry &&
other.isGhost == isGhost &&
other.expanded == expanded &&
other.id == id &&
listEquals(other.rows, rows);
@override
int get hashCode => Object.hash(isGhost, expanded, id, Object.hashAll(rows));
@override
String toString() => !isGhost
? 'TranscriptEntry.row($row)'
: 'TranscriptEntry.ghost($rows${expanded ? ', expanded' : ''})';
}
/// Groups [rows] (newest first, as displayed by the reversed chat list) into
/// visible entries.
///
/// A row is filtered-out when [filterActive] is true and it is a filtered
/// message (not an image). With [FilterDisplayMode.hide] such rows are dropped
/// unless their id is in [revealedIds]. With [FilterDisplayMode.placeholder]
/// consecutive filtered rows form runs, split wherever the revealed state
/// changes (and, when [sameDay] is given, where the chat day changes):
/// each run becomes one [TranscriptEntry.ghost], `expanded` when revealed.
/// Its id depends only on the newest member, so revealing or hiding a run
/// keeps the same entry (and lets the UI animate between the two states).
List<TranscriptEntry> groupFilteredRows(
List<TranscriptRowInfo> rows, {
required FilterDisplayMode mode,
Set<String> revealedIds = const <String>{},
bool filterActive = true,
bool Function(DateTime a, DateTime b)? sameDay,
}) {
bool isFilteredRow(TranscriptRowInfo row) =>
filterActive && row.isFiltered && !row.isImage;
final entries = <TranscriptEntry>[];
var run = <int>[];
var runRevealed = false;
void flushRun() {
if (run.isEmpty) return;
entries.add(
TranscriptEntry.ghost(run, rows[run.first].id, expanded: runRevealed),
);
run = <int>[];
}
for (var i = 0; i < rows.length; i++) {
final row = rows[i];
if (!isFilteredRow(row)) {
flushRun();
entries.add(TranscriptEntry.row(i, row.id));
continue;
}
final revealed = revealedIds.contains(row.id);
if (mode == FilterDisplayMode.hide) {
if (revealed) entries.add(TranscriptEntry.row(i, row.id));
continue;
}
if (run.isNotEmpty &&
(revealed != runRevealed ||
(sameDay != null &&
!sameDay(rows[run.last].receivedAt, row.receivedAt)))) {
flushRun();
}
if (run.isEmpty) runRevealed = revealed;
run.add(i);
}
flushRun();
return entries;
}
/// Maps every row index to the index of the entry that represents it on
/// screen, for scroll targets and the unread divider.
///
/// A row inside a ghost (collapsed or expanded) maps to that ghost. A row
/// dropped in hide mode maps
/// to the nearest newer visible entry (the one shown just below it), or, when
/// nothing newer is visible, the nearest older one. Rows map to nothing only
/// when [entries] is empty.
Map<int, int> entryIndexByRow(List<TranscriptEntry> entries, int rowCount) {
final result = <int, int>{};
for (var e = 0; e < entries.length; e++) {
for (final row in entries[e].rows) {
result[row] = e;
}
}
if (entries.isEmpty || result.length == rowCount) return result;
// Rows are newest first, so the newer neighbour has the smaller index.
int? newerEntry;
for (var row = 0; row < rowCount; row++) {
final own = result[row];
if (own != null) {
newerEntry = own;
} else if (newerEntry != null) {
result[row] = newerEntry;
}
}
int? olderEntry;
for (var row = rowCount - 1; row >= 0; row--) {
final own = result[row];
if (own != null) {
olderEntry = own;
} else if (olderEntry != null) {
result[row] = olderEntry;
}
}
return result;
}
/// Whether a reply's quoted preview must be concealed: the quoted message
/// ([quotedIsFiltered]) was hidden by the message filter, filtering is on for
/// the channel ([filterActive]) and the user has not revealed it
/// ([quotedRevealed]). Replies copy the quoted text when they arrive, so
/// without this a reply would show hidden spam in an ordinary bubble.
bool isReplyPreviewConcealed({
required bool quotedIsFiltered,
required bool filterActive,
required bool quotedRevealed,
}) => filterActive && quotedIsFiltered && !quotedRevealed;
+17 -11
View File
@@ -12,6 +12,7 @@ import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart'
show AppSettingsService, ChannelNotificationMode;
import '../services/message_filter/message_filter_service.dart';
import '../services/ui_view_state_service.dart';
import '../models/channel.dart';
import '../models/community.dart';
@@ -102,6 +103,12 @@ class _ChannelsScreenState extends State<ChannelsScreen>
Widget build(BuildContext context) {
final connector = context.watch<MeshCoreConnector>();
final viewState = context.watch<UiViewStateService>();
// Previews and "latest" sorting depend on per-channel filter settings.
try {
context.watch<MessageFilterService>();
} on ProviderNotFoundException {
// No message filter in this tree (tests); previews ignore it.
}
// Auto-navigate back to scanner if disconnected
if (!checkConnectionAndNavigate(connector)) {
@@ -426,9 +433,9 @@ class _ChannelsScreenState extends State<ChannelsScreen>
iconColor = MeshPalette.blue;
}
// Last message preview
final messages = connector.getChannelMessages(channel);
final lastMessage = messages.isNotEmpty ? messages.last : null;
// Last message preview. Messages hidden by the message filter never
// become the preview.
final lastMessage = connector.latestVisibleChannelMessage(channel);
final lastMessageText = lastMessage?.text ?? '';
final lastPreview =
lastMessageText.isNotEmpty &&
@@ -774,14 +781,13 @@ class _ChannelsScreenState extends State<ChannelsScreen>
break;
case ChannelSortOption.latestMessages:
filtered.sort((a, b) {
final aMessages = connector.getChannelMessages(a);
final bMessages = connector.getChannelMessages(b);
final aLast = aMessages.isEmpty
? DateTime(1970)
: aMessages.last.timestamp;
final bLast = bMessages.isEmpty
? DateTime(1970)
: bMessages.last.timestamp;
// Filtered messages don't bump a channel, matching the preview.
final aLast =
connector.latestVisibleChannelMessage(a)?.timestamp ??
DateTime(1970);
final bLast =
connector.latestVisibleChannelMessage(b)?.timestamp ??
DateTime(1970);
final timeCompare = bLast.compareTo(aLast);
if (timeCompare != 0) return timeCompare;
return compareByName(a, b);
+256
View File
@@ -0,0 +1,256 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/channel.dart';
import '../models/channel_message.dart';
import '../models/message_filter.dart';
import '../widgets/filtered_message_ghost.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../widgets/empty_state.dart';
import '../widgets/mesh_ui.dart';
/// Recent filtered channel messages across all channels, newest first.
///
/// Message text and sender stay hidden until the row is tapped, so the list
/// can be opened without being shown the spam itself. "Not spam" puts a
/// message back in its channel and teaches the filter.
class FilteredMessagesScreen extends StatefulWidget {
const FilteredMessagesScreen({super.key});
@override
State<FilteredMessagesScreen> createState() => _FilteredMessagesScreenState();
}
/// Identity of a row in the Filtered messages list (widget key and reveal
/// state). Message ids do not include the channel and can collide across
/// channels, so they are scoped by the channel's filter id.
String filteredMessageRowId(Channel channel, ChannelMessage message) =>
'${MeshCoreConnector.messageFilterChannelId(channel)}|${message.messageId}';
class _FilteredMessagesScreenState extends State<FilteredMessagesScreen> {
final Set<String> _revealed = <String>{};
static String _rowId(Channel channel, ChannelMessage message) =>
filteredMessageRowId(channel, message);
void _toggle(String rowId) {
setState(() {
if (!_revealed.remove(rowId)) _revealed.add(rowId);
});
}
Future<void> _markNotSpam(Channel channel, ChannelMessage message) async {
final connector = context.read<MeshCoreConnector>();
final text = context.l10n.messageFilter_markedNotSpam;
await connector.markChannelMessageNotSpam(channel, message);
if (!mounted) return;
_revealed.remove(_rowId(channel, message));
showDismissibleSnackBar(
context,
content: Text(text),
duration: const Duration(seconds: 2),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final connector = context.watch<MeshCoreConnector>();
final entries = connector.recentFilteredChannelMessages();
return Scaffold(
appBar: AppBar(
title: AdaptiveAppBarTitle(l10n.messageFilter_displayTitle),
centerTitle: true,
),
body: SafeArea(
top: false,
child: entries.isEmpty
? EmptyState(
icon: Icons.filter_alt_outlined,
title: l10n.messageFilter_filteredMessagesEmpty,
)
: ListView.builder(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 24),
itemCount: entries.length,
itemBuilder: (context, index) {
final (channel, message) = entries[index];
final id = _rowId(channel, message);
return _FilteredMessageCard(
key: ValueKey('filtered_$id'),
channel: channel,
message: message,
revealed: _revealed.contains(id),
onToggle: () => _toggle(id),
onNotSpam: () => _markNotSpam(channel, message),
);
},
),
),
);
}
}
class _FilteredMessageCard extends StatelessWidget {
final Channel channel;
final ChannelMessage message;
final bool revealed;
final VoidCallback onToggle;
final VoidCallback onNotSpam;
const _FilteredMessageCard({
super.key,
required this.channel,
required this.message,
required this.revealed,
required this.onToggle,
required this.onNotSpam,
});
String _relativeTime(BuildContext context, DateTime t) {
final diff = DateTime.now().difference(t);
final l10n = context.l10n;
if (diff.inMinutes < 1) return l10n.channels_timeNow;
if (diff.inMinutes < 60) return l10n.channels_timeMinutes(diff.inMinutes);
if (diff.inHours < 24) return l10n.channels_timeHours(diff.inHours);
return l10n.channels_timeDays(diff.inDays);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final channelLabel = channel.name.isEmpty
? l10n.channels_channelIndex(channel.index)
: channel.name;
final secondary = theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
);
return MeshCard(
onTap: onToggle,
padding: const EdgeInsets.fromLTRB(16, 12, 8, 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: Row(
children: [
Expanded(
child: Text(
channelLabel,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.w600,
),
),
),
const SizedBox(width: 8),
Text(
_relativeTime(context, message.receivedAt),
style: secondary,
),
],
),
),
const SizedBox(height: 4),
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: Text(
messageFilterReasonText(context, message, revealed: revealed),
style: secondary,
),
),
const SizedBox(height: 8),
AnimatedSize(
duration: const Duration(milliseconds: 150),
alignment: AlignmentDirectional.topStart,
child: Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: revealed
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
message.senderName,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
SelectableText(
message.text,
style: theme.textTheme.bodyLarge,
),
],
)
: Row(
children: [
Icon(
Icons.visibility_outlined,
size: 20,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 8),
Expanded(
child: Text(
l10n.messageFilter_ghostSingle,
style: secondary,
),
),
],
),
),
),
Align(
alignment: AlignmentDirectional.centerEnd,
child: TextButton.icon(
style: TextButton.styleFrom(minimumSize: const Size(0, 48)),
onPressed: onNotSpam,
icon: const Icon(Icons.check_circle_outline, size: 22),
label: Text(l10n.messageFilter_notSpam),
),
),
],
),
);
}
}
/// The "Filtered: …" line explaining why [message] was hidden.
///
/// Until the card is [revealed] the rule pattern is shortened like the chat
/// placeholder's (a rule made with "Filter messages like this…" can be the
/// whole spam message); once the message itself is shown, the full pattern is.
String messageFilterReasonText(
BuildContext context,
ChannelMessage message, {
bool revealed = false,
}) {
final l10n = context.l10n;
if (!revealed) {
return messageFilterReasonLabel(
l10n,
message.filterReason,
message.filterDetail,
);
}
final detail = message.filterDetail ?? '';
return switch (filterReasonFromJson(message.filterReason)) {
FilterReason.senderRule => l10n.messageFilter_reasonSenderRule(detail),
FilterReason.textRule => l10n.messageFilter_reasonTextRule(detail),
FilterReason.repeatedCharacters =>
l10n.messageFilter_reasonRepeatedCharacters,
FilterReason.duplicate => l10n.messageFilter_reasonDuplicate,
FilterReason.crossSenderDuplicate =>
l10n.messageFilter_reasonCrossSenderDuplicate,
FilterReason.learned => l10n.messageFilter_reasonLearned,
FilterReason.manual || null => l10n.messageFilter_reasonManual,
};
}
@@ -0,0 +1,404 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/message_filter.dart';
import '../services/message_filter/message_filter_service.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../widgets/filter_rule_dialog.dart';
import '../widgets/mesh_nav_tile.dart';
import '../widgets/mesh_ui.dart';
import 'filtered_messages_screen.dart';
/// Settings → Message filter: master switch, how filtered messages are shown,
/// the user's own rules and the automatic checks.
class MessageFilterSettingsScreen extends StatelessWidget {
const MessageFilterSettingsScreen({super.key});
static const _tilePadding = EdgeInsets.symmetric(horizontal: 16, vertical: 4);
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final service = context.watch<MessageFilterService>();
final settings = service.settings;
return Scaffold(
appBar: AppBar(
title: AdaptiveAppBarTitle(l10n.messageFilter_title),
centerTitle: true,
),
body: SafeArea(
top: false,
child: ListView(
padding: const EdgeInsets.fromLTRB(0, 8, 0, 24),
children: [
MeshCard(
padding: EdgeInsets.zero,
child: SwitchListTile(
key: const ValueKey('messageFilter_enabledSwitch'),
contentPadding: _tilePadding,
secondary: const Icon(Icons.filter_alt_outlined, size: 24),
title: Text(l10n.messageFilter_enabled),
subtitle: Text(l10n.messageFilter_enabledSubtitle),
value: settings.enabled,
onChanged: (value) => service.updateSettings(
service.settings.copyWith(enabled: value),
),
),
),
SectionHeader(l10n.messageFilter_displayTitle),
MeshCard(
padding: EdgeInsets.zero,
child: Column(
children: [
_DisplayModeOptions(service: service),
const Divider(height: 1, indent: 16),
const _FilteredMessagesTile(),
],
),
),
SectionHeader(l10n.messageFilter_rulesSection),
MeshCard(
padding: EdgeInsets.zero,
child: _RulesList(service: service),
),
SectionHeader(l10n.messageFilter_automaticSection),
MeshCard(
padding: EdgeInsets.zero,
child: _AutomaticOptions(service: service),
),
],
),
),
);
}
}
class _DisplayModeOptions extends StatelessWidget {
final MessageFilterService service;
const _DisplayModeOptions({required this.service});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final settings = service.settings;
return RadioGroup<FilterDisplayMode>(
groupValue: settings.displayMode,
onChanged: (mode) {
if (mode == null || mode == settings.displayMode) return;
service.updateSettings(service.settings.copyWith(displayMode: mode));
},
child: Column(
children: [
RadioListTile<FilterDisplayMode>(
key: const ValueKey('messageFilter_displayPlaceholder'),
contentPadding: MessageFilterSettingsScreen._tilePadding,
value: FilterDisplayMode.placeholder,
title: Text(l10n.messageFilter_displayPlaceholder),
),
RadioListTile<FilterDisplayMode>(
key: const ValueKey('messageFilter_displayHide'),
contentPadding: MessageFilterSettingsScreen._tilePadding,
value: FilterDisplayMode.hide,
title: Text(l10n.messageFilter_displayHide),
subtitle: Text(l10n.messageFilter_displayHideHelp),
),
],
),
);
}
}
/// "Filtered messages (N)" row. Rebuilds only when the count changes.
class _FilteredMessagesTile extends StatelessWidget {
const _FilteredMessagesTile();
@override
Widget build(BuildContext context) {
final count = context.select<MeshCoreConnector, int>(
(c) => c.recentFilteredChannelMessages().length,
);
return MeshNavTile(
icon: Icons.visibility_off_outlined,
title: context.l10n.messageFilter_filteredMessages(count),
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const FilteredMessagesScreen()),
),
);
}
}
class _RulesList extends StatelessWidget {
final MessageFilterService service;
const _RulesList({required this.service});
Future<void> _addRule(BuildContext context) async {
final rule = await showFilterRuleDialog(context);
if (rule == null) return;
await service.addRule(rule);
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.messageFilter_ruleSaved),
duration: const Duration(seconds: 2),
);
}
Future<void> _editRule(BuildContext context, FilterRule existing) async {
final rule = await showFilterRuleDialog(context, existing: existing);
if (rule == null) return;
await service.updateRule(rule);
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.messageFilter_ruleSaved),
duration: const Duration(seconds: 2),
);
}
Future<void> _deleteRule(BuildContext context, FilterRule rule) async {
final l10n = context.l10n;
// Capture before the await: the row (and its context) goes away with the
// rule, but the undo action must still be able to put it back.
final messenger = ScaffoldMessenger.maybeOf(context);
final index = service.rules.indexWhere((r) => r.id == rule.id);
await service.removeRule(rule.id);
if (messenger == null) return;
messenger.clearSnackBars();
messenger.showSnackBar(
SnackBar(
content: Text(l10n.messageFilter_ruleDeleted),
duration: const Duration(seconds: 6),
action: SnackBarAction(
label: l10n.common_undo,
onPressed: () =>
service.addRule(rule, index: index < 0 ? null : index),
),
),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final rules = service.rules;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (rules.isEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
child: Text(
l10n.messageFilter_rulesEmpty,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
for (var i = 0; i < rules.length; i++) ...[
if (i > 0) const Divider(height: 1, indent: 16),
_RuleTile(
key: ValueKey('messageFilter_rule_${rules[i].id}'),
rule: rules[i],
onTap: () => _editRule(context, rules[i]),
onEnabledChanged: (value) =>
service.updateRule(rules[i].copyWith(enabled: value)),
onDelete: () => _deleteRule(context, rules[i]),
),
],
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: FilledButton.tonalIcon(
key: const ValueKey('messageFilter_addRuleButton'),
style: FilledButton.styleFrom(
minimumSize: const Size(0, 48),
textStyle: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
onPressed: () => _addRule(context),
icon: const Icon(Icons.add, size: 24),
label: Text(l10n.messageFilter_addRule),
),
),
),
],
);
}
}
class _RuleTile extends StatelessWidget {
final FilterRule rule;
final VoidCallback onTap;
final ValueChanged<bool> onEnabledChanged;
final VoidCallback onDelete;
const _RuleTile({
super.key,
required this.rule,
required this.onTap,
required this.onEnabledChanged,
required this.onDelete,
});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final details =
'${filterRuleFieldLabel(context, rule.field)} · '
'${filterRuleMatchLabel(context, rule.match)}';
return InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 4, 8),
child: Row(
children: [
Icon(
rule.field == FilterRuleField.sender
? Icons.person_outline
: Icons.text_fields,
size: 24,
color: scheme.onSurfaceVariant,
),
const SizedBox(width: 16),
Expanded(
child: Opacity(
opacity: rule.enabled ? 1 : 0.6,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
rule.pattern,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
details,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
),
Switch(value: rule.enabled, onChanged: onEnabledChanged),
IconButton(
tooltip: l10n.common_delete,
icon: const Icon(Icons.delete_outline, size: 24),
color: scheme.onSurfaceVariant,
onPressed: onDelete,
),
],
),
),
);
}
}
class _AutomaticOptions extends StatelessWidget {
final MessageFilterService service;
const _AutomaticOptions({required this.service});
Future<void> _confirmResetLearning(BuildContext context) async {
final l10n = context.l10n;
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(l10n.messageFilter_resetLearning),
content: Text(l10n.messageFilter_resetLearningConfirm),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(l10n.common_cancel),
),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: Text(l10n.messageFilter_resetLearning),
),
],
),
);
if (confirmed == true) await service.resetLearning();
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final settings = service.settings;
final spam = service.spamExampleCount;
final notSpam = service.notSpamExampleCount;
const padding = MessageFilterSettingsScreen._tilePadding;
return Column(
children: [
SwitchListTile(
key: const ValueKey('messageFilter_duplicatesSwitch'),
contentPadding: padding,
secondary: const Icon(Icons.copy_all_outlined, size: 24),
title: Text(l10n.messageFilter_duplicates),
subtitle: Text(l10n.messageFilter_duplicatesSubtitle),
value: settings.duplicates,
onChanged: (value) => service.updateSettings(
service.settings.copyWith(duplicates: value),
),
),
const Divider(height: 1, indent: 16),
SwitchListTile(
key: const ValueKey('messageFilter_repeatedCharactersSwitch'),
contentPadding: padding,
secondary: const Icon(Icons.more_horiz, size: 24),
title: Text(l10n.messageFilter_repeatedCharacters),
subtitle: Text(l10n.messageFilter_repeatedCharactersSubtitle),
value: settings.repeatedCharacters,
onChanged: (value) => service.updateSettings(
service.settings.copyWith(repeatedCharacters: value),
),
),
const Divider(height: 1, indent: 16),
SwitchListTile(
key: const ValueKey('messageFilter_learningSwitch'),
contentPadding: padding,
secondary: const Icon(Icons.school_outlined, size: 24),
title: Text(l10n.messageFilter_learning),
subtitle: Text(l10n.messageFilter_learningSubtitle(spam, notSpam)),
value: settings.learning,
onChanged: (value) => service.updateSettings(
service.settings.copyWith(learning: value),
),
),
const Divider(height: 1, indent: 16),
MeshNavTile(
key: const ValueKey('messageFilter_resetLearning'),
icon: Icons.restart_alt,
title: l10n.messageFilter_resetLearning,
showChevron: false,
onTap: spam + notSpam == 0
? null
: () => _confirmResetLearning(context),
),
],
);
}
}
+27 -8
View File
@@ -18,6 +18,7 @@ import '../widgets/mesh_ui.dart';
import '../widgets/radio_settings_dialog.dart';
import 'app_settings_screen.dart';
import 'app_debug_log_screen.dart';
import 'message_filter_settings_screen.dart';
import 'ble_debug_log_screen.dart';
import '../widgets/radio_stats_entry.dart';
import 'telemetry_screen.dart';
@@ -124,14 +125,32 @@ class _SettingsScreenState extends State<SettingsScreen> {
SectionHeader(l10n.settings_appSettings),
MeshCard(
padding: EdgeInsets.zero,
child: MeshNavTile(
icon: Icons.settings_outlined,
title: l10n.settings_appSettings,
subtitle: l10n.settings_appSettingsSubtitle,
onTap: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const AppSettingsScreen()),
),
child: Column(
children: [
MeshNavTile(
icon: Icons.settings_outlined,
title: l10n.settings_appSettings,
subtitle: l10n.settings_appSettingsSubtitle,
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const AppSettingsScreen(),
),
),
),
const Divider(height: 1, indent: 16),
MeshNavTile(
icon: Icons.filter_alt_outlined,
title: l10n.messageFilter_title,
subtitle: l10n.messageFilter_settingsSubtitle,
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const MessageFilterSettingsScreen(),
),
),
),
],
),
),