Merge branch 'virtual-scrolling-2.0' into shigusegubu-themes3

This commit is contained in:
Henry Jameson 2026-09-10 23:08:11 +03:00
commit febc94c2bd
5 changed files with 313 additions and 215 deletions

View file

@ -1,6 +1,14 @@
import { get } from 'lodash-es' import { get } from 'lodash-es'
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { computed, provide, ref, toRefs, useTemplateRef, watch } from 'vue' import {
computed,
onUnmounted,
provide,
ref,
toRefs,
useTemplateRef,
watch,
} from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import ChatMessageList from 'src/components/chat_message_list/chat_message_list.vue' import ChatMessageList from 'src/components/chat_message_list/chat_message_list.vue'
@ -62,7 +70,8 @@ export default {
PostStatusForm, PostStatusForm,
RichContent, RichContent,
}, },
setup(props) { emits: ['heightChange', 'suspendableStateChange'],
setup(props, { emit }) {
// # Helpers // # Helpers
const getStatusObject = (id) => useStatusesStore().allStatuses.get(id) const getStatusObject = (id) => useStatusesStore().allStatuses.get(id)
const getConversationId = (statusId) => { const getConversationId = (statusId) => {
@ -190,6 +199,27 @@ export default {
const { fontSize } = useInterfaceSizes() const { fontSize } = useInterfaceSizes()
// External virtual scrolling
const unsuspendableIds = ref(new Set())
const suspendable = computed(
() => !isExpanded.value && unsuspendableIds.value.size === 0,
)
const rootElement = useTemplateRef('root')
const updateVirtualHeight = (e) => {
const [entry] = e
emit('heightChange', {
id: statusId.value,
height: entry.contentRect.height,
element: rootElement,
})
}
const resizeObserver = ref(new ResizeObserver(updateVirtualHeight))
watch(rootElement, () => resizeObserver.value.observe(rootElement.value))
watch(suspendable, (value) =>
emit('suspendableStateChange', { suspend: value, id: statusId.value }),
)
onUnmounted(() => resizeObserver.value.disconnect())
// Placeholder heights. // Placeholder heights.
const mutedStatusHeight = computed(() => fontSize.value * 1.5) const mutedStatusHeight = computed(() => fontSize.value * 1.5)
const normalStatusHeight = computed(() => fontSize.value * 10) const normalStatusHeight = computed(() => fontSize.value * 10)
@ -215,6 +245,15 @@ export default {
anchorRepeatId: currentStatus.value?.id, anchorRepeatId: currentStatus.value?.id,
getPlaceholderHeight, getPlaceholderHeight,
}) })
const changeSuspendStateLinearLocal = (e) => {
changeSuspendStateLinear(e)
const { id, suspend } = e
if (suspend) {
unsuspendableIds.value.add(id)
} else {
unsuspendableIds.value.delete(id)
}
}
// # Tree style stuff // # Tree style stuff
const isTreeView = computed(() => displayStyle.value === 'tree') const isTreeView = computed(() => displayStyle.value === 'tree')
@ -240,20 +279,24 @@ export default {
scrollCompensation: treeScrollCompensation, scrollCompensation: treeScrollCompensation,
getPlaceholderHeight, getPlaceholderHeight,
}) })
const changeSuspendStateAncestorsLocal = (e) => {
const currentLevel = computed(() => [currentStatus.value].filter(Boolean)) changeSuspendStateAncestors(e)
const currentLevelElement = useTemplateRef('currentLevel') const { id, suspend } = e
const { if (suspend) {
heightChart: heightChartCurrentLevel, unsuspendableIds.value.add(id)
changeSuspendState: changeSuspendStateCurrentLevel, } else {
updateVirtualHeight: updateVirtualHeightCurrentLevel, unsuspendableIds.value.delete(id)
} = useVirtualScrolling({ }
list: currentLevel, }
body: currentLevelElement, const changeSuspendStateCurrentLevelLocal = (e) => {
scrollPositionInstance: scroller, changeSuspendStateLinear(e)
scrollCompensation: false, const { id, suspend } = e
getPlaceholderHeight, if (suspend) {
}) unsuspendableIds.value.add(id)
} else {
unsuspendableIds.value.delete(id)
}
}
const treeViewIsSimple = computed( const treeViewIsSimple = computed(
() => !mergedConfig.value.conversationTreeAdvanced, () => !mergedConfig.value.conversationTreeAdvanced,
@ -299,7 +342,7 @@ export default {
// ## Linear virtual scrolling // ## Linear virtual scrolling
heightChartLinear, heightChartLinear,
changeSuspendStateLinear, changeSuspendStateLinearLocal,
updateVirtualHeightLinear, updateVirtualHeightLinear,
// # Tree style stuff // # Tree style stuff
@ -307,11 +350,10 @@ export default {
// ## Tree virtual scrolling // ## Tree virtual scrolling
heightChartAncestors, heightChartAncestors,
changeSuspendStateAncestors, changeSuspendStateAncestorsLocal,
updateVirtualHeightAncestors, updateVirtualHeightAncestors,
heightChartCurrentLevel,
changeSuspendStateCurrentLevel, changeSuspendStateCurrentLevelLocal,
updateVirtualHeightCurrentLevel,
// ## Tree state // ## Tree state
// ### Topology // ### Topology

View file

@ -112,7 +112,7 @@
@goto="setFocused" @goto="setFocused"
@dive="diveIntoStatus(element.item.id)" @dive="diveIntoStatus(element.item.id)"
@suspendable-state-change="changeSuspendStateAncestors" @suspendable-state-change="changeSuspendStateAncestorsLocal"
@height-change="updateVirtualHeightAncestors" @height-change="updateVirtualHeightAncestors"
/> />
<div <div
@ -122,32 +122,16 @@
/> />
</article> </article>
</div> </div>
<div <ThreadTree
class="currentLevel" :status-id="currentStatus.id"
ref="currentLevel" :depth="0"
>
<!-- Technically this will always have a single element but -->
<!-- it's more convenient for us to use a v-for here -->
<template v-for="element in heightChartCurrentLevel">
<ThreadTree
v-if="element.type === 'item'"
:status-id="currentStatus.id"
:depth="0"
@goto="setFocused" @goto="setFocused"
@dive="diveIntoStatus" @dive="diveIntoStatus"
@toggle-expanded="toggleExpanded" @toggle-expanded="toggleExpanded"
@show-thread-recursively="showThreadRecursively" @show-thread-recursively="showThreadRecursively"
@suspendable-state-change="changeSuspendStateCurrentLevel" @suspendable-state-change="changeSuspendStateCurrentLevelLocal"
@height-change="updateVirtualHeightCurrentLevel" />
/>
<div
v-if="element.type === 'spacer'"
class="virtual-spacer"
:style="{ height: element.height + 'px' }"
/>
</template>
</div>
</div> </div>
<div <div
v-else-if="isLinearView" v-else-if="isLinearView"
@ -171,7 +155,7 @@
:data-status-id="element.id" :data-status-id="element.id"
@goto="setFocused" @goto="setFocused"
@toggle-expanded="toggleExpanded" @toggle-expanded="toggleExpanded"
@suspendable-state-change="changeSuspendStateLinear" @suspendable-state-change="changeSuspendStateLinearLocal"
@height-change="updateVirtualHeightLinear" @height-change="updateVirtualHeightLinear"
/> />
<div <div

View file

@ -1,5 +1,15 @@
import { debounce, throttle } from 'lodash-es' import { debounce, throttle } from 'lodash-es'
import { mapState } from 'pinia' import { storeToRefs } from 'pinia'
import {
computed,
onMounted,
onUnmounted,
ref,
toRefs,
useTemplateRef,
watch,
} from 'vue'
import { useI18n } from 'vue-i18n'
import Conversation from 'src/components/conversation/conversation.vue' import Conversation from 'src/components/conversation/conversation.vue'
import QuickFilterSettings from 'src/components/quick_filter_settings/quick_filter_settings.vue' import QuickFilterSettings from 'src/components/quick_filter_settings/quick_filter_settings.vue'
@ -12,6 +22,10 @@ import { useMergedConfigStore } from 'src/stores/merged_config.js'
import { useStatusesStore } from 'src/stores/statuses.js' import { useStatusesStore } from 'src/stores/statuses.js'
import { useTimelinesStore } from 'src/stores/timelines.js' import { useTimelinesStore } from 'src/stores/timelines.js'
import { useInterfaceSizes } from 'src/composables/useInterfaceSizes.js'
import { useScrollPosition } from 'src/composables/useScrollPosition.js'
import { useVirtualScrolling } from 'src/composables/useVirtualScrolling.js'
import { library } from '@fortawesome/fontawesome-svg-core' import { library } from '@fortawesome/fontawesome-svg-core'
import { import {
faArrowUp, faArrowUp,
@ -29,23 +43,9 @@ const Timeline = {
timelineRef: Object, timelineRef: Object,
footerSlipgate: Object, // reference to an element where we should put our footer footerSlipgate: Object, // reference to an element where we should put our footer
embedded: Boolean, embedded: Boolean,
inProfile: Boolean,
skipPinned: Boolean, skipPinned: Boolean,
hideEmpty: Boolean, hideEmpty: Boolean,
}, },
data() {
return {
showScrollTop: false,
paused: false,
unfocused: false,
blockingClicks: false,
}
},
provide() {
return {
profileUserId: this.inProfile && this.timelineRef.argument,
}
},
components: { components: {
ScrollTopButton, ScrollTopButton,
Conversation, Conversation,
@ -53,93 +53,89 @@ const Timeline = {
QuickFilterSettings, QuickFilterSettings,
QuickViewSettings, QuickViewSettings,
}, },
computed: { setup(props, ctx) {
timeline() { const { t } = useI18n()
return useTimelinesStore()[this.timelineRef.name] const unfocused = ref(false)
},
filteredVisibleStatuses() { // Timeline
return this.timeline.order const { timelineRef } = toRefs(props)
.filter((id) => this.timeline.visibleStatusIds.has(id)) const timeline = computed(() => useTimelinesStore()[timelineRef.value.name])
const { skipPinned } = toRefs(props)
const filteredVisibleStatuses = computed(() => {
return timeline.value.order
.filter((id) => timeline.value.visibleStatusIds.has(id))
.map((id) => useStatusesStore().allStatuses.get(id)) .map((id) => useStatusesStore().allStatuses.get(id))
.filter(({ pinned }) => (this.skipPinned ? !pinned : true)) .filter(({ pinned }) => (skipPinned.value ? !pinned : true))
}, })
count() {
return this.timeline.order.length // Virtual scrolling
}, const { fontSize } = useInterfaceSizes()
newStatusCount() {
return this.timeline.newStatusCount // Placeholder heights.
}, const mutedStatusHeight = computed(() => fontSize.value * 1.5)
showLoadButton() { const normalStatusHeight = computed(() => fontSize.value * 10)
return this.timeline.newStatusCount > 0 || this.timeline.reloadNeeded const getPlaceholderHeight = (id) =>
}, filteredVisibleStatuses.value.find((item) => item.id === id)?.muted
loadButtonString() { ? mutedStatusHeight
if (this.timeline.reloadNeeded) { : normalStatusHeight
return this.$t('timeline.reload')
const body = useTemplateRef('timeline')
const { heightChart, changeSuspendState, updateVirtualHeight } =
useVirtualScrolling({
list: filteredVisibleStatuses,
body,
scrollPositionInstance: useScrollPosition(),
scrollCompensation: false,
getPlaceholderHeight,
})
// Counter
const count = computed(() => timeline.value.order.length)
const newStatusCount = computed(() => timeline.value.newStatusCount)
const showLoadButton = computed(
() => timeline.value.newStatusCount > 0 || timeline.value.reloadNeeded,
)
// Showing new
const paused = ref(false)
watch(newStatusCount, (count) => {
if (!useMergedConfigStore().mergedConfig.streaming) {
return
}
if (count <= 0) return
// only 'stream' them when you're scrolled to the top
const doc = document.documentElement
const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
if (
top < 15 &&
!paused.value &&
!(
unfocused.value &&
useMergedConfigStore().mergedConfig.pauseOnUnfocused
)
) {
showNewStatuses()
} else { } else {
return `${this.$t('timeline.show_new')} (${this.newStatusCount})` paused.value = true
} }
}, })
mobileLoadButtonString() { const showNewStatuses = () => {
if (this.timeline.reloadNeeded) { if (timeline.value.reloadNeeded) {
return '+' useTimelinesStore().clearTimeline(timelineRef.value.name)
fetchOlderStatuses()
} else { } else {
return this.newStatusCount > 99 ? '∞' : this.newStatusCount blockClicksTemporarily()
useTimelinesStore().showNewStatuses(timelineRef.value.name)
paused.value = false
} }
}, window.scrollTo({ top: 0 })
classes() {
let rootClasses = !this.embedded
? ['panel', 'panel-default']
: ['-embedded']
if (this.blockingClicks)
rootClasses = rootClasses.concat(['-blocked', '_misclick-prevention'])
return {
root: rootClasses,
header: ['timeline-heading'].concat(
!this.embedded ? ['panel-heading', '-sticky'] : ['panel-body'],
),
body: ['timeline-body'].concat(
!this.embedded ? ['panel-body'] : ['panel-body'],
),
footer: ['timeline-footer'].concat(
!this.embedded ? ['panel-footer'] : ['panel-body'],
),
}
},
statusesToDisplay() {
return new Set(this.filteredVisibleStatuses.map(({ id }) => id))
},
...mapState(useInterfaceStore, {
mobileLayout: (store) => store.layoutType === 'mobile',
}),
},
created() {
this.timelineChange(this.timelineRef)
},
mounted() {
if (document.hidden !== undefined) {
document.addEventListener(
'visibilitychange',
this.handleVisibilityChange,
false,
)
this.unfocused = document.hidden
} }
window.addEventListener('keydown', this.handleShortKey) const fetchOlderStatuses = throttle(() => {
window.addEventListener('scroll', this.handleScroll) timeline.value.fetcher.fetchOlder()
}, }, 1000)
unmounted() {
this.timelineChange(null, this.timelineRef) // Timeline change
window.removeEventListener('scroll', this.handleScroll) const timelineChange = (newTimeline, oldTimeline) => {
window.removeEventListener('keydown', this.handleShortKey)
if (document.hidden !== undefined)
document.removeEventListener(
'visibilitychange',
this.handleVisibilityChange,
false,
)
},
methods: {
timelineChange(newTimeline, oldTimeline) {
const sameName = newTimeline?.name === oldTimeline?.name const sameName = newTimeline?.name === oldTimeline?.name
const sameArgument = newTimeline?.argument === oldTimeline?.argument const sameArgument = newTimeline?.argument === oldTimeline?.argument
if (sameName && sameArgument) return if (sameName && sameArgument) return
@ -150,83 +146,143 @@ const Timeline = {
if (newTimeline) { if (newTimeline) {
useTimelinesStore().activate(newTimeline.name, newTimeline.argument) useTimelinesStore().activate(newTimeline.name, newTimeline.argument)
} }
}, }
stopBlockingClicks: debounce(function () { watch(timelineRef, timelineChange, { immediate: true })
this.blockingClicks = false onUnmounted(() => {
}, 1000), timelineChange(null, timelineRef.value) // ????
blockClicksTemporarily() { })
if (!this.blockingClicks) {
this.blockingClicks = true // Misclick prevention
const blockingClicks = ref(false)
const stopBlockingClicks = debounce(() => {
blockingClicks.value = false
}, 1000)
const blockClicksTemporarily = () => {
if (!blockingClicks.value) {
blockingClicks.value = true
} }
this.stopBlockingClicks() stopBlockingClicks()
}, }
handleShortKey(e) {
// Shortcuts
const handleShortKey = (e) => {
// Ignore when input fields are focused // Ignore when input fields are focused
if (['textarea', 'input'].includes(e.target.tagName.toLowerCase())) return if (['textarea', 'input'].includes(e.target.tagName.toLowerCase())) return
if (e.key === '.') this.showNewStatuses() if (e.key === '.') showNewStatuses()
}, }
showNewStatuses() { onMounted(() => {
if (this.timeline.reloadNeeded) { window.addEventListener('keydown', handleShortKey)
useTimelinesStore().clearTimeline(this.timelineRef.name) })
this.fetchOlderStatuses() onUnmounted(() => {
} else { window.removeEventListener('keydown', handleShortKey)
this.blockClicksTemporarily() })
useTimelinesStore().showNewStatuses(this.timelineRef.name)
this.paused = false // Scroll
} const scrollLoad = () => {
window.scrollTo({ top: 0 })
},
fetchOlderStatuses: throttle(
function () {
this.timeline.fetcher.fetchOlder()
},
1000,
this,
),
scrollLoad() {
// TODO simplify this logic // TODO simplify this logic
const bodyBRect = document.body.getBoundingClientRect() const bodyBRect = document.body.getBoundingClientRect()
const height = Math.max(bodyBRect.height, -bodyBRect.y) const height = Math.max(bodyBRect.height, -bodyBRect.y)
if ( if (
!this.timeline.fetcher.loadingOlder && !timeline.value.fetcher.loadingOlder &&
window.innerHeight + window.pageYOffset >= height - 750 window.innerHeight + window.pageYOffset >= height - 750
) { ) {
this.fetchOlderStatuses() fetchOlderStatuses()
} }
}, }
handleScroll: throttle(function (e) { const handleScroll = throttle((e) => {
this.scrollLoad(e) scrollLoad(e)
}, 200), }, 200)
handleVisibilityChange() { onMounted(() => {
this.unfocused = document.hidden window.addEventListener('scroll', handleScroll)
}, })
}, onUnmounted(() => {
watch: { window.removeEventListener('scroll', handleScroll)
timelineRef(newTimeline, oldTimeline) { })
this.timelineChange(newTimeline, oldTimeline)
}, // Focused state
newStatusCount(count) { const handleVisibilityChange = () => {
if (!useMergedConfigStore().mergedConfig.streaming) { unfocused.value = document.hidden
return }
onMounted(() => {
if (document.hidden === undefined) return
document.addEventListener(
'visibilitychange',
handleVisibilityChange,
false,
)
unfocused.value = document.hidden
})
onUnmounted(() => {
if (document.hidden === undefined) return
document.removeEventListener(
'visibilitychange',
handleVisibilityChange,
false,
)
})
// Misc UI things
const classes = computed(() => {
let rootClasses = !embedded.value
? ['panel', 'panel-default']
: ['-embedded']
if (blockingClicks.value)
rootClasses = rootClasses.concat(['-blocked', '_misclick-prevention'])
return {
root: rootClasses,
header: ['timeline-heading'].concat(
!embedded.value ? ['panel-heading', '-sticky'] : ['panel-body'],
),
body: ['timeline-body'].concat(
!embedded.value ? ['panel-body'] : ['panel-body'],
),
footer: ['timeline-footer'].concat(
!embedded.value ? ['panel-footer'] : ['panel-body'],
),
} }
if (count > 0) { })
// only 'stream' them when you're scrolled to the top const loadButtonString = computed(() => {
const doc = document.documentElement if (timeline.value.reloadNeeded) {
const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0) return t('timeline.reload')
if ( } else {
top < 15 && return `${t('timeline.show_new')} (${newStatusCount.value})`
!this.paused &&
!(
this.unfocused &&
useMergedConfigStore().mergedConfig.pauseOnUnfocused
)
) {
this.showNewStatuses()
} else {
this.paused = true
}
} }
}, })
const mobileLoadButtonString = computed(() => {
if (timeline.value.reloadNeeded) {
return '+'
} else {
return newStatusCount.value > 99 ? '∞' : newStatusCount.value
}
})
const { layoutType } = storeToRefs(useInterfaceStore())
const mobileLayout = computed(() => layoutType.value === 'mobile')
const { footerSlipgate, embedded, hideEmpty } = toRefs(props)
return {
timelineRef,
timeline,
filteredVisibleStatuses,
heightChart,
updateVirtualHeight,
changeSuspendState,
count,
showLoadButton,
showNewStatuses,
fetchOlderStatuses,
classes,
loadButtonString,
mobileLoadButtonString,
mobileLayout,
footerSlipgate,
embedded,
hideEmpty,
}
}, },
} }

View file

@ -82,12 +82,23 @@
ref="timeline" ref="timeline"
role="feed" role="feed"
> >
<Conversation <template
v-for="status in filteredVisibleStatuses" v-for="element in heightChart"
:key="status.id" :key="element.id"
:status-id="status.id" >
role="listitem" <Conversation
/> v-if="element.type === 'item'"
:status-id="element.item.id"
role="listitem"
@suspendable-state-change="changeSuspendState"
@height-change="updateVirtualHeight"
/>
<div
v-if="element.type === 'spacer'"
class="virtual-spacer"
:style="{ height: element.height + 'px' }"
/>
</template>
</div> </div>
<template v-if="!hideEmpty && count === 0"> <template v-if="!hideEmpty && count === 0">
<div <div

View file

@ -34,6 +34,11 @@ const UserProfile = {
this.tab = get(this.$route, 'query.tab', defaultTabKey) this.tab = get(this.$route, 'query.tab', defaultTabKey)
useInterfaceStore().setForeignProfileBackground(this.user?.background_image) useInterfaceStore().setForeignProfileBackground(this.user?.background_image)
}, },
provide() {
return {
profileUserId: this.userId,
}
},
updated() { updated() {
useInterfaceStore().setForeignProfileBackground(this.user?.background_image) useInterfaceStore().setForeignProfileBackground(this.user?.background_image)
}, },