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"
}
},
"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": {
"version": "1.2.0",
"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",
"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": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.2.tgz",
"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": {
"version": "0.3.4",
"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",
"integrity": "sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw=="
},
"html-entities": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/html-entities/-/html-entities-1.3.1.tgz",
"integrity": "sha512-rhE/4Z3hIhzHAUKbW8jVcCyuT5oJCXXqhN/6mXXVCpzTmvJnoH2HL/bt3EZ6p55jbFJBeAe1ZNpL5BugLujxNA=="
},
"htmlparser2": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz",
"integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==",
"htmlparser2-without-node-native": {
"version": "3.9.2",
"resolved": "https://registry.npmjs.org/htmlparser2-without-node-native/-/htmlparser2-without-node-native-3.9.2.tgz",
"integrity": "sha1-s+0FDYd9D/NGWWnjOYd7f59mMfY=",
"requires": {
"domelementtype": "^1.3.1",
"domelementtype": "^1.3.0",
"domhandler": "^2.3.0",
"domutils": "^1.5.1",
"entities": "^1.1.1",
"eventemitter2": "^1.0.0",
"inherits": "^2.0.1",
"readable-stream": "^3.1.1"
},
"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"
}
}
"readable-stream": "^2.0.2"
}
},
"http-errors": {
@ -3895,11 +3862,6 @@
"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": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-0.6.3.tgz",
@ -6619,6 +6581,15 @@
"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": {
"version": "1.3.0",
"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"
}
},
"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": {
"version": "3.1.4",
"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"
},
"dependencies": {
"@expo/vector-icons": "^10.0.0",
"@react-native-async-storage/async-storage": "^1.13.0",
"@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/native": "^5.7.6",
"@react-navigation/stack": "^5.9.3",
@ -22,15 +24,13 @@
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz",
"react-native-gesture-handler": "~1.7.0",
"react-native-htmlview": "^0.16.0",
"react-native-reanimated": "~1.13.0",
"react-native-render-html": "^4.2.4",
"react-native-safe-area-context": "3.1.4",
"react-native-screens": "~2.10.1",
"react-native-web": "~0.13.7",
"react-native-webview": "10.7.0",
"react-redux": "^7.2.1",
"@react-native-community/segmented-control": "2.1.1",
"@expo/vector-icons": "^10.0.0"
"react-redux": "^7.2.1"
},
"devDependencies": {
"@babel/core": "~7.9.0",

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
import React from 'react'
import PropTypes from 'prop-types'
import { Image, StyleSheet } from 'react-native'
import { Image, StyleSheet, View } from 'react-native'
export default function Avatar ({ uri }) {
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 { Dimensions, StyleSheet, View } from 'react-native'
import HTML from 'react-native-render-html'
import { StyleSheet, Text } from 'react-native'
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 }) {
const [viewWidth, setViewWidth] = useState()
return (
content && (
<View
style={{ width: '100%' }}
onLayout={e => setViewWidth(e.nativeEvent.layout.width)}
>
{viewWidth && (
<HTML html={content} containerStyle={{ width: viewWidth }} />
)}
</View>
)
function renderNode (navigation, node, index, mentions) {
if (node.name == 'a') {
const classes = node.attribs.class
const href = node.attribs.href
if (classes) {
if (classes.includes('hashtag')) {
return (
<Text
key={index}
style={styles.a}
onPress={() => {
const tag = href.split(new RegExp(/\/tag\/(.*)|\/tags\/(.*)/))
navigation.navigate('Hashtag', {
hashtag: tag[1] || tag[2]
})
}}
>
{node.children[0].data}
{node.children[1]?.children[0].data}
</Text>
)
} 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({
width: 50,
height: 50
a: {
color: 'blue'
}
})
Content.propTypes = {

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,14 @@
import React, { useEffect, useRef, useState } from 'react'
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 SegmentedControl from '@react-native-community/segmented-control'
import { Feather } from '@expo/vector-icons'
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()
@ -21,34 +24,35 @@ export default function TimelinesCombined ({ name, content }) {
const moveAnimation = useRef(new Animated.Value(0)).current
return (
<Stack.Navigator
screenOptions={{
statusBarAnimation: 'none',
headerRight: () =>
renderHeader ? (
<Feather name='search' size={24} color='black' />
) : null,
headerCenter: () =>
renderHeader ? (
<SegmentedControl
values={[content[0].title, content[1].title]}
selectedIndex={segment}
onChange={e => {
setSegment(e.nativeEvent.selectedSegmentIndex)
Animated.timing(moveAnimation, {
toValue:
-e.nativeEvent.selectedSegmentIndex *
Dimensions.get('window').width,
duration: 250,
useNativeDriver: false
}).start()
}}
style={{ width: 150, height: 30 }}
/>
) : null
}}
>
<Stack.Screen name={name}>
<Stack.Navigator>
<Stack.Screen
name={name}
options={{
statusBarAnimation: 'none',
headerRight: () =>
renderHeader ? (
<Feather name='search' size={24} color='black' />
) : null,
headerCenter: () =>
renderHeader ? (
<SegmentedControl
values={[content[0].title, content[1].title]}
selectedIndex={segment}
onChange={e => {
setSegment(e.nativeEvent.selectedSegmentIndex)
Animated.timing(moveAnimation, {
toValue:
-e.nativeEvent.selectedSegmentIndex *
Dimensions.get('window').width,
duration: 250,
useNativeDriver: false
}).start()
}}
style={{ width: 150, height: 30 }}
/>
) : null
}}
>
{props => (
<Animated.View
style={{
@ -59,14 +63,35 @@ export default function TimelinesCombined ({ name, content }) {
{...props}
>
<View style={{ width: Dimensions.get('window').width }}>
<Timeline timeline={content[0].timeline} />
<Timeline page={content[0].page} />
</View>
<View style={{ width: Dimensions.get('window').width }}>
<Timeline timeline={content[1].timeline} />
<Timeline page={content[1].page} />
</View>
</Animated.View>
)}
</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>
)
}
@ -76,7 +101,7 @@ TimelinesCombined.propTypes = {
content: PropTypes.arrayOf(
PropTypes.exact({
title: PropTypes.string.isRequired,
timeline: Timeline.propTypes.timeline
page: Timeline.propTypes.page
})
).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 getCurrentToken = state => state.currentToken
export const getRemote = state => state.remote
// export const getCurrent = state => state.current
// export const getCurrentToken = state => state.currentToken
// export const getRemote = state => state.remote
// export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default instanceInfoSlice.reducer

View File

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

View File

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