rainbow-fe/src/lib/mastoapi/pleroma_fixes.ts

61 lines
1.7 KiB
TypeScript

import type { MastodonStatus, MastodonStatusContext } from './status';
// Oh jeez
export function reorderAndFilterPleromaReplies(
status: MastodonStatus,
context: MastodonStatusContext
): MastodonStatusContext {
const findInOrig = (id: string): MastodonStatus | undefined =>
context.ancestors.find((status) => status.id === id) ||
context.descendants.find((status) => status.id === id);
const newContext: MastodonStatusContext = { ancestors: [], descendants: [] };
let currParent: MastodonStatus | undefined = status;
while (currParent != null) {
let replyingTo = currParent.in_reply_to_id;
if (replyingTo != null) {
currParent = findInOrig(replyingTo);
if (currParent != null) {
newContext.ancestors.unshift(currParent);
}
} else {
currParent = undefined;
}
}
const replyTree = new Map<string, MastodonStatus[]>();
for (const descendant of context.descendants) {
if (descendant.in_reply_to_id == null) {
continue;
}
if (!replyTree.has(descendant.in_reply_to_id)) {
replyTree.set(descendant.in_reply_to_id, []);
}
replyTree.get(descendant.in_reply_to_id)?.push(descendant);
}
let queue = [status];
newContext.descendants.push(status);
let potentialParent: MastodonStatus | undefined;
while ((potentialParent = queue.shift()) != null) {
const replies = replyTree.get(potentialParent.id);
if (replies) {
for (const reply of replies.reverse()) {
const parentIndex = newContext.descendants.indexOf(potentialParent);
newContext.descendants.splice(parentIndex + 1, 0, reply);
}
for (const reply of replies) {
queue.push(reply);
}
}
}
newContext.descendants.shift();
return newContext;
}