signal-desktop/ts/components/conversation/media-gallery/groupMessagesByDate.ts

60 lines
1.4 KiB
TypeScript
Raw Normal View History

2018-04-13 20:25:52 +00:00
/**
* @prettier
*/
2018-04-13 00:45:14 +00:00
import moment from 'moment';
2018-04-13 20:25:52 +00:00
import { compact, groupBy, sortBy } from 'lodash';
2018-04-13 00:45:14 +00:00
import { Message } from './propTypes/Message';
2018-04-13 20:25:52 +00:00
export const groupMessagesByDate = (
timestamp: number,
messages: Array<Message>
): any => {
2018-04-13 00:45:14 +00:00
const referenceDateTime = moment.utc(timestamp);
const today = moment(referenceDateTime).startOf('day');
2018-04-13 20:25:52 +00:00
const yesterday = moment(referenceDateTime)
.subtract(1, 'day')
.startOf('day');
2018-04-13 14:53:15 +00:00
const thisWeek = moment(referenceDateTime).startOf('isoWeek');
2018-04-13 00:45:14 +00:00
const thisMonth = moment(referenceDateTime).startOf('month');
2018-04-13 20:25:52 +00:00
const sorted = sortBy(messages, message => -message.received_at);
const annotations = sorted.map(message => {
2018-04-13 14:53:15 +00:00
const date = moment.utc(message.received_at);
2018-04-13 00:45:14 +00:00
if (date.isAfter(today)) {
return {
order: 0,
label: 'today',
message,
};
} else if (date.isAfter(yesterday)) {
return {
order: 1,
label: 'yesterday',
message,
};
} else if (date.isAfter(thisWeek)) {
return {
order: 2,
label: 'thisWeek',
message,
};
} else if (date.isAfter(thisMonth)) {
return {
order: 3,
label: 'thisMonth',
message,
};
}
return {
2018-04-13 20:25:52 +00:00
order: date.year() * 100 + date.month(),
2018-04-13 00:45:14 +00:00
label: 'yearMonth',
message,
};
});
return groupBy(annotations, 'label');
};