Merge branch 'luke/fix-join-part-collapsing-causality' of github.com:matrix-org/matrix-react-sdk into luke/fix-join-part-collapsing-causality

Conflicts:
	src/components/views/elements/MemberEventListSummary.js
This commit is contained in:
Luke Barnard 2017-01-24 14:17:11 +00:00
commit d690677bde
3 changed files with 759 additions and 141 deletions

View file

@ -46,111 +46,55 @@ module.exports = React.createClass({
}; };
}, },
shouldComponentUpdate: function(nextProps, nextState) {
// Update if
// - The number of summarised events has changed
// - or if the summary is currently expanded
// - or if the summary is about to toggle to become collapsed
// - or if there are fewEvents, meaning the child eventTiles are shown as-is
return (
nextProps.events.length !== this.props.events.length ||
this.state.expanded || nextState.expanded ||
nextProps.events.length < this.props.threshold
);
},
_toggleSummary: function() { _toggleSummary: function() {
this.setState({ this.setState({
expanded: !this.state.expanded, expanded: !this.state.expanded,
}); });
}, },
_renderNameList: function(users) { /**
if (users.length === 0) { * Render the JSX for users aggregated by their transition sequences (`eventAggregates`) where
return null; * the sequences are ordered by `orderedTransitionSequences`.
} * @param {object[]} eventAggregates a map of transition sequence to array of user display names
let originalNumber = users.length; * or user IDs.
* @param {string[]} orderedTransitionSequences an array which is some ordering of
users = users.slice(0, this.props.summaryLength); * `Object.keys(eventAggregates)`.
* @returns {ReactElement} a single <span> containing the textual summary of the aggregated
let remaining = originalNumber - this.props.summaryLength; * events that occurred.
if (remaining < 0) { */
remaining = 0; _renderSummary: function(eventAggregates, orderedTransitionSequences) {
} let summaries = orderedTransitionSequences.map((transitions) => {
let other = " other" + (remaining > 1 ? "s" : ""); let userNames = eventAggregates[transitions];
let nameList = this._renderNameList(userNames);
return this._renderCommaSeparatedList(users, remaining) + (remaining ? ' and ' + remaining + other : ''); let plural = userNames.length > 1;
},
// Test whether the first n items repeat for the duration
// e.g. [1,2,3,4,1,2,3] would resolve true for n = 4
_isRepeatedSequence: function(transitions, n) {
let count = 0;
for (let i = 0; i < transitions.length; i++) {
if (transitions[i % n] !== transitions[i]) {
return null;
}
}
return true;
},
_renderCommaSeparatedList(items, disableAnd) {
if (disableAnd) {
return items.join(', ');
}
if (items.length === 0) {
return "";
} else if (items.length === 1) {
return items[0];
} else {
let last = items.pop();
return items.join(', ') + ' and ' + last;
}
},
_getDescriptionForTransition(t, plural) {
let beConjugated = plural ? "were" : "was";
let invitation = plural ? "invitations" : "an invitation";
switch (t) {
case 'joined': return "joined";
case 'left': return "left";
case 'invite_reject': return "rejected " + invitation;
case 'invite_withdrawal': return "withdrew " + invitation;
case 'invited': return beConjugated + " invited";
case 'banned': return beConjugated + " banned";
case 'unbanned': return beConjugated + " unbanned";
case 'kicked': return beConjugated + " kicked";
}
return null;
},
_renderSummary: function(eventAggregates) {
let summaries = Object.keys(eventAggregates).map((transitions) => {
let nameList = this._renderNameList(eventAggregates[transitions]);
let repeats = 1;
let repeatExtra = 0;
let splitTransitions = transitions.split(','); let splitTransitions = transitions.split(',');
let describedTransitions = splitTransitions;
let plural = eventAggregates[transitions].length > 1;
for (let modulus = 1; modulus <= 2; modulus++) { // Some neighbouring transitions are common, so canonicalise some into "pair" transitions
// Sequences that are repeating through modulus transitions will be truncated let canonicalTransitions = this._getCanonicalTransitions(splitTransitions);
if (this._isRepeatedSequence(describedTransitions, modulus)) { // Transform into consecutive repetitions of the same transition (like 5 consecutive 'joined_and_left's)
// Extra repeating sequence on the end that should be treated separately let truncatedTransitions = this._getTruncatedTransitions(canonicalTransitions);
// so as to avoid j,l,j,l,j => "... joined and left 2.5 times"
repeatExtra = describedTransitions.length % modulus;
repeats = (describedTransitions.length - repeatExtra) / modulus; let descs = truncatedTransitions.map((t) => {
describedTransitions = describedTransitions.slice(0, modulus); return this._getDescriptionForTransition(t.transitionType, plural, t.repeats);
break;
}
}
let numberOfTimes = repeats > 1 ? " " + repeats + " times" : "";
let descs = describedTransitions.map((t) => {
return this._getDescriptionForTransition(t, plural);
});
let afterRepeatDescs = splitTransitions.slice(splitTransitions.length - repeatExtra).map((t) => {
return this._getDescriptionForTransition(t, plural);
}); });
let desc = this._renderCommaSeparatedList(descs); let desc = this._renderCommaSeparatedList(descs);
let afterRepeatDesc = this._renderCommaSeparatedList(afterRepeatDescs);
return nameList + " " + desc + numberOfTimes + (afterRepeatDesc ? " and then " + afterRepeatDesc : ""); return nameList + " " + desc;
}); });
if (!summaries) { if (!summaries) {
@ -164,6 +108,151 @@ module.exports = React.createClass({
); );
}, },
/**
* @param {string[]} users an array of user display names or user IDs.
* @returns {string} a comma-separated list that ends with "and [n] others" if there are
* more items in `users` than `this.props.summaryLength`, which is the number of names
* included before "and [n] others".
*/
_renderNameList: function(users) {
return this._renderCommaSeparatedList(users, this.props.summaryLength);
},
/**
* Canonicalise an array of transitions into an array of transitions and how many times
* they are repeated consecutively.
*
* An array of 123 "joined_and_left" transitions, would result in:
* ```
* [{
* transitionType: "joined_and_left"
* repeats: 123
* }, ... ]
* ```
* @param {string[]} transitions the array of transitions to transform.
* @returns {object[]} an array of truncated transitions.
*/
_getCanonicalTransitions: function(transitions) {
let modMap = {
'joined' : {
'after' : 'left',
'newTransition' : 'joined_and_left',
},
'left' : {
'after' : 'joined',
'newTransition' : 'left_and_joined',
},
// $currentTransition : {
// 'after' : $nextTransition,
// 'newTransition' : 'new_transition_type',
// },
};
const res = [];
for (let i = 0; i < transitions.length; i++) {
let t = transitions[i];
let t2 = transitions[i + 1];
let transition = t;
if (i < transitions.length - 1 && modMap[t] && modMap[t].after === t2) {
transition = modMap[t].newTransition;
i++;
}
res.push(transition);
}
return res;
},
/**
* Transform an array of transitions into an array of transitions and how many times
* they are repeated consecutively.
*
* An array of 123 "joined_and_left" transitions, would result in:
* ```
* [{
* transitionType: "joined_and_left"
* repeats: 123
* }, ... ]
* ```
* @param {string[]} transitions the array of transitions to transform.
* @returns {object[]} an array of truncated transitions.
*/
_getTruncatedTransitions: function(transitions) {
let res = [];
for (let i = 0; i < transitions.length; i++) {
if (res.length > 0 && res[res.length - 1].transitionType === transitions[i]) {
res[res.length - 1].repeats += 1;
} else {
res.push({
transitionType: transitions[i],
repeats: 1,
});
}
}
return res;
},
/**
* For a certain transition, t, describe what happened to the users that
* underwent the transition.
* @param {string} t the transition type.
* @param {boolean} plural whether there were multiple users undergoing the same transition.
* @param {number} repeats the number of times the transition was repeated in a row.
* @returns {string} the written English equivalent of the transition.
*/
_getDescriptionForTransition(t, plural, repeats) {
let beConjugated = plural ? "were" : "was";
let invitation = "their invitation" + (plural || (repeats > 1) ? "s" : "");
let res = null;
let map = {
"joined": "joined",
"left": "left",
"joined_and_left": "joined and left",
"left_and_joined": "left and rejoined",
"invite_reject": "rejected " + invitation,
"invite_withdrawal": "had " + invitation + " withdrawn",
"invited": beConjugated + " invited",
"banned": beConjugated + " banned",
"unbanned": beConjugated + " unbanned",
"kicked": beConjugated + " kicked",
};
if (Object.keys(map).includes(t)) {
res = map[t] + (repeats > 1 ? " " + repeats + " times" : "" );
}
return res;
},
/**
* Constructs a written English string representing `items`, with an optional limit on the number
* of items included in the result. If specified and if the length of `items` is greater than the
* limit, the string "and n others" will be appended onto the result.
* If `items` is empty, returns the empty string. If there is only one item, return it.
* @param {string[]} items the items to construct a string from.
* @param {number?} itemLimit the number by which to limit the list.
* @returns {string} a string constructed by joining `items` with a comma between each
* item, but with the last item appended as " and [lastItem]".
*/
_renderCommaSeparatedList(items, itemLimit) {
const remaining = itemLimit === undefined ? 0 : Math.max(items.length - itemLimit, 0);
if (items.length === 0) {
return "";
} else if (items.length === 1) {
return items[0];
} else if (remaining) {
items = items.slice(0, itemLimit);
const other = " other" + (remaining > 1 ? "s" : "");
return items.join(', ') + ' and ' + remaining + other;
} else {
let last = items.pop();
return items.join(', ') + ' and ' + last;
}
},
_renderAvatars: function(roomMembers) { _renderAvatars: function(roomMembers) {
let avatars = roomMembers.slice(0, this.props.avatarsMaxLength).map((m) => { let avatars = roomMembers.slice(0, this.props.avatarsMaxLength).map((m) => {
return ( return (
@ -178,32 +267,31 @@ module.exports = React.createClass({
); );
}, },
shouldComponentUpdate: function(nextProps, nextState) { _getTransitionSequence: function(events) {
// Update if return events.map(this._getTransition);
// - The number of summarised events has changed
// - or if the summary is currently expanded
// - or if the summary is about to toggle to become collapsed
// - or if there are fewEvents, meaning the child eventTiles are shown as-is
return (
nextProps.events.length !== this.props.events.length ||
this.state.expanded || nextState.expanded ||
nextProps.events.length < this.props.threshold
);
}, },
/**
* Enumerate a given membership event, `e`, where `getContent().membership` has
* changed for each transition allowed by the Matrix protocol. This attempts to
* enumerate the membership changes that occur in `../../../TextForEvent.js`.
* @param {MatrixEvent} e the membership change event to enumerate.
* @returns {string?} the transition type given to this event. This defaults to `null`
* if a transition is not recognised.
*/
_getTransition: function(e) { _getTransition: function(e) {
switch (e.getContent().membership) { switch (e.mxEvent.getContent().membership) {
case 'invite': return 'invited'; case 'invite': return 'invited';
case 'ban': return 'banned'; case 'ban': return 'banned';
case 'join': return 'joined'; case 'join': return 'joined';
case 'leave': case 'leave':
if (e.getSender() === e.getStateKey()) { if (e.mxEvent.getSender() === e.mxEvent.getStateKey()) {
switch (e.getPrevContent().membership) { switch (e.mxEvent.getPrevContent().membership) {
case 'invite': return 'invite_reject'; case 'invite': return 'invite_reject';
default: return 'left'; default: return 'left';
} }
} }
switch (e.getPrevContent().membership) { switch (e.mxEvent.getPrevContent().membership) {
case 'invite': return 'invite_withdrawal'; case 'invite': return 'invite_withdrawal';
case 'ban': return 'unbanned'; case 'ban': return 'unbanned';
case 'join': return 'kicked'; case 'join': return 'kicked';
@ -213,8 +301,44 @@ module.exports = React.createClass({
} }
}, },
_getTransitionSequence: function(events) { _getAggregate: function(userEvents) {
return events.map(this._getTransition); // A map of aggregate type to arrays of display names. Each aggregate type
// is a comma-delimited string of transitions, e.g. "joined,left,kicked".
// The array of display names is the array of users who went through that
// sequence during eventsToRender.
let aggregate = {
// $aggregateType : []:string
};
// A map of aggregate types to the indices that order them (the index of
// the first event for a given transition sequence)
let aggregateIndices = {
// $aggregateType : int
};
let users = Object.keys(userEvents);
users.forEach(
(userId) => {
let firstEvent = userEvents[userId][0];
let displayName = firstEvent.displayName;
let seq = this._getTransitionSequence(userEvents[userId]);
if (!aggregate[seq]) {
aggregate[seq] = [];
aggregateIndices[seq] = -1;
}
aggregate[seq].push(displayName);
if (aggregateIndices[seq] === -1 || firstEvent.index < aggregateIndices[seq]) {
aggregateIndices[seq] = firstEvent.index;
}
}
);
return {
names: aggregate,
indices: aggregateIndices,
};
}, },
render: function() { render: function() {
@ -235,51 +359,40 @@ module.exports = React.createClass({
); );
} }
// Map user IDs to all of the user's member events in eventsToRender // Map user IDs to an array of objects:
let userEvents = { let userEvents = {
// $userId : [] // $userId : [{
// // The original event
// mxEvent: e,
// // The display name of the user (if not, then user ID)
// displayName: e.target.name || userId,
// // The original index of the event in this.props.events
// index: index,
// }]
}; };
// Array of userIds ordered by the same ordering as the first event of each user
let users = [];
eventsToRender.forEach((e) => { let avatarMembers = [];
eventsToRender.forEach((e, index) => {
const userId = e.getStateKey(); const userId = e.getStateKey();
// Initialise a user's events // Initialise a user's events
if (!userEvents[userId]) { if (!userEvents[userId]) {
userEvents[userId] = []; userEvents[userId] = [];
users.push(userId); avatarMembers.push(e.target);
} }
userEvents[userId].push(e); userEvents[userId].push({
mxEvent: e,
displayName: e.target.name || userId,
index: index,
});
}); });
// A map of agregate type to arrays of display names. Each aggregate type let aggregate = this._getAggregate(userEvents);
// is a comma-delimited string of transitions, e.g. "joined,left,kicked".
// The array of display names is the array of users who went through that
// sequence during eventsToRender.
let aggregate = {
// $aggregateType : []:string
};
let avatarMembers = [];
users.forEach( // Sort types by order of lowest event index within sequence
(userId) => { let orderedTransitionSequences = Object.keys(aggregate.names).sort((seq1, seq2) => aggregate.indices[seq1] > aggregate.indices[seq2]);
let displayName = userEvents[userId][0].getContent().displayname || userId;
let seq = this._getTransitionSequence(userEvents[userId]);
if (!aggregate[seq]) {
aggregate[seq] = [];
}
// Assumes display names are unique
if (aggregate[seq].indexOf(displayName) === -1) {
aggregate[seq].push(displayName);
}
avatarMembers.push(userEvents[userId][0].target);
}
);
let avatars = this._renderAvatars(avatarMembers); let avatars = this._renderAvatars(avatarMembers);
let summary = this._renderSummary(aggregate); let summary = this._renderSummary(aggregate.names, orderedTransitionSequences);
let toggleButton = ( let toggleButton = (
<a className="mx_MemberEventListSummary_toggle" onClick={this._toggleSummary}> <a className="mx_MemberEventListSummary_toggle" onClick={this._toggleSummary}>
{expanded ? 'collapse' : 'expand'} {expanded ? 'collapse' : 'expand'}

View file

@ -0,0 +1,495 @@
const expect = require('expect');
const React = require('react');
const ReactDOM = require("react-dom");
const ReactTestUtils = require('react-addons-test-utils');
const sdk = require('matrix-react-sdk');
const MemberEventListSummary = sdk.getComponent('views.elements.MemberEventListSummary');
const jssdk = require('matrix-js-sdk');
const MatrixEvent = jssdk.MatrixEvent;
const testUtils = require('../../../test-utils');
describe.only('MemberEventListSummary', function() {
let sandbox;
// Generate dummy event tiles for use in simulating an expanded MELS
const generateTiles = (events) => {
return events.map((e) => {
return (
<div key={e.getId()} className="event_tile">
Expanded membership
</div>
);
});
};
/**
* Generates a membership event with the target of the event set as a mocked RoomMember based
* on `parameters.userId`.
* @param {string} eventId the ID of the event.
* @param {object} parameters the parameters to use to create the event.
* @param {string} parameters.membership the membership to assign to `content.membership`
* @param {string} parameters.userId the state key and target userId of the event. If
* `parameters.senderId` is not specified, this is also used as the event sender.
* @param {string} parameters.prevMembership the membership to assign to
* `prev_content.membership`.
* @param {string} parameters.senderId the user ID of the sender of the event. Optional.
* Defaults to `parameters.userId`.
* @returns {MatrixEvent} the event created.
*/
const generateMembershipEvent = (eventId, parameters) => {
let e = testUtils.mkMembership({
event: true,
user: parameters.senderId || parameters.userId,
skey: parameters.userId,
mship: parameters.membership,
prevMship: parameters.prevMembership,
target : {
name: parameters.userId.match(/@([^:]*):/)[1], // Use localpart as display name
userId: parameters.userId,
getAvatarUrl: () => {
return "avatar.jpeg";
},
},
});
// Override random event ID
e.event.event_id = eventId;
return e;
};
// Generate mock MatrixEvents from the array of parameters
const generateEvents = (parameters) => {
const res = [];
for (let i = 0; i < parameters.length; i++) {
res.push(generateMembershipEvent(`event${i}`, parameters[i]));
}
return res;
};
// Generate the same sequence of `events` for `n` users, where each user ID
// is created by replacing the first "$" in userIdTemplate with `i` for
// `i = 0 .. n`.
const generateEventsForUsers = (userIdTemplate, n, events) => {
let eventsForUsers = [];
let userId = "";
for (let i = 0; i < n; i++) {
userId = userIdTemplate.replace('$', i);
events.forEach((e) => {
e.userId = userId;
});
eventsForUsers = eventsForUsers.concat(generateEvents(events));
}
return eventsForUsers;
};
beforeEach(function() {
testUtils.beforeEach(this);
sandbox = testUtils.stubClient();
});
afterEach(function() {
sandbox.restore();
});
it('renders expanded events if there are less than props.threshold', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const renderer = ReactTestUtils.createRenderer();
renderer.render(<MemberEventListSummary {...props} />);
const result = renderer.getRenderOutput();
expect(result.type).toBe('div');
expect(result.props.children).toEqual([
<div className="event_tile" key="event0">Expanded membership</div>,
]);
});
it('renders expanded events if there are less than props.threshold', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const renderer = ReactTestUtils.createRenderer();
renderer.render(<MemberEventListSummary {...props} />);
const result = renderer.getRenderOutput();
expect(result.type).toBe('div');
expect(result.props.children).toEqual([
<div className="event_tile" key="event0">Expanded membership</div>,
<div className="event_tile" key="event1">Expanded membership</div>,
]);
});
it('renders collapsed events if events.length = props.threshold', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe("user_1 joined and left and joined");
});
it('truncates long join,leave repetitions', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe("user_1 joined and left 7 times");
});
it('truncates long join,leave repetitions inbetween other events', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", prevMembership: "ban", membership: "leave", senderId: "@some_other_user:some.domain"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "invite", senderId: "@some_other_user:some.domain"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe("user_1 was unbanned, joined and left 7 times and was invited");
});
it('truncates multiple sequences of repetitions with other events inbetween', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", prevMembership: "ban", membership: "leave", senderId: "@some_other_user:some.domain"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "ban", senderId: "@some_other_user:some.domain"},
{userId : "@user_1:some.domain", prevMembership: "ban", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "invite", senderId: "@some_other_user:some.domain"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe("user_1 was unbanned, joined and left 2 times, was banned, joined and left 3 times and was invited");
});
it('handles multiple users following the same sequence of memberships', function() {
const events = generateEvents([
// user_1
{userId : "@user_1:some.domain", prevMembership: "ban", membership: "leave", senderId: "@some_other_user:some.domain"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "ban", senderId: "@some_other_user:some.domain"},
// user_2
{userId : "@user_2:some.domain", prevMembership: "ban", membership: "leave", senderId: "@some_other_user:some.domain"},
{userId : "@user_2:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_2:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_2:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_2:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_2:some.domain", prevMembership: "leave", membership: "ban", senderId: "@some_other_user:some.domain"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe("user_1 and 1 other were unbanned, joined and left 2 times and were banned");
});
it('handles many users following the same sequence of memberships', function() {
const events = generateEventsForUsers("@user_$:some.domain", 20, [
{prevMembership: "ban", membership: "leave", senderId: "@some_other_user:some.domain"},
{prevMembership: "leave", membership: "join"},
{prevMembership: "join", membership: "leave"},
{prevMembership: "leave", membership: "join"},
{prevMembership: "join", membership: "leave"},
{prevMembership: "leave", membership: "ban", senderId: "@some_other_user:some.domain"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe("user_0 and 19 others were unbanned, joined and left 2 times and were banned");
});
it('correctly orders sequences of transitions by the order of their first event', function() {
const events = generateEvents([
{userId : "@user_2:some.domain", prevMembership: "ban", membership: "leave", senderId: "@some_other_user:some.domain"},
{userId : "@user_1:some.domain", prevMembership: "ban", membership: "leave", senderId: "@some_other_user:some.domain"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "leave", membership: "ban", senderId: "@some_other_user:some.domain"},
{userId : "@user_2:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_2:some.domain", prevMembership: "join", membership: "leave"},
{userId : "@user_2:some.domain", prevMembership: "leave", membership: "join"},
{userId : "@user_2:some.domain", prevMembership: "join", membership: "leave"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe(
"user_2 was unbanned and joined and left 2 times, user_1 was unbanned, joined and left 2 times and was banned"
);
});
it('correctly identifies transitions', function() {
const events = generateEvents([
// invited
{userId : "@user_1:some.domain", membership: "invite"},
// banned
{userId : "@user_1:some.domain", membership: "ban"},
// joined
{userId : "@user_1:some.domain", membership: "join"},
// invite_reject
{userId : "@user_1:some.domain", prevMembership: "invite", membership: "leave"},
// left
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave"},
// invite_withdrawal
{userId : "@user_1:some.domain", prevMembership: "invite", membership: "leave", senderId: "@some_other_user:some.domain"},
// unbanned
{userId : "@user_1:some.domain", prevMembership: "ban", membership: "leave", senderId: "@some_other_user:some.domain"},
// kicked
{userId : "@user_1:some.domain", prevMembership: "join", membership: "leave", senderId: "@some_other_user:some.domain"},
// default = left
{userId : "@user_1:some.domain", prevMembership: "????", membership: "leave", senderId: "@some_other_user:some.domain"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe(
"user_1 was invited, was banned, joined, rejected their invitation, left, had their invitation withdrawn, was unbanned, was kicked and left"
);
});
it('handles invitation plurals correctly when there are multiple users', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", prevMembership: "invite", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "invite", membership: "leave", senderId: "@some_other_user:some.domain"},
{userId : "@user_2:some.domain", prevMembership: "invite", membership: "leave"},
{userId : "@user_2:some.domain", prevMembership: "invite", membership: "leave", senderId: "@some_other_user:some.domain"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe(
"user_1 and 1 other rejected their invitations and had their invitations withdrawn"
);
});
it('handles invitation plurals correctly when there are multiple invites', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", prevMembership: "invite", membership: "leave"},
{userId : "@user_1:some.domain", prevMembership: "invite", membership: "leave"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 1,
avatarsMaxLength : 5,
threshold : 1, // threshold = 1 to force collapse
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe(
"user_1 rejected their invitations 2 times"
);
});
it('handles a summary length = 2, with no "others"', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", membership: "join"},
{userId : "@user_1:some.domain", membership: "join"},
{userId : "@user_2:some.domain", membership: "join"},
{userId : "@user_2:some.domain", membership: "join"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 2,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe(
"user_1 and user_2 joined 2 times"
);
});
it('handles a summary length = 2, with 1 "other"', function() {
const events = generateEvents([
{userId : "@user_1:some.domain", membership: "join"},
{userId : "@user_2:some.domain", membership: "join"},
{userId : "@user_3:some.domain", membership: "join"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 2,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe(
"user_1, user_2 and 1 other joined"
);
});
it('handles a summary length = 2, with many "others"', function() {
const events = generateEventsForUsers("@user_$:some.domain", 20, [
{membership: "join"},
]);
const props = {
events : events,
children : generateTiles(events),
summaryLength : 2,
avatarsMaxLength : 5,
threshold : 3,
};
const instance = ReactTestUtils.renderIntoDocument(<MemberEventListSummary {...props} />);
const summary = ReactTestUtils.findRenderedDOMComponentWithClass(instance, "mx_MemberEventListSummary_summary");
const summaryText = summary.innerText;
expect(summaryText).toBe(
"user_0, user_1 and 18 others joined"
);
});
});

View file

@ -108,6 +108,7 @@ export function mkEvent(opts) {
room_id: opts.room, room_id: opts.room,
sender: opts.user, sender: opts.user,
content: opts.content, content: opts.content,
prev_content: opts.prev_content,
event_id: "$" + Math.random() + "-" + Math.random(), event_id: "$" + Math.random() + "-" + Math.random(),
origin_server_ts: opts.ts, origin_server_ts: opts.ts,
}; };
@ -150,7 +151,9 @@ export function mkPresence(opts) {
* @param {Object} opts Values for the membership. * @param {Object} opts Values for the membership.
* @param {string} opts.room The room ID for the event. * @param {string} opts.room The room ID for the event.
* @param {string} opts.mship The content.membership for the event. * @param {string} opts.mship The content.membership for the event.
* @param {string} opts.prevMship The prev_content.membership for the event.
* @param {string} opts.user The user ID for the event. * @param {string} opts.user The user ID for the event.
* @param {RoomMember} opts.target The target of the event.
* @param {string} opts.skey The other user ID for the event if applicable * @param {string} opts.skey The other user ID for the event if applicable
* e.g. for invites/bans. * e.g. for invites/bans.
* @param {string} opts.name The content.displayname for the event. * @param {string} opts.name The content.displayname for the event.
@ -169,9 +172,16 @@ export function mkMembership(opts) {
opts.content = { opts.content = {
membership: opts.mship membership: opts.mship
}; };
if (opts.prevMship) {
opts.prev_content = { membership: opts.prevMship };
}
if (opts.name) { opts.content.displayname = opts.name; } if (opts.name) { opts.content.displayname = opts.name; }
if (opts.url) { opts.content.avatar_url = opts.url; } if (opts.url) { opts.content.avatar_url = opts.url; }
return mkEvent(opts); let e = mkEvent(opts);
if (opts.target) {
e.target = opts.target;
}
return e;
}; };
/** /**