diff --git a/lib/controllers/account_data.dart b/lib/controllers/account_data.dart index 62997b5..13b5d81 100644 --- a/lib/controllers/account_data.dart +++ b/lib/controllers/account_data.dart @@ -5,6 +5,8 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:flutter/foundation.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:nexus/controllers/client.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/models/per_message_profiles.dart"; import "package:nexus/models/account_data.dart"; import "package:nexus/models/push_rules.dart"; import "package:nexus/models/requests/update_push_rule.dart"; @@ -73,6 +75,40 @@ class AccountDataController extends Notifier { (data) => data.ignoredUserList.contains(userId) == ignored, ); + Future setPerMessageProfiles(PerMessageProfiles profiles) => + _sendAndWait( + () => ref + .read(ClientController.provider.notifier) + .setAccountData( + .new(type: AccountData.perMessageProfilesKey, content: profiles), + ), + (data) => data.perMessageProfiles == profiles, + ); + + Future setRoomProfile(String roomId, String profileId) async { + const type = AccountData.perMessageProfilesKey; + final current = ref + .read(RoomsController.provider)[roomId] + ?.accountData[type]; + + await ref + .read(ClientController.provider.notifier) + .setAccountData( + .new( + type: type, + roomId: roomId, + content: {...?current, "default_profile_id": profileId}, + ), + ); + await ref + .read(RoomsController.provider.notifier) + .awaitRooms( + (rooms) => + rooms[roomId]?.accountData[type]?["default_profile_id"] == + profileId, + ); + } + /// Saves [rule] of [kind], creating it if it's new, or otherwise changing only /// its actions and whether it's enabled. Future savePushRule(PushRuleKind kind, PushRule rule) { diff --git a/lib/controllers/personas.dart b/lib/controllers/personas.dart new file mode 100644 index 0000000..bc3073f --- /dev/null +++ b/lib/controllers/personas.dart @@ -0,0 +1,56 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:flutter/foundation.dart"; +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:nexus/controllers/account_data.dart"; +import "package:nexus/controllers/rooms.dart"; +import "package:nexus/models/account_data.dart"; +import "package:nexus/models/per_message_profiles.dart"; + +typedef RoomPersonas = ({ + IList profiles, + StoredProfile? current, +}); + +class PersonasController(final String roomId) extends Notifier { + @override + RoomPersonas build() { + final global = ref.watch( + AccountDataController.provider.select((data) => data.perMessageProfiles), + ); + final roomJson = ref.watch( + RoomsController.provider.select( + (rooms) => + rooms[roomId]?.accountData[AccountData.perMessageProfilesKey], + ), + ); + + PerMessageProfiles? room; + if (roomJson != null) { + try { + room = .fromJson(roomJson); + } catch (error) { + debugPrint("Ignoring invalid room per-message profiles: $error"); + } + } + + final roomIds = room?.profiles.map((profile) => profile.id).toISet(); + final profiles = (room?.profiles ?? const IList.empty()) + .addAll( + global.profiles.where( + (profile) => !(roomIds?.contains(profile.id) ?? false), + ), + ); + + final currentId = room?.defaultProfileId ?? global.defaultProfileId; + return ( + profiles: profiles, + current: currentId == null || currentId.isEmpty + ? null + : profiles.firstWhereOrNull((profile) => profile.id == currentId), + ); + } + + static final provider = NotifierProvider.autoDispose + .family(PersonasController.new); +} diff --git a/lib/controllers/rooms.dart b/lib/controllers/rooms.dart index 66ffa3b..91d8093 100644 --- a/lib/controllers/rooms.dart +++ b/lib/controllers/rooms.dart @@ -189,6 +189,7 @@ class RoomsController extends Notifier> { ? incoming.timeline : existing.timeline.addAll(incoming.timeline), receipts: mergeReceipts(existing.receipts, incoming.receipts), + accountData: existing.accountData.addAll(incoming.accountData), ) ?? incoming.copyWith( receipts: mergeReceipts(const .empty(), incoming.receipts), diff --git a/lib/controllers/settings_sections.dart b/lib/controllers/settings_sections.dart index f55a228..e2ea8a1 100644 --- a/lib/controllers/settings_sections.dart +++ b/lib/controllers/settings_sections.dart @@ -43,6 +43,7 @@ import "package:nexus/widgets/settings/block_user_field.dart"; import "package:nexus/widgets/settings/dialog_list_tile.dart"; import "package:nexus/widgets/settings/enable_image_packs_sheet.dart"; import "package:nexus/widgets/settings/keyword_field.dart"; +import "package:nexus/widgets/settings/persona_sheet.dart"; import "package:nexus/widgets/users/user_bottom_sheet.dart"; import "package:nexus/widgets/encryption/reset_encryption_sheet.dart"; @@ -51,6 +52,9 @@ class SettingsSectionsController @override Future>> build() async { final settings = await ref.watch(SettingsController.provider.future); + final personas = ref.watch( + AccountDataController.provider.select((data) => data.perMessageProfiles), + ); // Not awaited, so a slow homeserver doesn't hold up the rest of settings final accountManagement = ref .watch(AccountManagementController.provider) @@ -443,6 +447,99 @@ class SettingsSectionsController ), ]), ), + .new( + title: "Personas", + icon: Icons.groups, + settings: .new([ + .new( + title: "Enable Personas", + description: "Send messages as other names and avatars, chosen per room from the composer.", + icon: Icons.groups, + builder: (title, description, icon) => SwitchListTile( + title: Text(title), + subtitle: Text(description), + secondary: Icon(icon), + value: settings.personas, + onChanged: (value) => ref + .read(SettingsController.provider.notifier) + .set(settings.copyWith(personas: value)) + .onError(showError), + ), + ), + if (settings.personas) ...[ + if (personas.profiles.isNotEmpty) + .new( + title: "Default Persona", + description: "Who you send as in rooms you haven't chosen a persona for.", + icon: Icons.person_pin, + builder: (title, description, icon) => + DialogListTile( + icon: Icon(icon), + title: title, + subtitle: Text(description), + value: personas.defaultProfileId ?? "", + options: [ + "", + ...personas.profiles.map((profile) => profile.id), + ], + getName: (id) => switch (personas.byId(id)) { + final profile? => profile.displayName ?? id, + null => "Yourself", + }, + onChanged: (id) => accountData + .setPerMessageProfiles( + personas.copyWith( + defaultProfileId: id.isEmpty ? null : id, + ), + ) + .onError(showError), + ), + ), + header( + "Personas", + "The names and avatars you can send messages as.", + Icons.groups, + ), + ...personas.profiles.map( + (persona) => Setting( + title: persona.displayName ?? persona.id, + description: "A persona.", + icon: Icons.person, + builder: (title, _, _) => Builder( + builder: (context) => ListTile( + leading: AvatarOrHash(persona.avatarUrl, title), + title: Text(title), + subtitle: switch (persona.triggers.firstOrNull) { + final trigger? => Text( + "Trigger: ${trigger.prefix}text${trigger.suffix}", + ), + null => null, + }, + trailing: Icon(Icons.chevron_right), + onTap: () => context.showAdaptiveSheet( + (_) => PersonaSheet(persona: persona), + ), + ), + ), + ), + ), + .new( + title: "Add Persona", + description: "Create a name and avatar to send messages as.", + icon: Icons.add, + builder: (title, _, icon) => Builder( + builder: (context) => ListTile( + leading: Icon(icon), + title: Text(title), + onTap: () => context.showAdaptiveSheet( + (_) => const PersonaSheet(), + ), + ), + ), + ), + ], + ]), + ), .new( title: "Image Packs", icon: Icons.emoji_emotions, diff --git a/lib/models/account_data.dart b/lib/models/account_data.dart index 51176cd..94149f3 100644 --- a/lib/models/account_data.dart +++ b/lib/models/account_data.dart @@ -1,5 +1,6 @@ import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:freezed_annotation/freezed_annotation.dart"; +import "package:nexus/models/per_message_profiles.dart"; import "package:nexus/models/push_rules.dart"; part "account_data.freezed.dart"; @@ -27,6 +28,8 @@ class const AccountData({ final PushRules pushRules = const .new(), @JsonKey(name: AccountData.ignoredUserListKey) final IgnoredUserList ignoredUserList = const .new(), + @JsonKey(name: AccountData.perMessageProfilesKey) + final PerMessageProfiles perMessageProfiles = const .new(), }) with _$AccountData { static const invitePermissionConfigKey = "m.invite_permission_config"; static const directKey = "m.direct"; @@ -35,6 +38,7 @@ class const AccountData({ static const legacyImagePackRoomsKey = "im.ponies.emote_rooms"; static const pushRulesKey = "m.push_rules"; static const ignoredUserListKey = "m.ignored_user_list"; + static const perMessageProfilesKey = "fi.mau.msc4461.per_message_profiles.v3"; ImagePackRooms get enabledImagePacks => imagePackRooms ?? legacyImagePackRooms ?? const .new(); diff --git a/lib/models/per_message_profiles.dart b/lib/models/per_message_profiles.dart new file mode 100644 index 0000000..7de8398 --- /dev/null +++ b/lib/models/per_message_profiles.dart @@ -0,0 +1,48 @@ +import "package:collection/collection.dart"; +import "package:fast_immutable_collections/fast_immutable_collections.dart"; +import "package:freezed_annotation/freezed_annotation.dart"; + +part "per_message_profiles.freezed.dart"; +part "per_message_profiles.g.dart"; + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const PerMessageProfiles({ + final String? defaultProfileId, + final IList profiles = const .empty(), +}) with _$PerMessageProfiles { + StoredProfile? byId(String? id) => + profiles.firstWhereOrNull((profile) => profile.id == id); + + Map toJson() => _$PerMessageProfilesToJson(this); + + factory PerMessageProfiles.fromJson(Map json) => + _$PerMessageProfilesFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const StoredProfile({ + required final String id, + @JsonKey(name: "displayname") final String? displayName, + final Uri? avatarUrl, + final IList triggers = const .empty(), +}) with _$StoredProfile { + Map toJson() => _$StoredProfileToJson(this); + + factory StoredProfile.fromJson(Map json) => + _$StoredProfileFromJson(json); +} + +@Freezed(toJson: false, fromJson: false) +@JsonSerializable(includeIfNull: false) +class const ProfileTrigger({ + final String prefix = "", + final String suffix = "", + final bool keepTrigger = false, +}) with _$ProfileTrigger { + Map toJson() => _$ProfileTriggerToJson(this); + + factory ProfileTrigger.fromJson(Map json) => + _$ProfileTriggerFromJson(json); +} diff --git a/lib/models/room.dart b/lib/models/room.dart index b809a23..f93b261 100644 --- a/lib/models/room.dart +++ b/lib/models/room.dart @@ -45,10 +45,12 @@ class const Room({ final IMap> state = const .empty(), final IMap> receipts = const .empty(), + + @JsonKey(fromJson: Room.accountDataJsonToIMap) + final IMap> accountData = const .empty(), final bool dismissNotifications = false, final bool hasMore = true, - // IMap accountData, // IList notifications, }) with _$Room { static IMap timelineTupleJsonToIMap(List json) => @@ -61,6 +63,15 @@ class const Room({ ), ); + static IMap> accountDataJsonToIMap( + Map json, + ) => .fromEntries( + json.entries.map( + (entry) => + .new(entry.key, Map.from(entry.value["content"])), + ), + ); + static IMap eventsJsonToIMap(List json) => IMap.fromEntries( json.map((eventJson) { diff --git a/lib/models/settings.dart b/lib/models/settings.dart index 4b34fd5..923ee5f 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -23,6 +23,7 @@ class const Settings({ final RoomOrder roomOrder = .unreadFirst, final NameColor nameColor = .powerLevel, final ShowAndSend typingIndicators = .showAndSend, + final bool personas = false, /// When not sending, read receipts are still sent privately, so that the /// user's other devices know what has been read. diff --git a/lib/widgets/composer/composer.dart b/lib/widgets/composer/composer.dart index 5f34e35..96ed001 100644 --- a/lib/widgets/composer/composer.dart +++ b/lib/widgets/composer/composer.dart @@ -3,6 +3,7 @@ import "dart:io"; import "package:fast_immutable_collections/fast_immutable_collections.dart"; import "package:collection/collection.dart"; import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:nexus/widgets/composer/persona_button.dart"; import "package:nexus/controllers/bot_argument_suggestions.dart"; import "package:nexus/controllers/bot_command_draft.dart"; import "package:nexus/controllers/bot_commands.dart"; @@ -565,6 +566,7 @@ class const Composer( ), ) ? [ + PersonaButton(roomId), IconButton( onPressed: hasReplacement ? null diff --git a/lib/widgets/composer/persona_button.dart b/lib/widgets/composer/persona_button.dart new file mode 100644 index 0000000..960a525 --- /dev/null +++ b/lib/widgets/composer/persona_button.dart @@ -0,0 +1,74 @@ +import "package:flutter_riverpod/flutter_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/account_data.dart"; +import "package:nexus/controllers/personas.dart"; +import "package:nexus/controllers/settings.dart"; +import "package:nexus/main.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; + +/// Chooses the persona messages are sent as in [roomId], if personas are on. +class const PersonaButton(final String roomId, {super.key}) + extends ConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final enabled = ref.watch( + SettingsController.provider.select( + (settings) => settings.value?.personas ?? false, + ), + ); + final (:profiles, :current) = ref.watch( + PersonasController.provider(roomId), + ); + if (!enabled || profiles.isEmpty) return const SizedBox.shrink(); + + Future choose(String profileId) => ref + .read(AccountDataController.provider.notifier) + .setRoomProfile(roomId, profileId) + .onError(showError); + + PopupMenuItem item({ + required String id, + required Widget leading, + required String title, + }) { + final selected = (current?.id ?? "") == id; + return PopupMenuItem( + onTap: () => choose(id), + child: ListTile( + selected: selected, + leading: leading, + title: Text(title), + trailing: selected ? Icon(Icons.check) : null, + ), + ); + } + + return AdaptiveMenuButton( + tooltip: switch (current) { + final current? => "Sending as ${current.displayName ?? current.id}", + null => "Choose persona", + }, + icon: switch (current) { + final current? => AvatarOrHash( + current.avatarUrl, + current.displayName ?? current.id, + ), + null => Icon(Icons.person), + }, + itemBuilder: (_) => [ + item(id: "", leading: Icon(Icons.person), title: "Yourself"), + ...profiles.map( + (profile) => item( + id: profile.id, + leading: AvatarOrHash( + profile.avatarUrl, + profile.displayName ?? profile.id, + ), + title: profile.displayName ?? profile.id, + ), + ), + ], + ); + } +} diff --git a/lib/widgets/settings/persona_sheet.dart b/lib/widgets/settings/persona_sheet.dart new file mode 100644 index 0000000..d88aaf3 --- /dev/null +++ b/lib/widgets/settings/persona_sheet.dart @@ -0,0 +1,138 @@ +import "package:flutter_hooks/flutter_hooks.dart"; +import "package:hooks_riverpod/hooks_riverpod.dart"; +import "package:material_adaptive_sheets/material_adaptive_sheets.dart"; +import "package:material_ui/material_ui.dart"; +import "package:nexus/controllers/account_data.dart"; +import "package:nexus/helpers/hooks/saving.dart"; +import "package:nexus/main.dart"; +import "package:nexus/models/per_message_profiles.dart"; +import "package:nexus/widgets/avatars/avatar_or_hash.dart"; +import "package:nexus/widgets/avatars/editable_avatar.dart"; + +class const PersonaSheet({final StoredProfile? persona, super.key}) + extends HookConsumerWidget { + @override + Widget build(BuildContext context, WidgetRef ref) { + final saving = Saving.use(); + final trigger = persona?.triggers.firstOrNull; + final nameController = useTextEditingController(text: persona?.displayName); + final prefixController = useTextEditingController(text: trigger?.prefix); + final suffixController = useTextEditingController(text: trigger?.suffix); + final avatar = useState(persona?.avatarUrl); + final name = useValueListenable(nameController).text.trim(); + + final accountData = ref.read(AccountDataController.provider.notifier); + PerMessageProfiles current() => + ref.read(AccountDataController.provider).perMessageProfiles; + + Future update(PerMessageProfiles profiles) async { + await saving.run(() => accountData.setPerMessageProfiles(profiles)); + if (context.mounted) Navigator.of(context).pop(); + } + + Future save() { + final prefix = prefixController.text; + final suffix = suffixController.text; + final edited = StoredProfile( + id: + persona?.id ?? + DateTime.now().microsecondsSinceEpoch.toRadixString(36), + displayName: name, + avatarUrl: avatar.value, + triggers: .new([ + if (prefix.isNotEmpty || suffix.isNotEmpty) + (trigger ?? const .new()).copyWith(prefix: prefix, suffix: suffix), + ...?persona?.triggers.skip(1), + ]), + ); + final profiles = current(); + + return update( + profiles.copyWith( + profiles: persona == null + ? profiles.profiles.add(edited) + : profiles.profiles.replaceFirstWhere( + (profile) => profile.id == persona!.id, + (_) => edited, + ), + ), + ).onError(showError); + } + + Future delete() { + final profiles = current(); + return update( + profiles.copyWith( + profiles: profiles.profiles.removeWhere( + (profile) => profile.id == persona!.id, + ), + defaultProfileId: profiles.defaultProfileId == persona!.id + ? null + : profiles.defaultProfileId, + ), + ).onError(showError); + } + + return SheetLayout( + title: Text(persona == null ? "Add Persona" : "Edit Persona"), + actions: [ + if (persona != null) + TextButton( + onPressed: saving.active ? null : delete, + style: TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.error, + ), + child: Text("Delete"), + ), + TextButton(onPressed: Navigator.of(context).pop, child: Text("Cancel")), + TextButton( + onPressed: name.isEmpty || saving.active ? null : save, + child: Text("Save"), + ), + ], + children: [ + Center( + child: EditableAvatar( + dimension: 120, + hasAvatar: avatar.value != null, + onChanged: (url) async => avatar.value = url, + child: AvatarOrHash( + avatar.value, + name.isEmpty ? "Persona" : name, + dimension: 120, + ), + ), + ), + TextField( + controller: nameController, + autofocus: persona == null, + textCapitalization: .words, + decoration: const .new(labelText: "Display name"), + ), + Text( + "Optionally, messages that start with the prefix *and* end with the suffix are sent as this persona, without them. Leave one empty to only need the other. Both are case-sensitive.", + ), + Row( + spacing: 8, + children: [ + Expanded( + child: TextField( + controller: prefixController, + decoration: const .new( + labelText: "Prefix", + hintText: "e.g. k:", + ), + ), + ), + Expanded( + child: TextField( + controller: suffixController, + decoration: const .new(labelText: "Suffix"), + ), + ), + ], + ), + ], + ); + } +}