From d7b1a2e0eedda777f3f81f8ddc30586c3738eb79 Mon Sep 17 00:00:00 2001
From: Paul Frazee <pfrazee@gmail.com>
Date: Tue, 22 Nov 2022 12:56:56 -0600
Subject: Scroll to highlighted post in threads

---
 src/view/com/post-thread/PostThread.tsx | 28 ++++++++++++++++++++++++++--
 1 file changed, 26 insertions(+), 2 deletions(-)

(limited to 'src/view/com/post-thread/PostThread.tsx')

diff --git a/src/view/com/post-thread/PostThread.tsx b/src/view/com/post-thread/PostThread.tsx
index d819cc76c..d078cb8ee 100644
--- a/src/view/com/post-thread/PostThread.tsx
+++ b/src/view/com/post-thread/PostThread.tsx
@@ -1,4 +1,4 @@
-import React, {useState, useEffect} from 'react'
+import React, {useRef} from 'react'
 import {observer} from 'mobx-react-lite'
 import {ActivityIndicator, FlatList, Text, View} from 'react-native'
 import {
@@ -16,9 +16,31 @@ export const PostThread = observer(function PostThread({
   uri: string
   view: PostThreadViewModel
 }) {
+  const ref = useRef<FlatList>(null)
+  const posts = view.thread ? Array.from(flattenThread(view.thread)) : []
   const onRefresh = () => {
     view?.refresh().catch(err => console.error('Failed to refresh', err))
   }
+  const onLayout = () => {
+    const index = posts.findIndex(post => post._isHighlightedPost)
+    if (index !== -1) {
+      ref.current?.scrollToIndex({
+        index,
+        animated: false,
+        viewOffset: 40,
+      })
+    }
+  }
+  const onScrollToIndexFailed = (info: {
+    index: number
+    highestMeasuredFrameIndex: number
+    averageItemLength: number
+  }) => {
+    ref.current?.scrollToOffset({
+      animated: false,
+      offset: info.averageItemLength * info.index,
+    })
+  }
 
   // loading
   // =
@@ -47,17 +69,19 @@ export const PostThread = observer(function PostThread({
 
   // loaded
   // =
-  const posts = view.thread ? Array.from(flattenThread(view.thread)) : []
   const renderItem = ({item}: {item: PostThreadViewPostModel}) => (
     <PostThreadItem item={item} onPostReply={onRefresh} />
   )
   return (
     <FlatList
+      ref={ref}
       data={posts}
       keyExtractor={item => item._reactKey}
       renderItem={renderItem}
       refreshing={view.isRefreshing}
       onRefresh={onRefresh}
+      onLayout={onLayout}
+      onScrollToIndexFailed={onScrollToIndexFailed}
       style={{flex: 1}}
     />
   )
-- 
cgit 1.4.1

