@devanachat/sdk 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +2 -2
  3. package/build/index.cjs.js +362 -115
  4. package/build/index.cjs.js.map +1 -1
  5. package/build/index.mjs +362 -116
  6. package/build/index.mjs.map +1 -1
  7. package/build/index.umd.js +1 -1
  8. package/build/index.umd.js.map +1 -1
  9. package/build/types/AbstractChatClient.d.ts +18 -3
  10. package/build/types/Permissions.d.ts +5 -1
  11. package/build/types/index.d.ts +2 -2
  12. package/build/types/protocol/index.d.ts +15 -3
  13. package/build/types/protocol/schemes/Message.d.ts +4 -0
  14. package/build/types/protocol/schemes/MessageEmbed.d.ts +83 -0
  15. package/build/types/protocol/schemes/commands/AckInteraction.d.ts +10 -0
  16. package/build/types/protocol/schemes/commands/CreateMessage.d.ts +7 -0
  17. package/build/types/protocol/schemes/commands/GetGifCategories.d.ts +3 -0
  18. package/build/types/protocol/schemes/commands/GetMessages.d.ts +1 -0
  19. package/build/types/protocol/schemes/commands/Interact.d.ts +5 -0
  20. package/build/types/protocol/schemes/commands/SearchGifs.d.ts +5 -0
  21. package/build/types/protocol/schemes/commands/UpdateMessage.d.ts +8 -0
  22. package/build/types/protocol/schemes/events/Error.d.ts +1 -0
  23. package/build/types/protocol/schemes/events/FoundGifs.d.ts +14 -0
  24. package/build/types/protocol/schemes/events/GifCategories.d.ts +8 -0
  25. package/build/types/protocol/schemes/events/Interacted.d.ts +4 -0
  26. package/build/types/protocol/schemes/events/InteractionResolved.d.ts +7 -0
  27. package/build/types/protocol/schemes/events/MessageUpdated.d.ts +6 -0
  28. package/build/types/protocol/schemes/events/Messages.d.ts +6 -2
  29. package/build/types/protocol/schemes/events/NewInteraction.d.ts +10 -0
  30. package/build/types/protocol/schemes/events/NewMessage.d.ts +3 -0
  31. package/build/types/state-tracker/RoomMessagesHistory.d.ts +7 -2
  32. package/build/types/state-tracker/RoomsManager.d.ts +12 -1
  33. package/build/types/state-tracker/StateSnapshot.d.ts +5 -1
  34. package/build/types/state-tracker/TopicHistoryWindow.d.ts +29 -2
  35. package/build/types/state-tracker/functions.d.ts +8 -1
  36. package/package.json +1 -1
package/build/index.mjs CHANGED
@@ -402,8 +402,116 @@ class PromiseRegistry {
402
402
  this.promises.deleteAll();
403
403
  }
404
404
  }
405
+ ;// ./src/protocol/schemes/PmParticipant.ts
406
+ let PmParticipantFlag = /*#__PURE__*/function (PmParticipantFlag) {
407
+ PmParticipantFlag[PmParticipantFlag["IgnoresRoom"] = 1] = "IgnoresRoom";
408
+ return PmParticipantFlag;
409
+ }({});
410
+ ;// ./src/state-tracker/functions.ts
411
+
412
+
413
+ /**
414
+ * @return New objects of the other roles whose priority has to move; the given roles are left intact.
415
+ */
416
+ function reorderRolesOnPriorityUpdate(allRoles, oldRole, updatedRole) {
417
+ // If the priority has changed, adjust the rest of roles
418
+ const increased = updatedRole.priority - oldRole.priority > 0;
419
+ const decreased = !increased;
420
+ const changedRoles = [];
421
+ allRoles.forEach(role => {
422
+ if (role.id === updatedRole.id) {
423
+ // Skip the updated role
424
+ return;
425
+ }
426
+ if (increased && oldRole.priority <= role.priority) {
427
+ changedRoles.push({
428
+ ...role,
429
+ priority: role.priority - 1
430
+ });
431
+ }
432
+ if (decreased && updatedRole.priority <= role.priority) {
433
+ changedRoles.push({
434
+ ...role,
435
+ priority: role.priority + 1
436
+ });
437
+ }
438
+ });
439
+ return changedRoles;
440
+ }
441
+ function extractUserFromMember(member) {
442
+ return member.user ?? member.spaceMember?.user;
443
+ }
444
+
445
+ /**
446
+ * Whether the room is a private group conversation - 3 or more participants, including the ones ignoring it.
447
+ */
448
+ function isGroupPm(room) {
449
+ return room.type === 'Pm' && (room.participants?.length ?? 0) >= 3;
450
+ }
451
+
452
+ /**
453
+ * Participants of a private conversation taking part in it: without the ones ignoring it and without the user
454
+ * `meId`. Empty for notes and for rooms of spaces.
455
+ */
456
+ function getPmPeers(room, meId) {
457
+ return getActivePmParticipants(room).filter(participant => participant.user.id !== meId);
458
+ }
459
+ function getActivePmParticipants(room) {
460
+ return (room.participants ?? []).filter(participant => !(participant.flags & PmParticipantFlag.IgnoresRoom));
461
+ }
462
+ function isSameUser(a, b) {
463
+ const keys = Object.keys(a);
464
+ if (keys.length !== Object.keys(b).length) {
465
+ return false;
466
+ }
467
+ return keys.every(key => {
468
+ const valueA = a[key];
469
+ const valueB = b[key];
470
+ if (Array.isArray(valueA) && Array.isArray(valueB)) {
471
+ return valueA.length === valueB.length && valueA.every((item, index) => item === valueB[index]);
472
+ }
473
+ return valueA === valueB;
474
+ });
475
+ }
476
+
477
+ /**
478
+ * The counter arrives as the global source of truth - only it is overwritten, and a reaction nobody holds any more
479
+ * (count 0) leaves the message.
480
+ * @return Null when the reactions stay as they are.
481
+ */
482
+ function applyReactionCounter(reactions, counter) {
483
+ const index = reactions.findIndex(reaction => reaction.type === counter.type && reaction.value === counter.value);
484
+ if (index === -1 && !counter.count) {
485
+ return null;
486
+ }
487
+ const next = [...reactions];
488
+ if (index === -1) {
489
+ next.push(counter);
490
+ } else if (counter.count) {
491
+ next[index] = counter; // In place - a pill must not jump around as its counter moves
492
+ } else {
493
+ next.splice(index, 1);
494
+ }
495
+ return next;
496
+ }
497
+ function applyToggledReaction(own, toggled) {
498
+ const {
499
+ type,
500
+ value,
501
+ isAdded
502
+ } = toggled;
503
+ const next = own.filter(reaction => reaction.type !== type || reaction.value !== value);
504
+ if (isAdded) {
505
+ next.push({
506
+ type,
507
+ value
508
+ });
509
+ }
510
+ return next;
511
+ }
405
512
  ;// ./src/state-tracker/TopicHistoryWindow.ts
406
513
 
514
+
407
515
  let WindowState = /*#__PURE__*/function (WindowState) {
408
516
  /**
409
517
  * The latest messages (those received live) are available in the history window, history has not been fetched.
@@ -781,6 +889,8 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
781
889
  this.internalState.traverseLock = false;
782
890
  this.internalState.includeMyReactions = !preview;
783
891
  this.internalState.myReactions = {};
892
+ this.internalState.includeRepliedMessages = true;
893
+ this.internalState.repliedMessages = new Map();
784
894
  this.internalState.liveLimit = 50;
785
895
  }
786
896
  createMirror() {
@@ -820,6 +930,32 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
820
930
  this.internalState.includeMyReactions = value;
821
931
  }
822
932
 
933
+ /**
934
+ * Whether the history is fetched together with the messages its messages reply to.
935
+ * Turn it off only where replies are never shown with what they reply to.
936
+ */
937
+ get includeRepliedMessages() {
938
+ return this.internalState.includeRepliedMessages;
939
+ }
940
+ set includeRepliedMessages(value) {
941
+ this.internalState.includeRepliedMessages = value;
942
+ }
943
+
944
+ /**
945
+ * The message the given one replies to: null when it replies to nothing or the replied message is gone,
946
+ * undefined when the window does not know it (replied messages are not fetched).
947
+ */
948
+ getRepliedMessage(message) {
949
+ if (!message.replyTo) {
950
+ return null;
951
+ }
952
+ const replied = this.get(message.replyTo) ?? this.internalState.repliedMessages.get(message.replyTo);
953
+ if (replied) {
954
+ return replied;
955
+ }
956
+ return this.internalState.includeRepliedMessages ? null : undefined;
957
+ }
958
+
823
959
  /**
824
960
  * Maximum number of items a window that has not been fetched yet (LIVE state) collects from the incoming
825
961
  * messages. Null for the same as {@link limit}. It keeps the windows of topics nobody looks at small;
@@ -884,14 +1020,21 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
884
1020
  const continuousFrom = Math.max(0, ...this.internalState.gaps.map(id => items.findIndex(item => item.id === id)));
885
1021
  const messages = items.slice(Math.max(continuousFrom, items.length - Math.max(limit, this.fetchLimit)));
886
1022
  const myReactions = {};
1023
+ const exportedIds = new Set(messages.map(message => message.id));
1024
+ const repliedMessages = new Map();
887
1025
  for (const message of messages) {
888
1026
  if (this.internalState.myReactions[message.id]) {
889
1027
  myReactions[message.id] = this.internalState.myReactions[message.id];
890
1028
  }
1029
+ const replied = this.getRepliedMessage(message);
1030
+ if (replied && !exportedIds.has(replied.id)) {
1031
+ repliedMessages.set(replied.id, replied);
1032
+ }
891
1033
  }
892
1034
  return {
893
1035
  messages,
894
- myReactions
1036
+ myReactions,
1037
+ repliedMessages: [...repliedMessages.values()]
895
1038
  };
896
1039
  }
897
1040
 
@@ -900,12 +1043,13 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
900
1043
  * them.
901
1044
  * @internal
902
1045
  */
903
- _restoreLatest(messages, myReactions) {
1046
+ _restoreLatest(messages, myReactions, repliedMessages) {
904
1047
  const originalState = this.state;
905
1048
  this.replaceItems(messages);
906
1049
  this.internalState.myReactions = {
907
1050
  ...myReactions
908
1051
  };
1052
+ this.storeRepliedMessages(messages, repliedMessages);
909
1053
  this.internalState.current = WindowState.LATEST;
910
1054
  this.emitChangeWithDiff(true, originalState);
911
1055
  }
@@ -956,12 +1100,14 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
956
1100
  },
957
1101
  limit: this.internalState.fetchLimit,
958
1102
  includeMyReactions: this.internalState.includeMyReactions,
1103
+ includeRepliedMessages: this.internalState.includeRepliedMessages,
959
1104
  ...criteria
960
1105
  });
961
1106
  if (result.error) {
962
1107
  throw new Error(`Cannot fetch messages: ${result.error.message}`);
963
1108
  }
964
- this.storeMyReactions(result.data.messages, result.data.myReactions);
1109
+ this.storeMyReactions(result.data.messages, result.data.myReactions ?? []);
1110
+ this.storeRepliedMessages(result.data.messages, result.data.repliedMessages ?? []);
965
1111
  return result.data.messages;
966
1112
  }
967
1113
 
@@ -977,15 +1123,63 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
977
1123
  ...this.internalState.myReactions
978
1124
  };
979
1125
  for (const message of messages) {
980
- const own = myReactions?.[message.id];
981
- if (own?.length) {
982
- next[message.id] = own;
983
- } else {
984
- delete next[message.id];
1126
+ delete next[message.id];
1127
+ }
1128
+ for (const own of myReactions) {
1129
+ if (own.reactions.length) {
1130
+ next[own.messageId] = own.reactions;
985
1131
  }
986
1132
  }
987
1133
  this.internalState.myReactions = next;
988
1134
  }
1135
+
1136
+ /**
1137
+ * The response is the truth for its replies: an original it leaves out is gone. The originals the page holds
1138
+ * itself are kept too, as the window may drop them while their replies stay.
1139
+ */
1140
+ storeRepliedMessages(incoming, repliedMessages) {
1141
+ if (!this.internalState.includeRepliedMessages) {
1142
+ return;
1143
+ }
1144
+ const fromResponse = new Map();
1145
+ for (const message of [...incoming, ...repliedMessages]) {
1146
+ fromResponse.set(message.id, message);
1147
+ }
1148
+ const stored = this.internalState.repliedMessages;
1149
+ const kept = new Map();
1150
+ for (const message of incoming) {
1151
+ const replied = message.replyTo ? fromResponse.get(message.replyTo) : undefined;
1152
+ if (replied) {
1153
+ kept.set(replied.id, replied);
1154
+ }
1155
+ }
1156
+ for (const message of this.items) {
1157
+ if (!message.replyTo || fromResponse.has(message.id) || kept.has(message.replyTo)) {
1158
+ continue;
1159
+ }
1160
+ const replied = stored.get(message.replyTo) ?? this.get(message.replyTo);
1161
+ if (replied) {
1162
+ kept.set(replied.id, replied);
1163
+ }
1164
+ }
1165
+ this.internalState.repliedMessages = kept;
1166
+ }
1167
+ emitChange(setItems) {
1168
+ if (setItems.length) {
1169
+ this.eventTarget.emit('change', {
1170
+ setItems
1171
+ });
1172
+ }
1173
+ }
1174
+ repliesTo(repliedIds) {
1175
+ const replyIds = [];
1176
+ for (const message of this.items) {
1177
+ if (message.replyTo && repliedIds.has(message.replyTo)) {
1178
+ replyIds.push(message.id);
1179
+ }
1180
+ }
1181
+ return replyIds;
1182
+ }
989
1183
  async getTopic() {
990
1184
  if (this.preview) {
991
1185
  // The tracker holds the topics of the joined rooms only
@@ -1017,7 +1211,15 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1017
1211
  return;
1018
1212
  }
1019
1213
  const limit = this.state === WindowState.LIVE && !this.internalState.traverseLock ? this.internalState.liveLimit ?? this.limit : this.limit;
1214
+ if (ev.repliedMessage && this.internalState.includeRepliedMessages) {
1215
+ this.internalState.repliedMessages.set(ev.repliedMessage.id, ev.repliedMessage);
1216
+ }
1020
1217
  const deletedItems = this.addItems([ev.message], 'tail', limit);
1218
+
1219
+ // Pruned only once the store outgrows the window, not on every message that pushes one out
1220
+ if (deletedItems.length && this.internalState.repliedMessages.size > this.length) {
1221
+ this.storeRepliedMessages([], []);
1222
+ }
1021
1223
  this.eventTarget.emit('change', deletedItems.length ? {
1022
1224
  setItems: [ev.message.id],
1023
1225
  deletedItems
@@ -1034,25 +1236,13 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1034
1236
  */
1035
1237
  _handleReactionUpdated(ev) {
1036
1238
  const message = this.get(ev.messageId);
1037
- if (!message) {
1038
- return;
1039
- }
1040
- const index = message.reactions.findIndex(reaction => reaction.type === ev.reaction.type && reaction.value === ev.reaction.value);
1041
- if (index === -1 && !ev.reaction.count) {
1042
- return;
1043
- }
1044
- const reactions = [...message.reactions];
1045
- if (index === -1) {
1046
- reactions.push(ev.reaction);
1047
- } else if (ev.reaction.count) {
1048
- reactions[index] = ev.reaction; // In place - a pill must not jump around as its counter moves
1049
- } else {
1050
- reactions.splice(index, 1);
1239
+ const reactions = message ? applyReactionCounter(message.reactions, ev.reaction) : null;
1240
+ if (reactions) {
1241
+ this.set({
1242
+ ...message,
1243
+ reactions
1244
+ });
1051
1245
  }
1052
- this.set({
1053
- ...message,
1054
- reactions
1055
- });
1056
1246
  }
1057
1247
 
1058
1248
  /**
@@ -1063,18 +1253,7 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1063
1253
  if (!this.has(ev.messageId)) {
1064
1254
  return;
1065
1255
  }
1066
- const {
1067
- type,
1068
- value,
1069
- isAdded
1070
- } = ev.reaction;
1071
- const own = (this.internalState.myReactions[ev.messageId] ?? []).filter(reaction => reaction.type !== type || reaction.value !== value);
1072
- if (isAdded) {
1073
- own.push({
1074
- type,
1075
- value
1076
- });
1077
- }
1256
+ const own = applyToggledReaction(this.internalState.myReactions[ev.messageId] ?? [], ev.reaction);
1078
1257
 
1079
1258
  // Not `{[ev.messageId]: _, ...rest}` - Babel's loose object rest drops the key when the binding is unused (babel/babel#18196)
1080
1259
  const myReactions = {
@@ -1090,13 +1269,39 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1090
1269
  });
1091
1270
  }
1092
1271
 
1272
+ /**
1273
+ * Replaces a loaded message, also where it is kept as a replied one.
1274
+ * For internal use.
1275
+ * @internal
1276
+ */
1277
+ _handleMessageUpdated(ev) {
1278
+ const {
1279
+ message
1280
+ } = ev;
1281
+ const loaded = this.has(message.id);
1282
+ const kept = this.internalState.repliedMessages.has(message.id);
1283
+ if (loaded) {
1284
+ this.set(message);
1285
+ }
1286
+ if (kept) {
1287
+ this.internalState.repliedMessages.set(message.id, message);
1288
+ }
1289
+ if (loaded || kept) {
1290
+ this.emitChange(this.repliesTo(new Set([message.id])));
1291
+ }
1292
+ }
1293
+
1093
1294
  /**
1094
1295
  * For internal use.
1095
1296
  * @internal
1096
1297
  */
1097
1298
  async _handleMessagesRedacted(ev) {
1098
1299
  const refTopicIds = this.items.filter(msg => msg.topicRef && ev.ids.includes(msg.id)).map(msg => msg.topicRef);
1300
+ const redactedOriginals = new Set(ev.ids.filter(id => this.internalState.repliedMessages.delete(id) || this.has(id)));
1099
1301
  this.delete(...ev.ids);
1302
+ if (redactedOriginals.size) {
1303
+ this.emitChange(this.repliesTo(redactedOriginals));
1304
+ }
1100
1305
  if (this.length === 0) {
1101
1306
  await this.resetToLatest();
1102
1307
  }
@@ -1220,9 +1425,9 @@ class RoomMessagesHistory {
1220
1425
  * For internal use.
1221
1426
  * @internal
1222
1427
  */
1223
- _restoreWindow(topic, messages, myReactions) {
1428
+ _restoreWindow(topic, messages, myReactions, repliedMessages) {
1224
1429
  this.createHistoryWindowForTopic(topic);
1225
- this.historyWindows.get(topic.id)._restoreLatest(messages, myReactions);
1430
+ this.historyWindows.get(topic.id)._restoreLatest(messages, myReactions, repliedMessages);
1226
1431
  }
1227
1432
 
1228
1433
  /**
@@ -1272,6 +1477,14 @@ class RoomMessagesHistory {
1272
1477
  void this.historyWindows.get(ev.location.topicId)?._handleMessagesRedacted(ev);
1273
1478
  }
1274
1479
 
1480
+ /**
1481
+ * For internal use.
1482
+ * @internal
1483
+ */
1484
+ _handleMessageUpdated(ev) {
1485
+ this.historyWindows.get(ev.message.location.topicId)?._handleMessageUpdated(ev);
1486
+ }
1487
+
1275
1488
  /**
1276
1489
  * For internal use.
1277
1490
  * @internal
@@ -1343,6 +1556,7 @@ class MessagesManager {
1343
1556
  this.tracker.client.on('NewTopic', ev => this.roomHistories.get(ev.roomId)?._handleNewTopic(ev));
1344
1557
  this.tracker.client.on('TopicDeleted', ev => this.roomHistories.get(ev.location.roomId)?._handleTopicDeleted(ev));
1345
1558
  this.tracker.client.on('NewMessage', ev => this.roomHistories.get(ev.message.location.roomId)?._handleNewMessage(ev));
1559
+ this.tracker.client.on('MessageUpdated', ev => this.roomHistories.get(ev.message.location.roomId)?._handleMessageUpdated(ev));
1346
1560
  this.tracker.client.on('MessagesRedacted', ev => this.roomHistories.get(ev.location.roomId)?._handleMessagesRedacted(ev));
1347
1561
  this.tracker.client.on('ReactionUpdated', ev => this.forEachRoomHistory(history => history._handleReactionUpdated(ev)));
1348
1562
  this.tracker.client.on('Reacted', ev => this.forEachRoomHistory(history => history._handleReacted(ev)));
@@ -1418,7 +1632,7 @@ class MessagesManager {
1418
1632
  const history = this.roomHistories.get(roomId);
1419
1633
  if (history && !history._isEphemeral) {
1420
1634
  const messages = snapshot.messages.filter(message => message.location.roomId === roomId && message.location.topicId === topic.id);
1421
- history._restoreWindow(topic, messages, snapshot.myReactions);
1635
+ history._restoreWindow(topic, messages, snapshot.myReactions, snapshot.repliedMessages);
1422
1636
  }
1423
1637
  }
1424
1638
  forEachRoomHistory(callback) {
@@ -2026,7 +2240,7 @@ let UserStatus = /*#__PURE__*/function (UserStatus) {
2026
2240
  /**
2027
2241
  * Version of the {@link StateSnapshot} format. A snapshot of any other version is rejected on import.
2028
2242
  */
2029
- const STATE_SNAPSHOT_VERSION = 2;
2243
+ const STATE_SNAPSHOT_VERSION = 3;
2030
2244
 
2031
2245
  /**
2032
2246
  * Plain, JSON-serializable copy of the state tracked by {@link ChatStateTracker}, made to restore the state at the
@@ -2136,7 +2350,7 @@ function isUserReactions(value) {
2136
2350
  return isObject(value) && Object.values(value).every(reactions => isArrayOf(reactions, isObject));
2137
2351
  }
2138
2352
  function isTopicHistory(value) {
2139
- return isObject(value) && isString(value.roomId) && isString(value.topicId) && isArrayOf(value.messages, isFullMessage) && isUserReactions(value.myReactions) && isArrayOf(value.topics, isTopic);
2353
+ return isObject(value) && isString(value.roomId) && isString(value.topicId) && isArrayOf(value.messages, isFullMessage) && isUserReactions(value.myReactions) && isArrayOf(value.repliedMessages, isFullMessage) && isArrayOf(value.topics, isTopic);
2140
2354
  }
2141
2355
  function isRoomMember(value) {
2142
2356
  return isObject(value) && (isUser(value.user) || isObject(value.spaceMember) && isUser(value.spaceMember.user));
@@ -2144,77 +2358,6 @@ function isRoomMember(value) {
2144
2358
  function isRoomMembers(value) {
2145
2359
  return isObject(value) && isString(value.roomId) && isArrayOf(value.members, isRoomMember);
2146
2360
  }
2147
- ;// ./src/protocol/schemes/PmParticipant.ts
2148
- let PmParticipantFlag = /*#__PURE__*/function (PmParticipantFlag) {
2149
- PmParticipantFlag[PmParticipantFlag["IgnoresRoom"] = 1] = "IgnoresRoom";
2150
- return PmParticipantFlag;
2151
- }({});
2152
- ;// ./src/state-tracker/functions.ts
2153
-
2154
-
2155
- /**
2156
- * @return New objects of the other roles whose priority has to move; the given roles are left intact.
2157
- */
2158
- function reorderRolesOnPriorityUpdate(allRoles, oldRole, updatedRole) {
2159
- // If the priority has changed, adjust the rest of roles
2160
- const increased = updatedRole.priority - oldRole.priority > 0;
2161
- const decreased = !increased;
2162
- const changedRoles = [];
2163
- allRoles.forEach(role => {
2164
- if (role.id === updatedRole.id) {
2165
- // Skip the updated role
2166
- return;
2167
- }
2168
- if (increased && oldRole.priority <= role.priority) {
2169
- changedRoles.push({
2170
- ...role,
2171
- priority: role.priority - 1
2172
- });
2173
- }
2174
- if (decreased && updatedRole.priority <= role.priority) {
2175
- changedRoles.push({
2176
- ...role,
2177
- priority: role.priority + 1
2178
- });
2179
- }
2180
- });
2181
- return changedRoles;
2182
- }
2183
- function extractUserFromMember(member) {
2184
- return member.user ?? member.spaceMember?.user;
2185
- }
2186
-
2187
- /**
2188
- * Whether the room is a private group conversation - 3 or more participants, including the ones ignoring it.
2189
- */
2190
- function isGroupPm(room) {
2191
- return room.type === 'Pm' && (room.participants?.length ?? 0) >= 3;
2192
- }
2193
-
2194
- /**
2195
- * Participants of a private conversation taking part in it: without the ones ignoring it and without the user
2196
- * `meId`. Empty for notes and for rooms of spaces.
2197
- */
2198
- function getPmPeers(room, meId) {
2199
- return getActivePmParticipants(room).filter(participant => participant.user.id !== meId);
2200
- }
2201
- function getActivePmParticipants(room) {
2202
- return (room.participants ?? []).filter(participant => !(participant.flags & PmParticipantFlag.IgnoresRoom));
2203
- }
2204
- function isSameUser(a, b) {
2205
- const keys = Object.keys(a);
2206
- if (keys.length !== Object.keys(b).length) {
2207
- return false;
2208
- }
2209
- return keys.every(key => {
2210
- const valueA = a[key];
2211
- const valueB = b[key];
2212
- if (Array.isArray(valueA) && Array.isArray(valueB)) {
2213
- return valueA.length === valueB.length && valueA.every((item, index) => item === valueB[index]);
2214
- }
2215
- return valueA === valueB;
2216
- });
2217
- }
2218
2361
  ;// ./src/state-tracker/RoomsManager.ts
2219
2362
 
2220
2363
 
@@ -2234,6 +2377,8 @@ class RoomsManager {
2234
2377
  membersPromises = new PromiseRegistry();
2235
2378
  topicsPromises = new PromiseRegistry();
2236
2379
  importedTopicIds = new Map();
2380
+ stickyMyReactions = new ObservableIndexedObjectCollection('messageId');
2381
+ stickyMyReactionsPromises = new PromiseRegistry();
2237
2382
  constructor(tracker) {
2238
2383
  this.tracker = tracker;
2239
2384
  this.messages = new MessagesManager(tracker);
@@ -2241,6 +2386,9 @@ class RoomsManager {
2241
2386
  this.typing = new TypingManager(tracker);
2242
2387
  this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
2243
2388
  this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
2389
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
2390
+ this.tracker.client.on('ReactionUpdated', ev => this.handleReactionUpdated(ev));
2391
+ this.tracker.client.on('Reacted', ev => this.handleReacted(ev));
2244
2392
  this.tracker.client.on('NewTopic', ev => this.handleNewTopic(ev));
2245
2393
  this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
2246
2394
  this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
@@ -2279,6 +2427,34 @@ class RoomsManager {
2279
2427
  return this.members.get(roomId);
2280
2428
  }
2281
2429
 
2430
+ /**
2431
+ * Get the reactions of the connected user on sticky messages, keyed by message id. A sticky message comes with its
2432
+ * topic, outside of the message history, so the reactions of the given one are fetched once and then follow
2433
+ * the reactions of the user.
2434
+ */
2435
+ async getStickyMyReactions(location, messageId) {
2436
+ if (this.stickyMyReactionsPromises.notExist(messageId)) {
2437
+ this.stickyMyReactionsPromises.registerByFunction(async () => {
2438
+ const result = await this.tracker.client.send('GetMessages', {
2439
+ location,
2440
+ around: messageId,
2441
+ limit: 1,
2442
+ includeMyReactions: true
2443
+ });
2444
+ if (result.error) {
2445
+ throw result.error;
2446
+ }
2447
+ const own = result.data.myReactions?.find(item => item.messageId === messageId);
2448
+ this.stickyMyReactions.set({
2449
+ messageId,
2450
+ reactions: own?.reactions ?? []
2451
+ });
2452
+ }, messageId);
2453
+ }
2454
+ await this.stickyMyReactionsPromises.get(messageId);
2455
+ return this.stickyMyReactions;
2456
+ }
2457
+
2282
2458
  /**
2283
2459
  * Get a room member representing the current user.
2284
2460
  */
@@ -2404,6 +2580,7 @@ class RoomsManager {
2404
2580
  topicId,
2405
2581
  messages: latest.messages.map(messageWithoutPresence),
2406
2582
  myReactions: latest.myReactions,
2583
+ repliedMessages: latest.repliedMessages.map(messageWithoutPresence),
2407
2584
  topics: Array.from(topicIds).filter(id => topics?.has(id)).map(id => topics.get(id))
2408
2585
  });
2409
2586
  }
@@ -2680,6 +2857,8 @@ class RoomsManager {
2680
2857
  // so bound views refresh in place without blanking.
2681
2858
  this.membersPromises.forgetAll();
2682
2859
  this.topicsPromises.forgetAll();
2860
+ // Reactions could change meanwhile, and missed changes never arrive
2861
+ this.stickyMyReactionsPromises.forgetAll();
2683
2862
 
2684
2863
  // Upsert surviving/new rooms from the authoritative snapshot.
2685
2864
  this.addJoinedRooms(...ev.state.rooms);
@@ -2722,6 +2901,10 @@ class RoomsManager {
2722
2901
  this.list.set(...newRooms);
2723
2902
  }
2724
2903
  handleNewMessage(ev) {
2904
+ // Shown to one user and never stored, so it is neither counted nor the last message of the topic
2905
+ if (ev.message.type === 'Ephemeral') {
2906
+ return;
2907
+ }
2725
2908
  const topics = this.topics.get(ev.message.location.roomId);
2726
2909
  const topic = topics?.get(ev.message.location.topicId);
2727
2910
  if (!topic) {
@@ -2736,7 +2919,59 @@ class RoomsManager {
2736
2919
  topics.set(newTopic);
2737
2920
  this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
2738
2921
  }
2922
+ handleMessageUpdated(ev) {
2923
+ const topics = this.topics.get(ev.message.location.roomId);
2924
+ const refTopic = ev.message.topicRef ? topics?.get(ev.message.topicRef) : undefined;
2925
+ if (refTopic?.refMessage?.id === ev.message.id) {
2926
+ topics.set({
2927
+ ...refTopic,
2928
+ refMessage: ev.message
2929
+ });
2930
+ }
2931
+ const topic = topics?.get(ev.message.location.topicId);
2932
+ const isLast = topic?.lastMessage?.id === ev.message.id;
2933
+ const isSticky = topic?.stickyMessage?.id === ev.message.id;
2934
+ if (!topic || !isLast && !isSticky) {
2935
+ return;
2936
+ }
2937
+ const newTopic = {
2938
+ ...topic,
2939
+ lastMessage: isLast ? ev.message : topic.lastMessage,
2940
+ stickyMessage: isSticky ? ev.message : topic.stickyMessage
2941
+ };
2942
+ topics.set(newTopic);
2943
+ this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
2944
+ }
2945
+ handleReactionUpdated(ev) {
2946
+ for (const [roomId, topics] of this.topics.items) {
2947
+ for (const topic of topics.items) {
2948
+ const reactions = topic.stickyMessage?.id === ev.messageId ? applyReactionCounter(topic.stickyMessage.reactions, ev.reaction) : null;
2949
+ if (reactions) {
2950
+ const newTopic = {
2951
+ ...topic,
2952
+ stickyMessage: {
2953
+ ...topic.stickyMessage,
2954
+ reactions
2955
+ }
2956
+ };
2957
+ topics.set(newTopic);
2958
+ this.updatePmDefaultTopic(roomId, newTopic);
2959
+ }
2960
+ }
2961
+ }
2962
+ }
2963
+ handleReacted(ev) {
2964
+ const own = this.stickyMyReactions.get(ev.messageId);
2965
+ if (own) {
2966
+ this.stickyMyReactions.set({
2967
+ messageId: own.messageId,
2968
+ reactions: applyToggledReaction(own.reactions, ev.reaction)
2969
+ });
2970
+ }
2971
+ }
2739
2972
  async handleMessagesRedacted(ev) {
2973
+ this.stickyMyReactions.delete(...ev.ids);
2974
+
2740
2975
  // Remove redacted messages from topic and update metadata
2741
2976
  const topics = this.topics.get(ev.location.roomId);
2742
2977
  const topic = topics?.get(ev.location.topicId);
@@ -3204,7 +3439,7 @@ class Permissions {
3204
3439
  value: 1 << 18,
3205
3440
  maxLayer: Layer.Room
3206
3441
  },
3207
- RedactMessages: {
3442
+ ManageMessages: {
3208
3443
  value: 1 << 19,
3209
3444
  maxLayer: Layer.Topic
3210
3445
  },
@@ -3243,6 +3478,10 @@ class Permissions {
3243
3478
  SendAttachments: {
3244
3479
  value: 1 << 28,
3245
3480
  maxLayer: Layer.Topic
3481
+ },
3482
+ EditMessages: {
3483
+ value: 1 << 29,
3484
+ maxLayer: Layer.Topic
3246
3485
  }
3247
3486
  };
3248
3487
  static getNames() {
@@ -4425,6 +4664,7 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4425
4664
  ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
4426
4665
  ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
4427
4666
  ErrorCode["MessageNotFound"] = "MessageNotFoundException";
4667
+ ErrorCode["ReactionExistsAlready"] = "ReactionExistsAlreadyException";
4428
4668
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4429
4669
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
4430
4670
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
@@ -4432,6 +4672,12 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4432
4672
  ErrorCode["UserNotFound"] = "UserNotFoundException";
4433
4673
  return ErrorCode;
4434
4674
  }({});
4675
+ ;// ./src/protocol/schemes/MessageEmbed.ts
4676
+ let MessageEmbedFlag = /*#__PURE__*/function (MessageEmbedFlag) {
4677
+ MessageEmbedFlag[MessageEmbedFlag["HideContent"] = 1] = "HideContent";
4678
+ MessageEmbedFlag[MessageEmbedFlag["Suppressed"] = 2] = "Suppressed";
4679
+ return MessageEmbedFlag;
4680
+ }({});
4435
4681
  ;// ./src/protocol/schemes/Role.ts
4436
4682
  /**
4437
4683
  * Bit flags of a role, stored in {@link Role.flags}.
@@ -4566,6 +4812,6 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
4566
4812
 
4567
4813
 
4568
4814
 
4569
- export { AbstractRestClient, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, PmParticipantFlag, RoleFlag, STATE_SNAPSHOT_VERSION, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, TYPING_INTERVAL_MS, TYPING_TIMEOUT_MS, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember, getPmPeers, isGroupPm };
4815
+ export { AbstractRestClient, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, MessageEmbedFlag, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, PmParticipantFlag, RoleFlag, STATE_SNAPSHOT_VERSION, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, TYPING_INTERVAL_MS, TYPING_TIMEOUT_MS, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember, getPmPeers, isGroupPm };
4570
4816
 
4571
4817
  //# sourceMappingURL=index.mjs.map