From 0e6188582193cb35a5a9cfa062dde058c2da4a8c Mon Sep 17 00:00:00 2001 From: Christian Pauly Date: Thu, 23 Apr 2020 09:46:10 +0000 Subject: [PATCH] [User] Format displayname --- lib/src/user.dart | 25 +++++++++++++++++++++---- test/room_test.dart | 2 +- test/user_test.dart | 6 +++--- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/lib/src/user.dart b/lib/src/user.dart index af837378..4d4216ea 100644 --- a/lib/src/user.dart +++ b/lib/src/user.dart @@ -101,10 +101,27 @@ class User extends Event { : MxContent(''); /// Returns the displayname or the local part of the Matrix ID if the user - /// has no displayname. - String calcDisplayname() => (displayName == null || displayName.isEmpty) - ? (stateKey != null ? stateKey.localpart : 'Unknown User') - : displayName; + /// has no displayname. If [formatLocalpart] is true, then the localpart will + /// be formatted in the way, that all "_" characters are becomming white spaces and + /// the first character of each word becomes uppercase. + String calcDisplayname({bool formatLocalpart = true}) { + if (displayName?.isNotEmpty ?? false) { + return displayName; + } + if (stateKey != null) { + if (!formatLocalpart) { + return stateKey.localpart; + } + var words = stateKey.localpart.replaceAll('_', ' ').split(' '); + for (var i = 0; i < words.length; i++) { + if (words[i].isNotEmpty) { + words[i] = words[i][0].toUpperCase() + words[i].substring(1); + } + } + return words.join(' '); + } + return 'Unknown User'; + } /// Call the Matrix API to kick this user from this room. Future kick() => room.kick(id); diff --git a/test/room_test.dart b/test/room_test.dart index 609b2bd2..8ee9b8b8 100644 --- a/test/room_test.dart +++ b/test/room_test.dart @@ -109,7 +109,7 @@ void main() { expect(room.mJoinedMemberCount, notificationCount); expect(room.mInvitedMemberCount, notificationCount); expect(room.mHeroes, heroes); - expect(room.displayname, 'alice, bob, charley'); + expect(room.displayname, 'Alice, Bob, Charley'); expect(room.getState('m.room.join_rules').content['join_rule'], 'public'); expect(room.roomAccountData['com.test.foo'].content['foo'], 'bar'); diff --git a/test/user_test.dart b/test/user_test.dart index 081dae50..bc5b1ae3 100644 --- a/test/user_test.dart +++ b/test/user_test.dart @@ -61,10 +61,10 @@ void main() { test('calcDisplayname', () async { final user1 = User('@alice:example.com'); final user2 = User('@SuperAlice:example.com'); - final user3 = User('@alice:example.com'); - expect(user1.calcDisplayname(), 'alice'); + final user3 = User('@alice_mep:example.com'); + expect(user1.calcDisplayname(), 'Alice'); expect(user2.calcDisplayname(), 'SuperAlice'); - expect(user3.calcDisplayname(), 'alice'); + expect(user3.calcDisplayname(), 'Alice Mep'); }); }); }