about summary refs log tree commit diff
path: root/src/view/com/composer/Composer.tsx
blob: 6a15599d817b398bed7614cff0f889ec31c5ee3b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import React, {useState, forwardRef, useImperativeHandle} from 'react'
import {KeyboardAvoidingView, StyleSheet, TextInput, View} from 'react-native'
import Toast from '../util/Toast'
import ProgressCircle from '../util/ProgressCircle'
import {useStores} from '../../../state'
import {s} from '../../lib/styles'
import * as apilib from '../../../state/lib/api'

const MAX_TEXT_LENGTH = 256
const WARNING_TEXT_LENGTH = 200
const DANGER_TEXT_LENGTH = 255

export const Composer = forwardRef(function Composer(
  {
    replyTo,
  }: {
    replyTo: string | undefined
  },
  ref,
) {
  const store = useStores()
  const [text, setText] = useState('')

  const onChangeText = (newText: string) => {
    if (newText.length > MAX_TEXT_LENGTH) {
      setText(newText.slice(0, MAX_TEXT_LENGTH))
    } else {
      setText(newText)
    }
  }

  useImperativeHandle(ref, () => ({
    async publish() {
      if (text.trim().length === 0) {
        return false
      }
      await apilib.post(store.api, 'alice.com', text, replyTo)
      Toast.show(`Your ${replyTo ? 'reply' : 'post'} has been created`, {
        duration: Toast.durations.LONG,
        position: Toast.positions.TOP,
        shadow: true,
        animation: true,
        hideOnPress: true,
      })
      return true
    },
  }))

  const progressColor =
    text.length > DANGER_TEXT_LENGTH
      ? '#e60000'
      : text.length > WARNING_TEXT_LENGTH
      ? '#f7c600'
      : undefined

  return (
    <KeyboardAvoidingView style={styles.outer} behavior="padding">
      <TextInput
        multiline
        scrollEnabled
        onChangeText={text => onChangeText(text)}
        value={text}
        placeholder={replyTo ? 'Write your reply' : "What's new in the scene?"}
        style={styles.textInput}
      />
      <View style={[s.flexRow, s.pt10, s.pb10, s.pr5]}>
        <View style={s.flex1} />
        <View>
          <ProgressCircle
            color={progressColor}
            progress={text.length / MAX_TEXT_LENGTH}
          />
        </View>
      </View>
    </KeyboardAvoidingView>
  )
})

const styles = StyleSheet.create({
  outer: {
    flexDirection: 'column',
    backgroundColor: '#fff',
    padding: 10,
    height: '100%',
  },
  textInput: {
    flex: 1,
    padding: 10,
  },
})