}
37 | }
38 |
--------------------------------------------------------------------------------
/src/bindings/TableView.res:
--------------------------------------------------------------------------------
1 | module TableView = {
2 | @module("react-native-tableview-simple") @react.component
3 | external make: (~children: React.element=?) => React.element = "TableView"
4 | }
5 |
6 | module Section = {
7 | @module("react-native-tableview-simple") @react.component
8 | external make: (
9 | ~header: string=?,
10 | ~sectionTintColor: [#transparent]=?,
11 | ~children: React.element=?,
12 | ) => React.element = "Section"
13 | }
14 |
15 | module Cell = {
16 | @module("react-native-tableview-simple") @react.component
17 | external make: (
18 | ~title: string=?,
19 | ~cellContentView: React.element=?,
20 | ~cellAccessoryView: React.element=?,
21 | ~accessory: [#Checkmark | #DisclosureIndicator]=?,
22 | ~accessoryColor: string=?,
23 | ~onPress: unit => unit=?,
24 | ~withSafeAreaView: bool=?,
25 | ) => React.element = "Cell"
26 | }
27 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "name": "echojs-reader",
4 | "slug": "echojs-reader",
5 | "version": "1.0.0",
6 | "orientation": "portrait",
7 | "icon": "./assets/icon.png",
8 | "userInterfaceStyle": "light",
9 | "splash": {
10 | "image": "./assets/splash.png",
11 | "resizeMode": "contain",
12 | "backgroundColor": "#ffffff"
13 | },
14 | "updates": {
15 | "fallbackToCacheTimeout": 0
16 | },
17 | "assetBundlePatterns": ["**/*"],
18 | "ios": {
19 | "supportsTablet": true,
20 | "bundleIdentifier": "com.pd4d10.LamerNews"
21 | },
22 | "android": {
23 | "package": "io.github.pd4d10.echojsreader",
24 | "adaptiveIcon": {
25 | "foregroundImage": "./assets/adaptive-icon.png",
26 | "backgroundColor": "#FFFFFF"
27 | }
28 | },
29 | "web": {
30 | "favicon": "./assets/favicon.png"
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # EchoJS Reader
2 |
3 | Open source [EchoJS](https://echojs.com/) reader built with React Native.
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | ## Installation
15 |
16 | Click badges above to install it from Apple App Store or Google Play.
17 |
18 | Android users can also download APK file from [release page](https://github.com/pd4d10/echojs-reader/releases) and install it manually.
19 |
20 | ## Screenshots
21 |
22 | 
23 |
24 | ## License
25 |
26 | Apache-2.0
27 |
--------------------------------------------------------------------------------
/src/main.res:
--------------------------------------------------------------------------------
1 | module App = {
2 | @react.component
3 | let make = () => {
4 | let {colors} = Theme.context->React.useContext->Option.getExn
5 |
6 |
14 | Some(colors.headerAndroidBar)
18 | | _ => None
19 | }}
20 | />
21 |
22 |
23 | }
24 | }
25 |
26 | @react.component
27 | let default = () => {
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "echojs-reader",
3 | "version": "1.1.0",
4 | "main": "node_modules/expo/AppEntry.js",
5 | "scripts": {
6 | "start": "expo start",
7 | "android": "expo start --android",
8 | "ios": "expo start --ios",
9 | "web": "expo start --web"
10 | },
11 | "dependencies": {
12 | "@expo/react-native-action-sheet": "^4.0.1",
13 | "@react-native-async-storage/async-storage": "^1.18.0",
14 | "@react-navigation/bottom-tabs": "^6.5.7",
15 | "@react-navigation/native": "^6.1.6",
16 | "@react-navigation/native-stack": "^6.9.12",
17 | "date-fns": "^2.29.3",
18 | "expo": "^48.0.9",
19 | "expo-status-bar": "^1.4.4",
20 | "expo-web-browser": "^12.1.1",
21 | "react": "^18.2.0",
22 | "react-native": "^0.71.4",
23 | "react-native-gesture-handler": "^2.9.0",
24 | "react-native-reanimated": "^3.0.2",
25 | "react-native-safe-area-context": "4.5.0",
26 | "react-native-screens": "^3.20.0",
27 | "react-native-tableview-simple": "^4.4.0"
28 | },
29 | "devDependencies": {
30 | "@babel/core": "^7.21.3",
31 | "@greenlabs/ppx-spice": "^0.1.12",
32 | "@rescript-react-native/async-storage": "^1.6.3",
33 | "@rescript/core": "^0.2.0",
34 | "@rescript/react": "^0.11.0",
35 | "rescript": "^10.1.3",
36 | "rescript-react-native": "^0.70.0",
37 | "rescript-react-navigation": "^6.0.3",
38 | "rescript-webapi": "^0.7.0"
39 | },
40 | "private": true,
41 | "packageManager": "pnpm@8.0.0"
42 | }
43 |
--------------------------------------------------------------------------------
/src/navigators/BottomTabs.res:
--------------------------------------------------------------------------------
1 | module M = {
2 | type params
3 | }
4 | module Tab = ReactNavigation.BottomTabs.Make(M)
5 |
6 | @react.component
7 | let make = () => {
8 | let {colors} = Theme.context->React.useContext->Option.getExn
9 |
10 | let getIconColor = focused => {
11 | focused ? colors.primary : colors.tabInactive
12 | }
13 |
14 |
16 | Tab.options(
17 | ~headerShown=false,
18 | ~tabBarActiveTintColor=colors.primary,
19 | ~tabBarInactiveTintColor=colors.tabInactive,
20 | (),
21 | )}>
22 |
26 | Tab.options(
27 | ~tabBarIcon=({focused}) =>
28 | ,
29 | (),
30 | )}
31 | />
32 |
36 | Tab.options(
37 | ~tabBarIcon=({focused}) =>
38 | ,
39 | (),
40 | )}
41 | />
42 |
46 | Tab.options(
47 | ~tabBarIcon=({focused}) =>
48 | ,
49 | (),
50 | )}
51 | />
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/components/CommentItem.res:
--------------------------------------------------------------------------------
1 | open ReactNative
2 |
3 | @react.component
4 | let rec make = (~item: Model.comment, ~level) => {
5 | let marginLeft = level->Float.fromInt *. 20.
6 | let theme = Theme.context->React.useContext->Option.getExn
7 |
8 | <>
9 | Style.dp,
13 | ~marginLeft=marginLeft->Style.dp,
14 | // borderTopColor: colors.contentBorder,
15 | // borderTopWidth: this.props.index === 0 ? 0 : 1,
16 | (),
17 | )}>
18 |
19 | Style.dp, ())}>
21 |
22 | {` | ${item.ctime->Utils.timeAgo} ago`->React.string}
23 |
24 |
25 | {item.body->React.string}
26 |
27 |
28 | Style.dp,
32 | ~marginTop=2.->Style.dp,
33 | ~paddingLeft=10.->Style.dp,
34 | (),
35 | )}>
36 | {
37 | let up = item.up
38 | let down = item.down->Option.getWithDefault(0)
39 |
40 | }
41 |
42 |
43 | {item.replies
44 | ->Array.map(reply =>
45 | make->React.createElement({
46 | // "key": reply.ctime + reply.username,
47 | "item": reply,
48 | "level": level + 1,
49 | })
50 | )
51 | ->React.array}
52 | >
53 | }
54 |
--------------------------------------------------------------------------------
/src/screens/DetailScreen.res:
--------------------------------------------------------------------------------
1 | open ReactNative
2 |
3 | @react.component
4 | let make = (~navigation as _, ~route as _) => {
5 | let route = ReactNavigation.Native.useRoute()->Nullable.toOption->Option.getExn
6 | let params: Model.post = route.params->Option.getExn
7 |
8 | let theme = Theme.context->React.useContext->Option.getExn
9 | let auth = Auth.context->React.useContext
10 |
11 | let (loading, setLoading) = React.useState(_ => false)
12 | let (comments, setComments) = React.useState(_ => [])
13 |
14 | React.useEffect0(() => {
15 | let init = async () => {
16 | try {
17 | setLoading(_ => true)
18 | // let id = "22273"
19 | let id = params.id
20 | let json = await auth->Auth.fetch(`/getcomments/${id}`, #get)
21 | let {comments} = json->Model.Api.comments_decode->Result.getExn
22 | setComments(_ =>
23 | comments->Array.sort((a, b) => a.ctime->Float.toInt - b.ctime->Float.toInt)
24 | )
25 | setLoading(_ => false)
26 | } catch {
27 | | Exn.Error(obj) => setLoading(_ => false)
28 | // TODO:
29 | }
30 | }
31 |
32 | init()->ignore
33 |
34 | None
35 | })
36 |
37 | Style.dp,
41 | (),
42 | )}>
43 | {
47 | ()
48 | }}
49 | />
50 |
57 | {if loading {
58 | Style.dp, ())} />
59 | } else {
60 | comments
61 | ->Array.map(comment => {
62 | Float.toString ++ comment.username} item=comment level=0 />
63 | })
64 | ->React.array
65 | }}
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/bindings/Expo.res:
--------------------------------------------------------------------------------
1 | module WebBrowser = {
2 | type openOptions = {
3 | controlsColor?: string,
4 | dismissButtonStyle?: [#done | #close | #cancel],
5 | toolbarColor?: string,
6 | }
7 |
8 | type result = {@as("type") type_: [#cancel | #dismiss | #locked | #opened]}
9 |
10 | @module("expo-web-browser")
11 | external openBrowserAsync: (string, ~browserParams: openOptions=?, unit) => promise =
12 | "openBrowserAsync"
13 | }
14 |
15 | module StatusBar = {
16 | type style = [#auto | #inverted | #light | #dark]
17 |
18 | @react.component @module("expo-status-bar")
19 | external make: (~style: style=?, ~backgroundColor: string=?) => React.element = "StatusBar"
20 | }
21 |
22 | module ActionSheet = {
23 | type options = {
24 | title?: string,
25 | options: array,
26 | cancelButtonIndex?: int,
27 | }
28 |
29 | type actionSheetProps = {showActionSheetWithOptions: (. options, ~callback: int => unit) => unit}
30 |
31 | @module("@expo/react-native-action-sheet")
32 | external useActionSheet: unit => actionSheetProps = "useActionSheet"
33 |
34 | module ActionSheetProvider = {
35 | @react.component @module("@expo/react-native-action-sheet")
36 | external make: (~children: React.element=?) => React.element = "ActionSheetProvider"
37 | }
38 | }
39 |
40 | module VectorIcons = {
41 | module Ionicons = {
42 | @react.component @module("@expo/vector-icons")
43 | external make: (
44 | ~name: string=?,
45 | ~size: int=?,
46 | ~color: string=?,
47 | ~style: ReactNative.Style.t=?,
48 | unit,
49 | ) => React.element = "Ionicons"
50 | }
51 | module Entypo = {
52 | @react.component @module("@expo/vector-icons")
53 | external make: (
54 | ~name: string=?,
55 | ~size: int=?,
56 | ~color: string=?,
57 | ~style: ReactNative.Style.t=?,
58 | unit,
59 | ) => React.element = "Entypo"
60 | }
61 | module MaterialCommunityIcons = {
62 | @react.component @module("@expo/vector-icons")
63 | external make: (
64 | ~name: string=?,
65 | ~size: int=?,
66 | ~color: string=?,
67 | ~style: ReactNative.Style.t=?,
68 | unit,
69 | ) => React.element = "MaterialCommunityIcons"
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/screens/LoginScreen.res:
--------------------------------------------------------------------------------
1 | open ReactNative
2 | open TableView
3 |
4 | module M = {
5 | type params
6 | type options
7 | }
8 | module Navigation = ReactNavigation.Core.NavigationScreenProp(M)
9 |
10 | @react.component
11 | let make = (~navigation, ~route as _) => {
12 | let {colors} = Theme.context->React.useContext->Option.getExn
13 | let auth = Auth.context->React.useContext
14 |
15 | let (username, setUsername) = React.useState(_ => "")
16 | let (password, setPassword) = React.useState(_ => "")
17 |
18 |
19 |
20 | setUsername(_ => v)}
25 | style={Style.textStyle(~fontSize=16., ~flex=1., ())}
26 | placeholder="Username"
27 | />}
28 | />
29 | | setPassword(_ => v)}
34 | style={Style.textStyle(~fontSize=16., ~flex=1., ())}
35 | placeholder="Password"
36 | secureTextEntry=true
37 | />}
38 | />
39 | | |
40 |
41 |
42 |
59 |
60 |
78 |
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/src/screens/SettingsScreen.res:
--------------------------------------------------------------------------------
1 | open ReactNative
2 | open TableView
3 |
4 | module M = {
5 | type params
6 | type options
7 | }
8 | module Navigation = ReactNavigation.Core.NavigationScreenProp(M)
9 |
10 | @react.component
11 | let make = (~navigation, ~route as _) => {
12 | let auth = Auth.context->React.useContext
13 | let {theme, setTheme, colors} = Theme.context->React.useContext->Option.getExn
14 |
15 | Style.dp, ())}>
16 |
17 |
18 | {switch auth.state {
19 | | Some({username}) =>
20 |
22 | {username->React.string}
23 | }
24 | cellAccessoryView={ |
60 |
61 | {[Theme.Theme.Light, Theme.Theme.Dark]
62 | ->Array.map(item => {
63 | let themeS = Theme.Theme.toString(item)
64 |
65 | {
71 | setTheme(item)
72 | }}
73 | />
74 | })
75 | ->React.array}
76 | |
77 |
78 |
79 | {
83 | Expo.WebBrowser.openBrowserAsync("https://github.com/pd4d10/echojs-reader", ())->ignore
84 | }}
85 | />
86 | |
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/contexts/Theme.res:
--------------------------------------------------------------------------------
1 | module Theme = {
2 | type t = Light | Dark
3 | let toString = v => {
4 | switch v {
5 | | Light => "light"
6 | | Dark => "dark"
7 | }
8 | }
9 | let fromString = v => {
10 | switch v {
11 | | "light" => Some(Light)
12 | | "dark" => Some(Dark)
13 | | _ => None
14 | }
15 | }
16 | }
17 |
18 | type colors = {
19 | primary: string,
20 | headerStatusBar: Expo.StatusBar.style,
21 | headerAndroidBar: string,
22 | contentTitle: string,
23 | contentUrl: string,
24 | contentUser: string,
25 | contentBorder: string,
26 | contentBackground: string,
27 | contentIcon: string,
28 | tabInactive: string,
29 | safariStatusBar: ReactNative.StatusBar.barStyle,
30 | settingsActive: string,
31 | settingsAndroidSwitchActiveBackground: string,
32 | }
33 |
34 | type value = {
35 | theme: Theme.t,
36 | setTheme: Theme.t => unit,
37 | colors: colors,
38 | }
39 |
40 | let context = React.createContext(None)
41 |
42 | module Provider = {
43 | @react.component
44 | let make = (~children) => {
45 | let (theme, _setTheme) = React.useState(_ => None)
46 |
47 | React.useEffect0(() => {
48 | ReactNativeAsyncStorage.getItem("theme")
49 | ->Promise.then(v => {
50 | _setTheme(
51 | _ =>
52 | v->Null.toOption->Option.flatMap(Theme.fromString)->Option.getWithDefault(Light)->Some,
53 | )
54 | Promise.resolve()
55 | })
56 | ->ignore
57 |
58 | None
59 | })
60 |
61 | let setTheme = v => {
62 | _setTheme(_ => v->Some)
63 | ReactNativeAsyncStorage.setItem("theme", v->Theme.toString)->ignore
64 | }
65 |
66 | let value = theme->Option.flatMap(theme => {
67 | let colors = switch theme {
68 | | Theme.Dark => {
69 | // TODO:
70 | primary: "#af1d1d",
71 | headerStatusBar: #dark,
72 | headerAndroidBar: "#831616",
73 | contentTitle: "#000",
74 | contentUrl: "#999",
75 | contentUser: "#666",
76 | contentBorder: "#eee",
77 | contentBackground: "#fff",
78 | contentIcon: "#444",
79 | tabInactive: "grey",
80 | safariStatusBar: #"dark-content",
81 | settingsActive: "#af1d1d",
82 | settingsAndroidSwitchActiveBackground: "#faa",
83 | }
84 | | _ => {
85 | primary: "#af1d1d",
86 | headerStatusBar: #light,
87 | headerAndroidBar: "#831616",
88 | contentTitle: "#000",
89 | contentUrl: "#999",
90 | contentUser: "#666",
91 | contentBorder: "#eee",
92 | contentBackground: "#fff",
93 | contentIcon: "#444",
94 | tabInactive: "grey",
95 | safariStatusBar: #"dark-content",
96 | settingsActive: "#af1d1d",
97 | settingsAndroidSwitchActiveBackground: "#faa",
98 | }
99 | }
100 |
101 | {theme, setTheme, colors}->Some
102 | })
103 |
104 | switch value {
105 | | None => React.null
106 | | Some(value) =>
107 | context->React.Context.provider->React.createElement({value: Some(value), children})
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/assets/icon.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
27 |
--------------------------------------------------------------------------------
/src/contexts/Auth.res:
--------------------------------------------------------------------------------
1 | type state = {
2 | auth: string,
3 | username: string,
4 | secret: string,
5 | }
6 |
7 | let initialState = None
8 |
9 | type action = Update({auth: string, username: string, secret: string}) | Drop
10 |
11 | let reducer = (_state, action) =>
12 | switch action {
13 | | Update({auth, username, secret}) =>
14 | {
15 | auth,
16 | username,
17 | secret,
18 | }->Some
19 | | Drop => None
20 | }
21 |
22 | type value = {state: option, dispatch: action => unit}
23 |
24 | let context = React.createContext({state: initialState, dispatch: _ => ()})
25 |
26 | let fetch = async (ctx, url, method) => {
27 | open Webapi.Fetch
28 | let cookie = ctx.state->Option.map(state => `auth=${state.auth}`)
29 | let method_ = switch method {
30 | | #post => Webapi.Fetch.Post
31 | | #get | _ => Webapi.Fetch.Get
32 | }
33 | let headers = HeadersInit.make({"Cookie": cookie})
34 | let init = RequestInit.make(~method_, ~headers, ())
35 |
36 | Console.log3("req:", url, method)
37 | let res = await fetchWithInit("https://echojs.com/api" ++ url, init)
38 | let json = await res->Response.json
39 | Console.log2("res:", json)
40 |
41 | // TODO:
42 | // if (json.status === "err") {
43 | // throw new Error(json.error);
44 | // }
45 | json
46 | }
47 |
48 | let createAccount = async (ctx, ~username, ~password) => {
49 | let _json = await ctx->fetch(`/create_account?username=${username}&password=${password}`, #post)
50 | // Seems EchoJS's create account API does not return secret
51 | // So don't use any data from this API
52 | // Just create account and call login API again to login
53 | }
54 |
55 | let login = async (ctx, ~username, ~password) => {
56 | let json = await ctx->fetch(`/login?username=${username}&password=${password}`, #get)
57 | let data = json->Model.Api.login_decode->Result.getExn
58 | await ReactNativeAsyncStorage.multiSet([
59 | ("auth", data.auth),
60 | ("username", username),
61 | ("secret", data.apisecret),
62 | ])
63 | Update({auth: data.auth, username, secret: data.apisecret})->ctx.dispatch
64 | }
65 |
66 | let logout = async ctx => {
67 | switch ctx.state {
68 | | None => ()
69 | | Some(state) => {
70 | let _json = await ctx->fetch(`/logout?apisecret=${state.secret}`, #post)
71 | await ReactNativeAsyncStorage.multiRemove(["auth", "username", "secret"])
72 | Drop->ctx.dispatch
73 | }
74 | }
75 | }
76 |
77 | module Provider = {
78 | @react.component
79 | let make = (~children) => {
80 | let (state, dispatch) = React.useReducer(reducer, initialState)
81 |
82 | React.useEffect0(() => {
83 | // for debugging
84 | ReactNativeAsyncStorage.getAllKeys()
85 | ->Promise.then(async keys => {
86 | switch keys->Null.toOption {
87 | | Some(keys) => {
88 | let data = await ReactNativeAsyncStorage.multiGet(keys)
89 | Console.log(data)
90 | }
91 |
92 | | _ => ()
93 | }
94 | })
95 | ->ignore
96 |
97 | ReactNativeAsyncStorage.multiGet(["auth", "username", "secret"])
98 | ->Promise.then(async items => {
99 | switch [0, 1, 2]->Array.map(
100 | index => items[index]->Option.flatMap(((_key, value)) => value->Null.toOption),
101 | ) {
102 | | [Some(auth), Some(username), Some(secret)] => Update({auth, username, secret})->dispatch
103 | | _ => ()
104 | }
105 | })
106 | ->ignore
107 |
108 | None
109 | })
110 |
111 | context->React.Context.provider->React.createElement({value: {state, dispatch}, children})
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/src/components/Posts.res:
--------------------------------------------------------------------------------
1 | open ReactNative
2 |
3 | @react.component
4 | let make = (~sort) => {
5 | let {colors} = Theme.context->React.useContext->Option.getExn
6 | let auth = Auth.context->React.useContext
7 |
8 | let (first, setFirst) = React.useState(() => false)
9 | let (refreshing, setRefreshing) = React.useState(() => false)
10 | let (loadingMore, setLoadingMore) = React.useState(() => false)
11 | let (items, setItems) = React.useState(() => [])
12 | let (end, setEnd) = React.useState(() => false)
13 |
14 | let pageSize = 30
15 | let fetchData = async (~anchor=0, ()) => {
16 | let json =
17 | await auth->Auth.fetch(
18 | `/getnews/${sort}/${anchor->Int.toString}/${pageSize->Int.toString}`,
19 | #get,
20 | )
21 | let {news} = json->Model.Api.posts_decode->Result.getExn
22 | news
23 | }
24 |
25 | React.useEffect0(() => {
26 | let init = async () => {
27 | setFirst(_ => true)
28 | let items = await fetchData()
29 | setItems(_ => items)
30 | setEnd(_ => items->Belt.Array.length < pageSize)
31 | setFirst(_ => false)
32 | }
33 | init()->ignore
34 |
35 | None
36 | })
37 |
38 |
45 | {switch first {
46 | | true =>
47 | | false =>
48 | {
51 | switch item.del {
52 | | Some(true) =>
53 | Style.dp, ())}>
54 |
55 | {"[deleted news]"->React.string}
56 |
57 |
58 | | _ =>
59 | {
62 | let newItems = items->Belt.Array.map(item => {
63 | if item.id == id {
64 | switch type_ {
65 | | "up" => {
66 | ...item,
67 | up: (item.up->Int.fromString->Option.getExn + 1)->Int.toString,
68 | }
69 | | "down" => {
70 | ...item,
71 | down: (item.down->Int.fromString->Option.getExn + 1)->Int.toString,
72 | }
73 | | _ => assert false
74 | }
75 | } else {
76 | item
77 | }
78 | })
79 | setItems(_ => newItems)
80 | }}
81 | />
82 | }
83 | }}
84 | keyExtractor={(item, _) => item.id}
85 | \"ItemSeparatorComponent"={_ =>
86 | Style.dp, ~backgroundColor=colors.contentBorder, ())}
88 | />}
89 | refreshing
90 | onRefresh={_ => {
91 | switch refreshing {
92 | | true => ()
93 | | false => {
94 | let refresh = async () => {
95 | setRefreshing(_ => true)
96 | let items = await fetchData()
97 | setItems(_ => items)
98 | setEnd(_ => items->Belt.Array.length < pageSize)
99 | setRefreshing(_ => false)
100 | }
101 |
102 | refresh()->ignore
103 | }
104 | }
105 | }}
106 | onEndReached={_ => {
107 | switch loadingMore || end {
108 | | true => ()
109 | | false => {
110 | let loadMore = async () => {
111 | setLoadingMore(_ => true)
112 |
113 | let newItems = await fetchData(~anchor=items->Array.length, ())
114 | // remove duplicated items
115 | let ids = items->Array.map(item => item.id)->Set.fromArray
116 | let newItems = newItems->Array.filter(item => !Set.has(ids, item.id))
117 |
118 | setItems(_ => items->Array.concat(newItems))
119 | setEnd(_ => newItems->Array.length < pageSize)
120 | setLoadingMore(_ => false)
121 | }
122 |
123 | loadMore()->ignore
124 | }
125 | }
126 | }}
127 | onEndReachedThreshold=0.1
128 | \"ListFooterComponent"={_ =>
129 | Style.dp,
132 | ~height=56.->Style.dp,
133 | ~borderTopWidth=1.,
134 | ~borderColor=colors.contentBorder,
135 | ~alignItems=#center,
136 | (),
137 | )}>
138 | {switch loadingMore {
139 | | true =>
140 | | false => end ? : React.null
141 | }}
142 | }
143 | />
144 | }}
145 |
146 | }
147 |
--------------------------------------------------------------------------------
/src/components/PostItem.res:
--------------------------------------------------------------------------------
1 | open ReactNative
2 |
3 | module M = {
4 | type params = Model.post
5 | type options
6 | }
7 |
8 | module Navigation = ReactNavigation.Core.NavigationScreenProp(M)
9 |
10 | @react.component
11 | let make = (~item: Model.post, ~hascommentlink=true, ~updateVote) => {
12 | let navigation = ReactNavigation.Native.useNavigation()->Nullable.toOption
13 | let auth = Auth.context->React.useContext
14 | let theme = Theme.context->React.useContext->Option.getExn
15 | let actionSheet = Expo.ActionSheet.useActionSheet()
16 |
17 | let isText = item.url->String.startsWith("text://")
18 |
19 | Style.dp, ())}>
20 |
21 | {
23 | if isText {
24 | navigation->Option.forEach(navigation => {
25 | navigation->Navigation.navigateWithParams("Detail", item)
26 | })
27 | } else {
28 | Expo.WebBrowser.openBrowserAsync(item.url, ())->ignore
29 | }
30 | }}>
31 | Style.dp,
37 | (),
38 | )}>
39 | {item.title->React.string}
40 |
41 | {switch isText {
42 | | true => React.null
43 | | false =>
44 | Style.dp,
49 | (),
50 | )}>
51 | {
52 | let host = item.url->Utils.getHostFromUrl
53 | `at ${host}`->React.string
54 | }
55 |
56 | }}
57 |
58 |
59 |
60 | {switch item.ctime->Float.fromString {
61 | | Some(ctime) => ` | ${ctime->Utils.timeAgo} ago`->React.string
62 | | None => React.null
63 | }}
64 |
65 |
66 | {if hascommentlink {
67 | Style.dp,
71 | ~marginTop=2.->Style.dp,
72 | ~paddingLeft=10.->Style.dp,
73 | (),
74 | )}>
75 | {
77 | switch auth.state {
78 | | Some(state) =>
79 | switch item.voted {
80 | | Some(voted) => ReactNative.Alert.alert(~title=`You already vote ${voted}`, ())
81 | | _ =>
82 | actionSheet.showActionSheetWithOptions(.
83 | {
84 | title: `Vote for ${item.username}'s post`,
85 | options: ["Up", "Down", "cancel"],
86 | cancelButtonIndex: 2,
87 | },
88 | ~callback=index => {
89 | let vote = async () => {
90 | let type_ = switch index {
91 | | 0 => "up"
92 | | 1 => "down"
93 | | _ => assert false
94 | }
95 |
96 | let _ =
97 | await auth->Auth.fetch(
98 | `/votenews?news_id=${item.id}&vote_type=${type_}&apisecret=${state.secret}`,
99 | #post,
100 | )
101 | ReactNative.Alert.alert(~title="Vote succeed", ())
102 |
103 | updateVote(item.id, type_)
104 | }
105 |
106 | vote()->ignore
107 | },
108 | )
109 | }
110 |
111 | | None =>
112 | navigation->Option.forEach(navigation => {
113 | navigation->Navigation.navigate("Login")
114 | })
115 | }
116 | }}>
117 | {
118 | let up = item.up->Int.fromString->Option.getWithDefault(0)
119 | let down = item.down->Int.fromString->Option.getWithDefault(0)
120 |
121 | }
122 |
123 | {
126 | navigation->Option.forEach(navigation => {
127 | navigation->Navigation.navigateWithParams("Detail", item)
128 | })
129 | }}>
130 |
131 | Style.viewStyle(~marginRight=3.->Style.dp, ~marginTop=3.->Style.dp, ())
136 | | #ios | _ => Style.viewStyle(~marginRight=2.->Style.dp, ~marginTop=2.->Style.dp, ())
137 | }}
138 | />
139 |
140 | {item.comments->React.string}
141 |
142 |
143 |
144 |
145 | } else {
146 | React.null
147 | }}
148 |
149 | }
150 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------