1
0
mirror of https://github.com/tooot-app/app synced 2025-04-04 21:51:12 +02:00

Basic toot in timeline working

This commit is contained in:
Zhiyuan Zheng 2020-10-26 00:27:53 +01:00
parent 996cf0c1e7
commit eefa7e01bd
No known key found for this signature in database
GPG Key ID: 078A93AB607D85E0
21 changed files with 483 additions and 284 deletions

82
package-lock.json generated
View File

@ -2325,23 +2325,6 @@
"node-int64": "^0.4.0" "node-int64": "^0.4.0"
} }
}, },
"buffer": {
"version": "4.9.2",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz",
"integrity": "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==",
"requires": {
"base64-js": "^1.0.2",
"ieee754": "^1.1.4",
"isarray": "^1.0.0"
},
"dependencies": {
"isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
}
}
},
"buffer-alloc": { "buffer-alloc": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz", "resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz",
@ -3097,16 +3080,16 @@
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==" "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="
}, },
"eventemitter2": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-1.0.5.tgz",
"integrity": "sha1-+YNhBRexc3wLncZDvsqTiTwE3xg="
},
"eventemitter3": { "eventemitter3": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.2.tgz", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.2.tgz",
"integrity": "sha512-tvtQIeLVHjDkJYnzf2dgVMxfuSGJeM/7UCG17TT4EumTfNtF+0nebF/4zWOIkCreAbtNqhGEboB6BWrwqNaw4Q==" "integrity": "sha512-tvtQIeLVHjDkJYnzf2dgVMxfuSGJeM/7UCG17TT4EumTfNtF+0nebF/4zWOIkCreAbtNqhGEboB6BWrwqNaw4Q=="
}, },
"events": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz",
"integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ="
},
"exec-sh": { "exec-sh": {
"version": "0.3.4", "version": "0.3.4",
"resolved": "https://registry.npmjs.org/exec-sh/-/exec-sh-0.3.4.tgz", "resolved": "https://registry.npmjs.org/exec-sh/-/exec-sh-0.3.4.tgz",
@ -3840,34 +3823,18 @@
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz", "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz",
"integrity": "sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw==" "integrity": "sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw=="
}, },
"html-entities": { "htmlparser2-without-node-native": {
"version": "1.3.1", "version": "3.9.2",
"resolved": "https://registry.npmjs.org/html-entities/-/html-entities-1.3.1.tgz", "resolved": "https://registry.npmjs.org/htmlparser2-without-node-native/-/htmlparser2-without-node-native-3.9.2.tgz",
"integrity": "sha512-rhE/4Z3hIhzHAUKbW8jVcCyuT5oJCXXqhN/6mXXVCpzTmvJnoH2HL/bt3EZ6p55jbFJBeAe1ZNpL5BugLujxNA==" "integrity": "sha1-s+0FDYd9D/NGWWnjOYd7f59mMfY=",
},
"htmlparser2": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz",
"integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==",
"requires": { "requires": {
"domelementtype": "^1.3.1", "domelementtype": "^1.3.0",
"domhandler": "^2.3.0", "domhandler": "^2.3.0",
"domutils": "^1.5.1", "domutils": "^1.5.1",
"entities": "^1.1.1", "entities": "^1.1.1",
"eventemitter2": "^1.0.0",
"inherits": "^2.0.1", "inherits": "^2.0.1",
"readable-stream": "^3.1.1" "readable-stream": "^2.0.2"
},
"dependencies": {
"readable-stream": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz",
"integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==",
"requires": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
}
}
} }
}, },
"http-errors": { "http-errors": {
@ -3895,11 +3862,6 @@
"safer-buffer": ">= 2.1.2 < 3.0.0" "safer-buffer": ">= 2.1.2 < 3.0.0"
} }
}, },
"ieee754": {
"version": "1.1.13",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz",
"integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg=="
},
"image-size": { "image-size": {
"version": "0.6.3", "version": "0.6.3",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-0.6.3.tgz", "resolved": "https://registry.npmjs.org/image-size/-/image-size-0.6.3.tgz",
@ -6619,6 +6581,15 @@
"prop-types": "^15.7.2" "prop-types": "^15.7.2"
} }
}, },
"react-native-htmlview": {
"version": "0.16.0",
"resolved": "https://registry.npmjs.org/react-native-htmlview/-/react-native-htmlview-0.16.0.tgz",
"integrity": "sha512-yUrzXje+kKKLkWkccKNBeg3CbvrodA7f4+1d/XRrrg0SDFfIdj7NnjRdH+WXqGze6R501bfRZOPaZx/M5HTz3A==",
"requires": {
"entities": "^1.1.1",
"htmlparser2-without-node-native": "^3.9.2"
}
},
"react-native-iphone-x-helper": { "react-native-iphone-x-helper": {
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/react-native-iphone-x-helper/-/react-native-iphone-x-helper-1.3.0.tgz", "resolved": "https://registry.npmjs.org/react-native-iphone-x-helper/-/react-native-iphone-x-helper-1.3.0.tgz",
@ -6632,17 +6603,6 @@
"fbjs": "^1.0.0" "fbjs": "^1.0.0"
} }
}, },
"react-native-render-html": {
"version": "4.2.4",
"resolved": "https://registry.npmjs.org/react-native-render-html/-/react-native-render-html-4.2.4.tgz",
"integrity": "sha512-OiLItEzKgS7dzD9XI5bHhjcUEfpWdzH1FgexzjbBdICPfYjmmcefpcRmLZY1+HMfxJ7wL8iF1PzTF48LchGTBA==",
"requires": {
"buffer": "^4.5.1",
"events": "^1.1.0",
"html-entities": "^1.2.0",
"htmlparser2": "3.10.1"
}
},
"react-native-safe-area-context": { "react-native-safe-area-context": {
"version": "3.1.4", "version": "3.1.4",
"resolved": "https://registry.npmjs.org/react-native-safe-area-context/-/react-native-safe-area-context-3.1.4.tgz", "resolved": "https://registry.npmjs.org/react-native-safe-area-context/-/react-native-safe-area-context-3.1.4.tgz",

View File

@ -8,8 +8,10 @@
"eject": "expo eject" "eject": "expo eject"
}, },
"dependencies": { "dependencies": {
"@expo/vector-icons": "^10.0.0",
"@react-native-async-storage/async-storage": "^1.13.0", "@react-native-async-storage/async-storage": "^1.13.0",
"@react-native-community/masked-view": "0.1.10", "@react-native-community/masked-view": "0.1.10",
"@react-native-community/segmented-control": "2.1.1",
"@react-navigation/bottom-tabs": "^5.9.2", "@react-navigation/bottom-tabs": "^5.9.2",
"@react-navigation/native": "^5.7.6", "@react-navigation/native": "^5.7.6",
"@react-navigation/stack": "^5.9.3", "@react-navigation/stack": "^5.9.3",
@ -22,15 +24,13 @@
"react-dom": "16.13.1", "react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz", "react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz",
"react-native-gesture-handler": "~1.7.0", "react-native-gesture-handler": "~1.7.0",
"react-native-htmlview": "^0.16.0",
"react-native-reanimated": "~1.13.0", "react-native-reanimated": "~1.13.0",
"react-native-render-html": "^4.2.4",
"react-native-safe-area-context": "3.1.4", "react-native-safe-area-context": "3.1.4",
"react-native-screens": "~2.10.1", "react-native-screens": "~2.10.1",
"react-native-web": "~0.13.7", "react-native-web": "~0.13.7",
"react-native-webview": "10.7.0", "react-native-webview": "10.7.0",
"react-redux": "^7.2.1", "react-redux": "^7.2.1"
"@react-native-community/segmented-control": "2.1.1",
"@expo/vector-icons": "^10.0.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "~7.9.0", "@babel/core": "~7.9.0",

View File

@ -2,7 +2,6 @@ import 'react-native-gesture-handler'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs' import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'
import { NavigationContainer } from '@react-navigation/native' import { NavigationContainer } from '@react-navigation/native'
import { enableScreens } from 'react-native-screens' import { enableScreens } from 'react-native-screens'
enableScreens()
import React from 'react' import React from 'react'
import { Feather } from '@expo/vector-icons' import { Feather } from '@expo/vector-icons'
@ -16,6 +15,7 @@ import Post from 'src/stacks/Post'
import Notifications from 'src/stacks/Notifications' import Notifications from 'src/stacks/Notifications'
import Me from 'src/stacks/Me' import Me from 'src/stacks/Me'
enableScreens()
const Tab = createBottomTabNavigator() const Tab = createBottomTabNavigator()
export default function Index () { export default function Index () {

View File

@ -13,21 +13,19 @@ export async function client (url, query, { body, ...customConfig } = {}) {
} }
} }
if (body) { const queryString = query
config.body = JSON.stringify(body)
}
let data
try {
const response = await fetch(
`https://${url}${
Object.keys(query).length
? `?${Object.keys(query) ? `?${Object.keys(query)
.map(key => `${key}=${query[key]}`) .map(key => `${key}=${query[key]}`)
.join('&')}` .join('&')}`
: '' : ''
}`,
config if (body) {
) config.body = JSON.stringify(body)
}
let data
try {
const response = await fetch(`https://${url}${queryString}`, config)
data = await response.json() data = await response.json()
if (response.ok) { if (response.ok) {
return data return data

View File

@ -8,7 +8,36 @@ import Header from './TootTimeline/Header'
import Content from './TootTimeline/Content' import Content from './TootTimeline/Content'
import Actions from './TootTimeline/Actions' import Actions from './TootTimeline/Actions'
// Maybe break away notification types? https://docs.joinmastodon.org/entities/notification/
export default function TootTimeline ({ item, notification }) { export default function TootTimeline ({ item, notification }) {
let contentAggregated = {}
if (notification && item.status) {
contentAggregated = {
content: item.status.content,
emojis: item.status.emojis,
media_attachments: item.status.media_attachments,
mentions: item.status.mentions,
tags: item.status.tags
}
} else if (item.reblog) {
contentAggregated = {
content: item.reblog.content,
emojis: item.reblog.emojis,
media_attachments: item.reblog.media_attachments,
mentions: item.reblog.mentions,
tags: item.reblog.tags
}
} else {
contentAggregated = {
content: item.content,
emojis: item.emojis,
media_attachments: item.media_attachments,
mentions: item.mentions,
tags: item.tags
}
}
return ( return (
<View style={styles.tootTimeline}> <View style={styles.tootTimeline}>
{item.reblog && ( {item.reblog && (
@ -19,7 +48,7 @@ export default function TootTimeline ({ item, notification }) {
)} )}
<View style={styles.toot}> <View style={styles.toot}>
<Avatar uri={item.reblog?.account.avatar || item.account.avatar} /> <Avatar uri={item.reblog?.account.avatar || item.account.avatar} />
<View style={{flexGrow: 1}}> <View style={styles.details}>
<Header <Header
name={ name={
(item.reblog?.account.display_name (item.reblog?.account.display_name
@ -34,9 +63,7 @@ export default function TootTimeline ({ item, notification }) {
created_at={item.created_at} created_at={item.created_at}
application={item.application || null} application={item.application || null}
/> />
<Content <Content {...contentAggregated} />
content={notification ? item.status.content : item.content}
/>
</View> </View>
</View> </View>
<Actions /> <Actions />
@ -51,7 +78,11 @@ const styles = StyleSheet.create({
padding: 12 padding: 12
}, },
toot: { toot: {
flex: 1,
flexDirection: 'row' flexDirection: 'row'
},
details: {
flex: 1
} }
}) })

View File

@ -1,6 +1,6 @@
import React from 'react' import React from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { Image, StyleSheet } from 'react-native' import { Image, StyleSheet, View } from 'react-native'
export default function Avatar ({ uri }) { export default function Avatar ({ uri }) {
return <Image source={{ uri: uri }} style={styles.avatar} /> return <Image source={{ uri: uri }} style={styles.avatar} />

View File

@ -1,29 +1,100 @@
import React, { useState } from 'react' import React from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { Dimensions, StyleSheet, View } from 'react-native' import { StyleSheet, Text } from 'react-native'
import HTML from 'react-native-render-html' import { useNavigation } from '@react-navigation/native'
import HTMLView from 'react-native-htmlview'
// !! Need to solve dimension issue import Emojis from './Emojis'
export default function Content ({ content }) { function renderNode (navigation, node, index, mentions) {
const [viewWidth, setViewWidth] = useState() if (node.name == 'a') {
const classes = node.attribs.class
const href = node.attribs.href
if (classes) {
if (classes.includes('hashtag')) {
return ( return (
content && ( <Text
<View key={index}
style={{ width: '100%' }} style={styles.a}
onLayout={e => setViewWidth(e.nativeEvent.layout.width)} onPress={() => {
const tag = href.split(new RegExp(/\/tag\/(.*)|\/tags\/(.*)/))
navigation.navigate('Hashtag', {
hashtag: tag[1] || tag[2]
})
}}
> >
{viewWidth && ( {node.children[0].data}
<HTML html={content} containerStyle={{ width: viewWidth }} /> {node.children[1]?.children[0].data}
)} </Text>
</View>
) )
} else if (classes.includes('mention')) {
return (
<Text
key={index}
style={styles.a}
onPress={() => {
const username = href.split(new RegExp(/@(.*)/))
const usernameIndex = mentions.findIndex(
m => m.username === username[1]
)
navigation.navigate('Account', {
id: mentions[usernameIndex].id
})
}}
>
{node.children[0].data}
{node.children[1]?.children[0].data}
</Text>
)
}
} else {
const domain = href.split(new RegExp(/:\/\/(.*?)\//))
return (
<Text
key={index}
style={styles.a}
onPress={() => {
navigation.navigate('Webview', {
uri: href,
domain: domain[1]
})
}}
>
{domain[1]}
</Text>
)
}
}
}
export default function Content ({
content,
emojis,
media_attachments,
mentions,
tags
}) {
const navigation = useNavigation()
return content ? (
<HTMLView
value={content}
renderNode={(node, index) =>
renderNode(navigation, node, index, mentions)
}
TextComponent={({ children }) => (
<Emojis content={children} emojis={emojis} dimension={14} />
)}
/>
) : (
<></>
) )
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
width: 50, a: {
height: 50 color: 'blue'
}
}) })
Content.propTypes = { Content.propTypes = {

View File

@ -15,7 +15,7 @@ export default function Header ({
const [since, setSince] = useState(relativeTime(created_at)) const [since, setSince] = useState(relativeTime(created_at))
useEffect(() => { useEffect(() => {
const timer = setTimeout(() => { setTimeout(() => {
setSince(relativeTime(created_at)) setSince(relativeTime(created_at))
}, 1000) }, 1000)
}) })
@ -49,8 +49,7 @@ export default function Header ({
const styles = StyleSheet.create({ const styles = StyleSheet.create({
names: { names: {
flexDirection: 'row', flexDirection: 'row'
marginBottom: 8
}, },
name: { name: {
flexDirection: 'row', flexDirection: 'row',
@ -66,6 +65,8 @@ const styles = StyleSheet.create({
created_at: { created_at: {
fontSize: 12, fontSize: 12,
lineHeight: 12, lineHeight: 12,
marginTop: 8,
marginBottom: 8,
marginRight: 8 marginRight: 8
}, },
application: { application: {

View File

@ -7,8 +7,8 @@ export default function Local () {
<TimelinesCombined <TimelinesCombined
name='Local' name='Local'
content={[ content={[
{ title: '关注', timeline: { endpoint: 'home' } }, { title: '关注', page: 'Following' },
{ title: '本站', timeline: { endpoint: 'public', local: true } } { title: '本站', page: 'Local' }
]} ]}
/> />
) )

View File

@ -26,9 +26,7 @@ export default function Notifications () {
}} }}
> >
<Stack.Screen name='Notifications'> <Stack.Screen name='Notifications'>
{props => ( {props => <Timeline page='Notifications' {...props} />}
<Timeline timeline={{ endpoint: 'notifications' }} {...props} />
)}
</Stack.Screen> </Stack.Screen>
</Stack.Navigator> </Stack.Navigator>
) )

View File

@ -7,8 +7,8 @@ export default function Public () {
<TimelinesCombined <TimelinesCombined
name='Public' name='Public'
content={[ content={[
{ title: '跨站', timeline: { endpoint: 'public' } }, { title: '跨站', page: 'LocalPublic' },
{ title: '他站', timeline: { remote: true } } { title: '他站', page: 'RemotePublic' }
]} ]}
/> />
) )

View File

@ -1,7 +0,0 @@
import React from 'react'
import Timeline from 'src/stacks/common/Timeline'
export default function LocalPublic () {
return <Timeline endpoint='public' />
}

View File

@ -0,0 +1,41 @@
import React, { useEffect } from 'react'
import { SafeAreaView, ScrollView, Text } from 'react-native'
import { useDispatch, useSelector } from 'react-redux'
import { useFocusEffect } from '@react-navigation/native'
import { fetch, getState, reset } from 'src/stacks/common/accountSlice'
// Show remote hashtag? Only when private, show local version?
export default function Account ({
route: {
params: { id }
}
}) {
const dispatch = useDispatch()
const state = useSelector(getState)
useEffect(() => {
if (state.status === 'idle') {
dispatch(fetch({ id }))
}
}, [state, dispatch])
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
dispatch(reset())
}
}, [])
)
return (
<SafeAreaView>
<ScrollView>
<Text>{state.account.acct}</Text>
</ScrollView>
</SafeAreaView>
)
}

View File

@ -0,0 +1,28 @@
import React from 'react'
import { useDispatch } from 'react-redux'
import { useFocusEffect } from '@react-navigation/native'
import Timeline from 'src/stacks/common/Timeline'
import { reset } from 'src/stacks/common/timelineSlice'
// Show remote hashtag? Only when private, show local version?
export default function Hashtag ({
route: {
params: { hashtag }
}
}) {
const dispatch = useDispatch()
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
dispatch(reset('Hashtag'))
}
}, [])
)
return <Timeline page='Hashtag' hashtag={hashtag} />
}

View File

@ -0,0 +1,17 @@
import React from 'react'
import PropTypes from 'prop-types'
import { WebView } from 'react-native-webview'
// Webview preview card
export default function Webview ({
route: {
params: { uri }
}
}) {
return <WebView source={{ uri: uri }} />
}
Webview.propTypes = {
uri: PropTypes.string.isRequired
}

View File

@ -1,98 +1,65 @@
import React, { useEffect, useState } from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import React, { useEffect } from 'react'
import { ActivityIndicator, FlatList, View } from 'react-native' import { ActivityIndicator, FlatList, View } from 'react-native'
import { useSelector, useDispatch } from 'react-redux' import { useSelector, useDispatch } from 'react-redux'
import TootTimeline from 'src/components/TootTimeline' import TootTimeline from 'src/components/TootTimeline'
import { fetch, getToots, getStatus } from './timelineSlice' import { fetch, getState } from './timelineSlice'
const Default = ({ dispatch, toots, status, timeline }) => { // Opening nesting hashtag pages
return (
export default function Timeline ({ page, hashtag, list }) {
const dispatch = useDispatch()
const state = useSelector(state => getState(state)(page))
const [timelineReady, setTimelineReady] = useState(false)
useEffect(() => {
if (state.status === 'idle') {
dispatch(fetch({ page, hashtag, list }))
setTimelineReady(true)
}
}, [state, dispatch])
let content
if (state.status === 'error') {
content = <Text>Error message</Text>
} else {
content = (
<> <>
<FlatList <FlatList
data={toots} data={state.toots}
keyExtractor={({ id }) => id} keyExtractor={({ id }) => id}
renderItem={TootTimeline} renderItem={TootTimeline}
onRefresh={() => onRefresh={() =>
dispatch(fetch({ ...timeline, id: toots[0].id, newer: true })) dispatch(fetch({ page, query: { since_id: state.toots[0].id } }))
} }
refreshing={status === 'loading'} refreshing={state.status === 'loading'}
onEndReached={() => onEndReached={() => {
dispatch(fetch({ ...timeline, id: toots[toots.length - 1].id })) if (!timelineReady) {
dispatch(
fetch({
page,
query: {
max_id: state.toots[state.toots.length - 1].id
} }
})
)
setTimelineReady(true)
}
}}
onEndReachedThreshold={0.5} onEndReachedThreshold={0.5}
onMomentumScrollBegin={() => setTimelineReady(false)}
/> />
{status === 'loading' && <ActivityIndicator />} {state.status === 'loading' && <ActivityIndicator />}
</> </>
) )
} }
const Notifications = ({ dispatch, toots, status, timeline }) => {
return (
<>
<FlatList
data={toots}
keyExtractor={({ status: { id } }) => id}
renderItem={({ item }) => (
<TootTimeline item={item} notification={true} />
)}
onRefresh={() =>
dispatch(fetch({ ...timeline, id: toots[0].id, newer: true }))
}
refreshing={status === 'loading'}
onEndReached={() =>
dispatch(fetch({ ...timeline, id: toots[toots.length - 1].id }))
}
onEndReachedThreshold={0.5}
/>
{status === 'loading' && <ActivityIndicator />}
</>
)
}
export default function Timeline ({ timeline }) {
const dispatch = useDispatch()
const toots = useSelector(state => getToots(state)(timeline))
const status = useSelector(state => getStatus(state)(timeline))
useEffect(() => {
if (status === 'idle') {
dispatch(fetch(timeline))
}
}, [status, dispatch])
let content
if (status === 'error') {
content = <Text>Error message</Text>
} else {
if (timeline.endpoint === 'notifications') {
content = (
<Notifications
dispatch={dispatch}
toots={toots}
status={status}
timeline={timeline}
/>
)
} else {
content = (
<Default
dispatch={dispatch}
toots={toots}
status={status}
timeline={timeline}
/>
)
}
}
return <View>{content}</View> return <View>{content}</View>
} }
Timeline.propTypes = { Timeline.propTypes = {
timeline: PropTypes.exact({ page: PropTypes.string.isRequired,
remote: PropTypes.bool, hashtag: PropTypes.string,
endpoint: PropTypes.string, list: PropTypes.string
local: PropTypes.bool
}).isRequired
} }

View File

@ -1,11 +1,14 @@
import React, { useEffect, useRef, useState } from 'react' import React, { useEffect, useRef, useState } from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { Animated, Dimensions, View } from 'react-native' import { Animated, Dimensions, Text, View } from 'react-native'
import { createNativeStackNavigator } from 'react-native-screens/native-stack' import { createNativeStackNavigator } from 'react-native-screens/native-stack'
import SegmentedControl from '@react-native-community/segmented-control' import SegmentedControl from '@react-native-community/segmented-control'
import { Feather } from '@expo/vector-icons' import { Feather } from '@expo/vector-icons'
import Timeline from './Timeline' import Timeline from './Timeline'
import Account from 'src/stacks/Shared/Account'
import Hashtag from 'src/stacks/Shared/Hashtag'
import Webview from 'src/stacks/Shared/Webview'
const Stack = createNativeStackNavigator() const Stack = createNativeStackNavigator()
@ -21,8 +24,10 @@ export default function TimelinesCombined ({ name, content }) {
const moveAnimation = useRef(new Animated.Value(0)).current const moveAnimation = useRef(new Animated.Value(0)).current
return ( return (
<Stack.Navigator <Stack.Navigator>
screenOptions={{ <Stack.Screen
name={name}
options={{
statusBarAnimation: 'none', statusBarAnimation: 'none',
headerRight: () => headerRight: () =>
renderHeader ? ( renderHeader ? (
@ -48,7 +53,6 @@ export default function TimelinesCombined ({ name, content }) {
) : null ) : null
}} }}
> >
<Stack.Screen name={name}>
{props => ( {props => (
<Animated.View <Animated.View
style={{ style={{
@ -59,14 +63,35 @@ export default function TimelinesCombined ({ name, content }) {
{...props} {...props}
> >
<View style={{ width: Dimensions.get('window').width }}> <View style={{ width: Dimensions.get('window').width }}>
<Timeline timeline={content[0].timeline} /> <Timeline page={content[0].page} />
</View> </View>
<View style={{ width: Dimensions.get('window').width }}> <View style={{ width: Dimensions.get('window').width }}>
<Timeline timeline={content[1].timeline} /> <Timeline page={content[1].page} />
</View> </View>
</Animated.View> </Animated.View>
)} )}
</Stack.Screen> </Stack.Screen>
<Stack.Screen
name='Account'
component={Account}
options={({ route }) => ({
title: `${route.params.id}`
})}
/>
<Stack.Screen
name='Hashtag'
component={Hashtag}
options={({ route }) => ({
title: `#${decodeURIComponent(route.params.hashtag)}`
})}
/>
<Stack.Screen
name='Webview'
component={Webview}
options={({ route }) => ({
title: `${route.params.domain}`
})}
/>
</Stack.Navigator> </Stack.Navigator>
) )
} }
@ -76,7 +101,7 @@ TimelinesCombined.propTypes = {
content: PropTypes.arrayOf( content: PropTypes.arrayOf(
PropTypes.exact({ PropTypes.exact({
title: PropTypes.string.isRequired, title: PropTypes.string.isRequired,
timeline: Timeline.propTypes.timeline page: Timeline.propTypes.page
}) })
).isRequired ).isRequired
} }

View File

@ -0,0 +1,48 @@
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { client } from 'src/api/client'
export const fetch = createAsyncThunk(
'account/fetch',
async ({ id }, { getState }) => {
const instanceLocal = getState().instanceInfo.local + '/api/v1/'
return await client.get(`${instanceLocal}accounts/${id}`)
}
)
const accountInitState = {
account: {},
status: 'idle'
}
export const getState = state => state.account
export const accountSlice = createSlice({
name: 'account',
initialState: {
account: {},
status: 'idle'
},
reducers: {
reset: state => {
state.account = accountInitState
}
},
extraReducers: {
[fetch.pending]: state => {
state.status = 'loading'
},
[fetch.fulfilled]: (state, action) => {
state.status = 'succeeded'
state.account = action.payload
},
[fetch.rejected]: (state, action) => {
state.status = 'failed'
console.error(action.error.message)
}
}
})
export const { reset } = accountSlice.actions
export default accountSlice.reducer

View File

@ -16,9 +16,9 @@ const instanceInfoSlice = createSlice({
} }
}) })
export const getCurrent = state => state.current // export const getCurrent = state => state.current
export const getCurrentToken = state => state.currentToken // export const getCurrentToken = state => state.currentToken
export const getRemote = state => state.remote // export const getRemote = state => state.remote
// export const { increment, decrement, incrementByAmount } = counterSlice.actions // export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default instanceInfoSlice.reducer export default instanceInfoSlice.reducer

View File

@ -2,19 +2,21 @@ import { configureStore } from '@reduxjs/toolkit'
import instanceInfoSlice from 'src/stacks/common/instanceInfoSlice' import instanceInfoSlice from 'src/stacks/common/instanceInfoSlice'
import timelineSlice from 'src/stacks/common/timelineSlice' import timelineSlice from 'src/stacks/common/timelineSlice'
import accountSlice from 'src/stacks/common/accountSlice'
// get site information from local storage and pass to reducers // get site information from local storage and pass to reducers
const preloadedState = { const preloadedState = {
instanceInfo: { instanceInfo: {
current: 'social.xmflsct.com', local: 'social.xmflsct.com',
currentToken: 'qjzJ0IjvZ1apsn0_wBkGcdjKgX7Dao9KEPhGwggPwAo', localToken: 'qjzJ0IjvZ1apsn0_wBkGcdjKgX7Dao9KEPhGwggPwAo',
remote: 'mastodon.social' remote: 'mastodon.social'
} }
} }
const reducer = { const reducer = {
instanceInfo: instanceInfoSlice, instanceInfo: instanceInfoSlice,
timelines: timelineSlice timelines: timelineSlice,
account: accountSlice
} }
export default configureStore({ export default configureStore({

View File

@ -3,85 +3,104 @@ import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { client } from 'src/api/client' import { client } from 'src/api/client'
// Naming convention // Naming convention
// Following: home // Following: timelines/home
// Local: public/local // Local: timelines/public/local
// CurrentPublic: public // LocalPublic: timelines/public
// RemotePublic: remote // RemotePublic: remote/timelines/public
// Notifications: notifications // Notifications: notifications
// Hashtag: hastag
const checkInstance = ({ remote, endpoint, local }) => // List: list
remote ? 'remote' : `${endpoint}${local ? '/local' : ''}`
export const fetch = createAsyncThunk( export const fetch = createAsyncThunk(
'timeline/fetch', 'timeline/fetch',
async ({ remote, endpoint, local, id, newer }, { getState }) => { async ({ page, query, hashtag, list }, { getState }) => {
const instance = remote const instanceLocal = getState().instanceInfo.local + '/api/v1/'
? `${getState().instanceInfo.remote}/api/v1/timelines/public` const instanceRemote = getState().instanceInfo.remote + '/api/v1/'
: endpoint === 'notifications'
? `${getState().instanceInfo.current}/api/v1/${endpoint}`
: `${getState().instanceInfo.current}/api/v1/timelines/${endpoint}`
const query = {
...(local && { local: 'true' }),
...(newer ? { since_id: id } : id && { max_id: id })
}
const header = { const header = {
...(getState().instanceInfo.currentToken && {
headers: { headers: {
Authorization: `Bearer ${getState().instanceInfo.currentToken}` Authorization: `Bearer ${getState().instanceInfo.localToken}`
} }
})
} }
return await client.get(instance, query, header) switch (page) {
case 'Following':
return await client.get(`${instanceLocal}timelines/home`, query, header)
case 'Local':
query ? (query.local = true) : (query = { local: 'true' })
return await client.get(
`${instanceLocal}timelines/public`,
query,
header
)
case 'LocalPublic':
return await client.get(
`${instanceLocal}timelines/public`,
query,
header
)
case 'RemotePublic':
return await client.get(`${instanceRemote}timelines/public`, query)
case 'Notifications':
return await client.get(`${instanceLocal}notifications`, query, header)
case 'Hashtag':
return await client.get(
`${instanceLocal}timelines/tag/${hashtag}`,
query,
header
)
case 'List':
return await client.get(
`${instanceLocal}timelines/list/${list}`,
query,
header
)
default:
console.error('Timeline type error')
}
} }
) )
export const getToots = state => instance => const timelineInitState = {
state.timelines[checkInstance(instance)].toots toots: [],
export const getStatus = state => instance => status: 'idle'
state.timelines[checkInstance(instance)].status }
export const getState = state => page => state.timelines[page]
export const timelineSlice = createSlice({ export const timelineSlice = createSlice({
name: 'timeline', name: 'timeline',
initialState: { initialState: {
home: { Following: timelineInitState,
toots: [], Local: timelineInitState,
status: 'idle' LocalPublic: timelineInitState,
RemotePublic: timelineInitState,
Notifications: timelineInitState,
Hashtag: timelineInitState,
List: timelineInitState
}, },
'public/local': { reducers: {
toots: [], reset (state, action) {
status: 'idle' state[action.payload] = timelineInitState
},
public: {
toots: [],
status: 'idle'
},
remote: {
toots: [],
status: 'idle'
},
notifications: {
toots: [],
status: 'idle'
} }
}, },
extraReducers: { extraReducers: {
[fetch.pending]: (state, action) => { [fetch.pending]: (state, action) => {
state[checkInstance(action.meta.arg)].status = 'loading' state[action.meta.arg.page].status = 'loading'
}, },
[fetch.fulfilled]: (state, action) => { [fetch.fulfilled]: (state, action) => {
state[checkInstance(action.meta.arg)].status = 'succeeded' state[action.meta.arg.page].status = 'succeeded'
action.meta.arg.newer if (action.meta.arg.query && action.meta.arg.query.since_id) {
? state[checkInstance(action.meta.arg)].toots.unshift(...action.payload) state[action.meta.arg.page].toots.unshift(...action.payload)
: state[checkInstance(action.meta.arg)].toots.push(...action.payload) } else {
state[action.meta.arg.page].toots.push(...action.payload)
}
}, },
[fetch.rejected]: (state, action) => { [fetch.rejected]: (state, action) => {
state[action.meta.arg.page].status = 'failed'
console.error(action.error.message) console.error(action.error.message)
state[checkInstance(action.meta.arg)].status = 'failed'
} }
} }
}) })
export const { reset } = timelineSlice.actions
export default timelineSlice.reducer export default timelineSlice.reducer