feat: improve timeline reordering
This commit is contained in:
parent
bf0c3425fc
commit
9890656477
7 changed files with 119 additions and 21 deletions
|
@ -158,20 +158,3 @@ async function fetchRelationships() {
|
|||
for (let i = 0; i < requested.length; i++)
|
||||
requested[i][1].value = relationships[i]
|
||||
}
|
||||
|
||||
const maxDistance = 10
|
||||
export function timelineWithReorderedReplies(items: Status[]) {
|
||||
const newItems = [...items]
|
||||
// TODO: Basic reordering, we should get something more efficient and robust
|
||||
for (let i = items.length - 1; i > 0; i--) {
|
||||
for (let k = 1; k <= maxDistance && i - k >= 0; k++) {
|
||||
const inReplyToId = newItems[i - k].inReplyToId ?? newItems[i - k].reblog?.inReplyToId
|
||||
if (inReplyToId && (inReplyToId === newItems[i].reblog?.id || inReplyToId === newItems[i].id)) {
|
||||
const item = newItems.splice(i, 1)[0]
|
||||
newItems.splice(i - k, 0, item)
|
||||
k = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return newItems
|
||||
}
|
||||
|
|
50
composables/timeline.ts
Normal file
50
composables/timeline.ts
Normal file
|
@ -0,0 +1,50 @@
|
|||
import type { Status } from 'masto'
|
||||
|
||||
const maxDistance = 10
|
||||
const maxSteps = 1000
|
||||
|
||||
// Checks if (b) is a reply to (a)
|
||||
function areStatusesConsecutive(a: Status, b: Status) {
|
||||
const inReplyToId = b.inReplyToId ?? b.reblog?.inReplyToId
|
||||
return !!inReplyToId && (inReplyToId === a.reblog?.id || inReplyToId === a.id)
|
||||
}
|
||||
|
||||
export function reorderedTimeline(items: Status[]) {
|
||||
let steps = 0
|
||||
const newItems = [...items]
|
||||
for (let i = items.length - 1; i > 0; i--) {
|
||||
for (let k = 1; k <= maxDistance && i - k >= 0; k++) {
|
||||
// Prevent infinite loops
|
||||
steps++
|
||||
if (steps > maxSteps)
|
||||
return newItems
|
||||
|
||||
// Check if the [i-k] item is a reply to the [i] item
|
||||
// This means that they are in the wrong order
|
||||
|
||||
if (areStatusesConsecutive(newItems[i], newItems[i - k])) {
|
||||
const item = newItems.splice(i, 1)[0]
|
||||
newItems.splice(i - k, 0, item) // insert older item before the newer one
|
||||
k = 0
|
||||
}
|
||||
else if (k > 1) {
|
||||
// Check if the [i] item is a reply to the [i-k] item
|
||||
// This means that they are in the correct order but there are posts between them
|
||||
if (areStatusesConsecutive(newItems[i - k], newItems[i])) {
|
||||
// If the next statuses are already ordered, move them all
|
||||
let j = i
|
||||
for (; j < items.length - 1; j++) {
|
||||
if (!areStatusesConsecutive(newItems[j], newItems[j + 1]))
|
||||
break
|
||||
}
|
||||
const orderedCount = j - i + 1
|
||||
const itemsToMove = newItems.splice(i, orderedCount)
|
||||
// insert older item after the newer one
|
||||
newItems.splice(i - k + 1, 0, ...itemsToMove)
|
||||
k = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return newItems
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue