Add support for jumping to event links (#103)

Fixes #78.

Reviewed-on: #103
This commit is contained in:
Henry Hiles 2026-09-29 17:00:43 -04:00 • committed by Henry Hiles
commit 1c4bf99be2
16 changed files with 169 additions and 113 deletions

View file

@ -84,9 +84,7 @@ A simple and user-friendly Matrix client made with Flutter and a Gomuks backend.
- [x] Clickable - [x] Clickable
- [x] Matrix URIs - [x] Matrix URIs
- [x] Matrix.to links - [x] Matrix.to links
- [ ] Events - [x] Events
- [ ] Render more nicely
- [ ] Clickable
- [x] Custom emojis/stickers - [x] Custom emojis/stickers
- [x] History loading - [x] History loading
- [x] Editing - [x] Editing

View file

@ -9,8 +9,8 @@ class ContextualEventController(String? _) extends Notifier<int?> {
@override @override
bool updateShouldNotify(_, _) => true; bool updateShouldNotify(_, _) => true;
static final provider = NotifierProvider.family static final provider =
.autoDispose<ContextualEventController, int?, String?>( NotifierProvider.family<ContextualEventController, int?, String?>(
ContextualEventController.new, ContextualEventController.new,
); );
} }

View file

@ -16,11 +16,28 @@ class EventController(final GetEventRequest request)
(event) => event.eventId == request.eventId, (event) => event.eventId == request.eventId,
); );
return event ?? if (event != null) return event;
await ref
final fetchedEvent = await ref
.watch(ClientController.provider.notifier) .watch(ClientController.provider.notifier)
.getEvent(request) .getEvent(request)
.onError((_, _) => null); .onError((_, _) => null);
if (fetchedEvent != null) {
ref
.watch(RoomsController.provider.notifier)
.update(
.new({
request.roomId: .new(
events: .new({fetchedEvent.rowId: fetchedEvent}),
),
}),
);
return fetchedEvent;
}
return null;
} }
static final provider = AsyncNotifierProvider.family static final provider = AsyncNotifierProvider.family

View file

@ -59,7 +59,6 @@ class GomuksListenerController extends AsyncNotifier<void> {
.new({ .new({
event.roomId: .new(events: .new({event.rowId: event})), event.roomId: .new(events: .new({event.rowId: event})),
}), }),
.new(),
); );
break; break;

View file

@ -35,7 +35,6 @@ class NotificationsController([final NotificationsRequest? request])
), ),
), ),
}), }),
.new(),
); );
return .new(mentions.map((event) => (event.rowId, event.roomId))); return .new(mentions.map((event) => (event.rowId, event.roomId)));
@ -79,7 +78,6 @@ class NotificationsController([final NotificationsRequest? request])
), ),
), ),
}), }),
.new(),
); );
return currentNotifications.addAll( return currentNotifications.addAll(

View file

@ -77,7 +77,6 @@ class RoomChatController(final ChatParams info)
), ),
), ),
}), }),
.new(),
); );
return .new( return .new(
timeline: .new(events.map((element) => element.rowId)), timeline: .new(events.map((element) => element.rowId)),
@ -149,7 +148,6 @@ class RoomChatController(final ChatParams info)
), ),
), ),
}), }),
.new(),
); );
} else { } else {
final paginationResponse = await client.paginateManual( final paginationResponse = await client.paginateManual(
@ -173,7 +171,6 @@ class RoomChatController(final ChatParams info)
), ),
), ),
}), }),
.new(),
); );
final eventRowIds = paginationResponse.events final eventRowIds = paginationResponse.events
@ -274,7 +271,6 @@ class RoomChatController(final ChatParams info)
clientSticky: .new({event.rowId}), clientSticky: .new({event.rowId}),
), ),
}), }),
.new(),
); );
} }

View file

@ -33,7 +33,10 @@ class RoomsController extends Notifier<IMap<String, Room>> {
.new(), .new(),
); );
void update(IMap<String, Room> rooms, ISet<String> leftRooms) { void update(
IMap<String, Room> rooms, [
ISet<String> leftRooms = const ISet.empty(),
]) {
final merged = rooms.entries.fold(state, (acc, entry) { final merged = rooms.entries.fold(state, (acc, entry) {
final roomId = entry.key; final roomId = entry.key;
final incoming = entry.value; final incoming = entry.value;

View file

@ -202,7 +202,7 @@ extension BuildEventOptions on Event {
await Clipboard.setData( await Clipboard.setData(
ClipboardData( ClipboardData(
text: text:
"matrix:roomid/${room.metadata?.id.substring(1)}/e/$eventId$vias", "matrix:roomid/${room.metadata?.id.substring(1)}/e/${eventId.substring(1)}$vias",
), ),
); );
}, },

View file

@ -1,27 +1,28 @@
import "package:collection/collection.dart"; import "package:collection/collection.dart";
import "package:flutter_riverpod/experimental/mutation.dart"; import "package:flutter_riverpod/experimental/mutation.dart";
import "package:nexus/controllers/contextual_event.dart";
import "package:nexus/controllers/key.dart"; import "package:nexus/controllers/key.dart";
import "package:nexus/controllers/spaces.dart"; import "package:nexus/controllers/spaces.dart";
import "package:nexus/models/space.dart"; import "package:nexus/models/space.dart";
extension FocusRoom on MutationTarget { extension FocusRoom on MutationTarget {
Future<bool> focusRoom(String id) async { Future<bool> focusRoom(String roomId, [int? eventRowId]) async {
final spaces = container.read(SpacesController.provider); final spaces = container.read(SpacesController.provider);
if (spaces.firstWhereOrNull((space) => space.id == id) case Space _?) { if (spaces.firstWhereOrNull((space) => space.id == roomId) case Space _?) {
await container await container
.read(KeyController.provider(KeyController.spaceKey).notifier) .read(KeyController.provider(KeyController.spaceKey).notifier)
.set(id); .set(roomId);
return true; return true;
} }
final parent = spaces.firstWhereOrNull( final parent = spaces.firstWhereOrNull(
(space) => (space) =>
space.children.any((room) => room.metadata?.id == id) || space.children.any((room) => room.metadata?.id == roomId) ||
space.subSpaces.any( space.subSpaces.any(
(sub) => (sub) =>
sub.room.metadata?.id == id || sub.room.metadata?.id == roomId ||
sub.children.any((room) => room.metadata?.id == id), sub.children.any((room) => room.metadata?.id == roomId),
), ),
); );
if (parent == null) return false; if (parent == null) return false;
@ -32,7 +33,13 @@ extension FocusRoom on MutationTarget {
await container await container
.read(KeyController.provider(KeyController.roomKey).notifier) .read(KeyController.provider(KeyController.roomKey).notifier)
.set(id); .set(roomId);
if (eventRowId != null) {
container
.read(ContextualEventController.provider(roomId).notifier)
.set(eventRowId);
}
return true; return true;
} }

View file

@ -0,0 +1,70 @@
import "package:fast_immutable_collections/fast_immutable_collections.dart";
/// A parsed Matrix link.
///
/// [identifier] is the room ID, room alias or user ID (e.g. "#room:matrix.org"),
/// [eventId] is set for event permalinks (e.g. "$abc123"), and [via] holds any
/// `via` servers from the link.
typedef LinkInfo = ({String identifier, String? eventId, IList<String> via});
extension GetLinkInfo on String {
/// Parses this string as a Matrix link.
///
/// Supports:
/// - https://matrix.to/#/{id}[/{eventId}][?via=...]
/// - matrix:roomid/{id}[/e/{eventId}][?via=...]
/// - matrix:r/{alias}[/e/{eventId}][?via=...]
/// - matrix:u/{userId}
///
/// Returns null if this is not a Matrix link.
LinkInfo? get linkInfo {
final uri = Uri.tryParse(trim());
if (uri == null) return null;
if ((uri.scheme == "http" || uri.scheme == "https") &&
uri.host == "matrix.to") {
// matrix.to keeps everything, including the query, in the fragment,
// so parse the fragment as its own URI.
final inner = Uri.tryParse(uri.fragment);
final segments = inner?.pathSegments.where((s) => s.isNotEmpty).toList();
if (inner == null || segments == null || segments.isEmpty) return null;
return (
identifier: segments.first,
eventId: segments.length > 1 && segments[1].startsWith(r"$")
? segments[1]
: null,
via: .new(inner.queryParametersAll["via"] ?? []),
);
}
if (uri.scheme == "matrix") {
final segments = uri.pathSegments;
if (segments.length < 2 || segments[1].isEmpty) return null;
final sigil = switch (segments[0].toLowerCase()) {
"r" => "#",
"roomid" => "!",
"u" => "@",
_ => null,
};
if (sigil == null) return null;
// Event segment is "e/{eventId}" (without the "$" sigil) and is
// only valid on room links.
final hasEvent =
sigil != "@" &&
segments.length >= 4 &&
segments[2].toLowerCase() == "e" &&
segments[3].isNotEmpty;
return (
identifier: "$sigil${segments[1]}",
eventId: hasEvent ? "\$${segments[3]}" : null,
via: .new(uri.queryParametersAll["via"] ?? []),
);
}
return null;
}
}

View file

@ -1,51 +0,0 @@
import "package:fast_immutable_collections/fast_immutable_collections.dart";
extension LinkToMention on String {
/// Extracts a Matrix identifier from this string.
///
/// Supports:
/// - https://matrix.to/#/...
/// - matrix:roomid/...
/// - matrix:r/...
/// - matrix:u/...
///
/// Returns the decoded identifier (e.g. "#room:matrix.org")
/// or null if this is not a Matrix link.
/// TODO: Needs to be reworked to handle event links. Might be worth just rewriting, I don't like this code.
String? get mention {
final trimmed = trim();
final matrixTo = RegExp(
r"^https?://matrix\.to/#/(.[^/?#]+)",
caseSensitive: false,
);
final matrixToMatch = matrixTo.firstMatch(trimmed);
if (matrixToMatch != null) {
return Uri.decodeComponent(matrixToMatch.group(1)!);
}
if (trimmed.toLowerCase().startsWith("matrix:")) {
try {
final uri = Uri.parse(trimmed);
if (uri.pathSegments.isNotEmpty) {
final identifier = uri.pathSegments.last;
if (identifier.isNotEmpty) {
return "${switch (uri.pathSegments.firstOrNull) {
"r" => "#",
"roomid" => "!",
"u" => "@",
_ => "",
}}${Uri.decodeComponent(identifier)}";
}
}
} catch (_) {}
}
return null;
}
IList<String> get via =>
.new(Uri.tryParse(replaceAll("/#", ""))?.queryParametersAll["via"] ?? []);
}

View file

@ -2,7 +2,7 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart";
import "package:material_ui/material_ui.dart"; import "package:material_ui/material_ui.dart";
import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_riverpod/flutter_riverpod.dart";
import "package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart"; import "package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart";
import "package:nexus/helpers/extensions/link_to_mention.dart"; import "package:nexus/helpers/extensions/get_link_info.dart";
import "package:nexus/helpers/launch_helper.dart"; import "package:nexus/helpers/launch_helper.dart";
import "package:nexus/helpers/mxc_image.dart"; import "package:nexus/helpers/mxc_image.dart";
import "package:nexus/widgets/expandable_image.dart"; import "package:nexus/widgets/expandable_image.dart";
@ -70,7 +70,7 @@ class const Html(
), ),
"a" => "a" =>
element.attributes["href"]?.mention == null element.attributes["href"]?.linkInfo == null
? null ? null
: InlineCustomWidget( : InlineCustomWidget(
child: MentionChip(element.attributes["href"]!, roomId), child: MentionChip(element.attributes["href"]!, roomId),

View file

@ -1,9 +1,10 @@
import "package:material_ui/material_ui.dart"; import "package:material_ui/material_ui.dart";
import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_riverpod/flutter_riverpod.dart";
import "package:nexus/controllers/event.dart";
import "package:nexus/controllers/room_summary.dart"; import "package:nexus/controllers/room_summary.dart";
import "package:nexus/controllers/user.dart"; import "package:nexus/controllers/user.dart";
import "package:nexus/helpers/extensions/focus_room.dart"; import "package:nexus/helpers/extensions/focus_room.dart";
import "package:nexus/helpers/extensions/link_to_mention.dart"; import "package:nexus/helpers/extensions/get_link_info.dart";
import "package:nexus/helpers/extensions/show_user_popover.dart"; import "package:nexus/helpers/extensions/show_user_popover.dart";
import "package:nexus/models/content/membership.dart"; import "package:nexus/models/content/membership.dart";
import "package:nexus/models/room_summary.dart"; import "package:nexus/models/room_summary.dart";
@ -13,7 +14,8 @@ class const MentionChip(final String content, final String? roomId, {super.key})
extends ConsumerWidget { extends ConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final mention = content.mention; final linkInfo = content.linkInfo;
final mention = linkInfo?.identifier;
final data = switch (mention?.characters.firstOrNull) { final data = switch (mention?.characters.firstOrNull) {
"@" => "@" =>
ref ref
@ -40,7 +42,22 @@ class const MentionChip(final String content, final String? roomId, {super.key})
if (data case MembershipContent membership) { if (data case MembershipContent membership) {
context.showUserPopover(membership, mention, roomId: roomId); context.showUserPopover(membership, mention, roomId: roomId);
} else if (data case RoomSummary summary) { } else if (data case RoomSummary summary) {
if (!await ref.focusRoom(summary.roomId) && context.mounted) { // TODO: This is an extra call that isn't truly needed, get rid of it
final eventRowId = linkInfo?.eventId == null
? null
: await ref
.read(
EventController.provider(
.new(
roomId: summary.roomId,
eventId: linkInfo!.eventId!,
),
).selectAsync((data) => data?.rowId),
)
.onError((_, _) => null);
if (!await ref.focusRoom(summary.roomId, eventRowId) &&
context.mounted) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => Consumer( builder: (context) => Consumer(
@ -53,7 +70,7 @@ class const MentionChip(final String content, final String? roomId, {super.key})
) )
.whenOrNull(data: (data) => data) ?? .whenOrNull(data: (data) => data) ??
summary, summary,
via: content.via, via: linkInfo?.via,
), ),
), ),
); );
@ -63,9 +80,7 @@ class const MentionChip(final String content, final String? roomId, {super.key})
child: Text( child: Text(
switch (data) { switch (data) {
RoomSummary summary => RoomSummary summary =>
(summary.name == null ? null : "#${summary.name}") ?? "${(summary.name == null ? null : "#${summary.name}") ?? summary.canonicalAlias ?? summary.roomId}${linkInfo?.eventId == null ? "" : " > ${linkInfo?.eventId}"}",
summary.canonicalAlias ??
summary.roomId,
MembershipContent membership => MembershipContent membership =>
membership.displayName == null membership.displayName == null
? mention ? mention

View file

@ -1,8 +1,9 @@
import "package:fast_immutable_collections/fast_immutable_collections.dart";
import "package:material_ui/material_ui.dart"; import "package:material_ui/material_ui.dart";
import "package:flutter_hooks/flutter_hooks.dart"; import "package:flutter_hooks/flutter_hooks.dart";
import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:hooks_riverpod/hooks_riverpod.dart";
import "package:nexus/controllers/room_summary.dart"; import "package:nexus/controllers/room_summary.dart";
import "package:nexus/helpers/extensions/link_to_mention.dart"; import "package:nexus/helpers/extensions/get_link_info.dart";
import "package:nexus/widgets/room_summary_dialog.dart"; import "package:nexus/widgets/room_summary_dialog.dart";
class const JoinDialog(final WidgetRef ref, {super.key}) extends HookWidget { class const JoinDialog(final WidgetRef ref, {super.key}) extends HookWidget {
@ -13,20 +14,26 @@ class const JoinDialog(final WidgetRef ref, {super.key}) extends HookWidget {
Future<void> onJoin() async { Future<void> onJoin() async {
Navigator.of(context).pop(); Navigator.of(context).pop();
final roomIdOrAlias = roomAlias.text.mention ?? roomAlias.text; final linkInfo = roomAlias.text.linkInfo;
final via = roomAlias.text.via; final roomIdOrAlias = linkInfo?.identifier ?? roomAlias.text;
showDialog( showDialog(
context: context, context: context,
builder: (context) => switch (ref.watch( builder: (context) => switch (ref.watch(
RoomSummaryController.provider( RoomSummaryController.provider(
.new(roomIdOrAlias: roomIdOrAlias, via: via), .new(
roomIdOrAlias: roomIdOrAlias,
via: linkInfo?.via ?? const IList.empty(),
),
), ),
)) { )) {
AsyncData(:final value) => RoomSummaryDialog(value, via: via), AsyncData(:final value) => RoomSummaryDialog(
value,
via: linkInfo?.via,
),
AsyncError _ || AsyncLoading _ => RoomSummaryDialog( AsyncError _ || AsyncLoading _ => RoomSummaryDialog(
.new(roomId: roomAlias.text), .new(roomId: roomAlias.text),
via: via, via: linkInfo?.via,
), ),
}, },
); );

View file

@ -4,7 +4,6 @@ import "package:m3e_buttons/m3e_buttons.dart";
import "package:material_ui/material_ui.dart"; import "package:material_ui/material_ui.dart";
import "package:flutter_hooks/flutter_hooks.dart"; import "package:flutter_hooks/flutter_hooks.dart";
import "package:hooks_riverpod/hooks_riverpod.dart"; import "package:hooks_riverpod/hooks_riverpod.dart";
import "package:nexus/controllers/contextual_event.dart";
import "package:nexus/controllers/notifications.dart"; import "package:nexus/controllers/notifications.dart";
import "package:nexus/helpers/extensions/focus_room.dart"; import "package:nexus/helpers/extensions/focus_room.dart";
import "package:nexus/models/event.dart"; import "package:nexus/models/event.dart";
@ -129,18 +128,8 @@ class const NotificationsPage({
child: HighlightWrapper( child: HighlightWrapper(
InkWell( InkWell(
onTap: () async { onTap: () async {
await ref.focusRoom(roomId);
ref
.watch(
ContextualEventController.provider(
roomId,
).notifier,
)
.set(rowId);
if (context.mounted) {
Navigator.of(context).pop(); Navigator.of(context).pop();
} await ref.focusRoom(roomId, rowId);
}, },
child: IgnorePointer( child: IgnorePointer(
child: EventRenderer( child: EventRenderer(

View file

@ -13,6 +13,8 @@ import "package:nexus/helpers/hooks/chat_scroll.dart";
import "package:nexus/models/event.dart"; import "package:nexus/models/event.dart";
import "package:nexus/models/relation_type.dart"; import "package:nexus/models/relation_type.dart";
import "package:nexus/widgets/composer/composer.dart"; import "package:nexus/widgets/composer/composer.dart";
import "package:nexus/widgets/error_dialog.dart";
import "package:nexus/widgets/loading.dart";
import "package:nexus/widgets/pinned_events_drawer.dart"; import "package:nexus/widgets/pinned_events_drawer.dart";
import "package:nexus/widgets/member_list.dart"; import "package:nexus/widgets/member_list.dart";
import "package:nexus/widgets/room_appbar.dart"; import "package:nexus/widgets/room_appbar.dart";
@ -168,7 +170,9 @@ final class const RoomChat({
Positioned.fill( Positioned.fill(
child: Padding( child: Padding(
padding: .symmetric(horizontal: 4), padding: .symmetric(horizontal: 4),
child: ChatTimeline( child: switch (controllerData) {
AsyncLoading(value: _?) ||
AsyncData(value: _) => ChatTimeline(
scroll: scroll, scroll: scroll,
roomId: roomId, roomId: roomId,
jumpToEvent: jumpToEvent, jumpToEvent: jumpToEvent,
@ -176,6 +180,10 @@ final class const RoomChat({
highlightedEvent: highlightedEvent.value, highlightedEvent: highlightedEvent.value,
composerHeight: composerSize.value, composerHeight: composerSize.value,
), ),
AsyncLoading _ => Loading(),
AsyncError(:final error, :final stackTrace) =>
ErrorDialog(error, stackTrace),
},
), ),
), ),
Positioned( Positioned(