1
0
mirror of https://github.com/tooot-app/app synced 2025-02-18 04:40:57 +01:00

Rewrite emoji component logic to be more generic

This commit is contained in:
xmflsct 2022-09-18 01:02:25 +02:00
parent 535268c680
commit 8a054f2205
12 changed files with 367 additions and 455 deletions

View File

@ -4,19 +4,14 @@ import { useAccessibility } from '@utils/accessibility/AccessibilityManager'
import { useEmojisQuery } from '@utils/queryHooks/emojis'
import { getInstanceFrequentEmojis } from '@utils/slices/instancesSlice'
import { chunk, forEach, groupBy, sortBy } from 'lodash'
import React, {
Dispatch,
MutableRefObject,
PropsWithChildren,
SetStateAction,
useCallback,
useEffect,
useReducer
} from 'react'
import React, { PropsWithChildren, RefObject, useEffect, useReducer, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Keyboard, KeyboardAvoidingView, Text, TextInput, View } from 'react-native'
import FastImage from 'react-native-fast-image'
import { ScrollView } from 'react-native-gesture-handler'
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'
import { useSelector } from 'react-redux'
import EmojisContext, { emojisReducer } from './Emojis/helpers/EmojisContext'
import EmojisContext, { emojisReducer, EmojisState } from './Emojis/helpers/EmojisContext'
const prefetchEmojis = (
sortedEmojis: {
@ -45,71 +40,29 @@ const prefetchEmojis = (
} catch {}
}
export interface Props {
enabled?: boolean
value?: string
setValue:
| Dispatch<SetStateAction<string | undefined>>
| Dispatch<SetStateAction<string>>
selectionRange: MutableRefObject<{
start: number
end: number
}>
maxLength?: number
export type Props = {
inputProps: EmojisState['inputProps']
focusRef?: RefObject<TextInput>
}
const ComponentEmojis: React.FC<Props & PropsWithChildren> = ({
enabled = false,
value,
setValue,
selectionRange,
maxLength,
children
children,
inputProps,
focusRef
}) => {
const { reduceMotionEnabled } = useAccessibility()
const [emojisState, emojisDispatch] = useReducer(emojisReducer, {
enabled,
active: false,
emojis: [],
shortcode: null
targetProps: null,
inputProps
})
useEffect(() => {
if (emojisState.shortcode) {
addEmoji(emojisState.shortcode)
emojisDispatch({
type: 'shortcode',
payload: null
})
}
}, [emojisState.shortcode])
const addEmoji = useCallback(
(emojiShortcode: string) => {
if (value?.length) {
const contentFront = value.slice(0, selectionRange.current?.start)
const contentRear = value.slice(selectionRange.current?.end)
const whiteSpaceRear = /\s/g.test(contentRear.slice(-1))
const newTextWithSpace = ` ${emojiShortcode}${
whiteSpaceRear ? '' : ' '
}`
setValue(
[contentFront, newTextWithSpace, contentRear]
.join('')
.slice(0, maxLength)
)
} else {
setValue(`${emojiShortcode} `.slice(0, maxLength))
}
},
[value, selectionRange.current?.start, selectionRange.current?.end]
)
emojisDispatch({ type: 'input', payload: inputProps })
}, [inputProps])
const { t } = useTranslation()
const { data } = useEmojisQuery({ options: { enabled } })
const { data } = useEmojisQuery({})
const frequentEmojis = useSelector(getInstanceFrequentEmojis, () => true)
useEffect(() => {
if (data && data.length) {
@ -117,9 +70,8 @@ const ComponentEmojis: React.FC<Props & PropsWithChildren> = ({
title: string
data: Pick<Mastodon.Emoji, 'shortcode' | 'url' | 'static_url'>[][]
}[] = []
forEach(
groupBy(sortBy(data, ['category', 'shortcode']), 'category'),
(value, key) => sortedEmojis.push({ title: key, data: chunk(value, 5) })
forEach(groupBy(sortBy(data, ['category', 'shortcode']), 'category'), (value, key) =>
sortedEmojis.push({ title: key, data: chunk(value, 5) })
)
if (frequentEmojis.length) {
sortedEmojis.unshift({
@ -130,19 +82,56 @@ const ComponentEmojis: React.FC<Props & PropsWithChildren> = ({
)
})
}
emojisDispatch({
type: 'load',
payload: sortedEmojis
})
emojisDispatch({ type: 'load', payload: sortedEmojis })
prefetchEmojis(sortedEmojis, reduceMotionEnabled)
}
}, [data, reduceMotionEnabled])
const insets = useSafeAreaInsets()
const [keyboardShown, setKeyboardShown] = useState(false)
useEffect(() => {
const showSubscription = Keyboard.addListener('keyboardWillShow', () => {
emojisDispatch({ type: 'target', payload: null })
setKeyboardShown(true)
})
const hideSubscription = Keyboard.addListener('keyboardWillHide', () => {
setKeyboardShown(false)
})
return () => {
showSubscription.remove()
hideSubscription.remove()
}
}, [])
useEffect(() => {
if (focusRef) {
setTimeout(() => focusRef.current?.focus(), 500)
}
}, [])
return (
<EmojisContext.Provider
value={{ emojisState, emojisDispatch }}
children={children}
/>
<KeyboardAvoidingView style={{ flex: 1 }}>
<SafeAreaView style={{ flex: 1 }} edges={['bottom']}>
<View style={{ flex: 1, justifyContent: 'space-between' }}>
<EmojisContext.Provider value={{ emojisState, emojisDispatch }}>
<ScrollView keyboardShouldPersistTaps='always' children={children} />
<View
style={[
keyboardShown
? {
position: 'absolute',
bottom: 0,
width: '100%'
}
: null,
{ marginBottom: keyboardShown ? insets.bottom : 0 }
]}
children={keyboardShown ? <EmojisButton /> : <EmojisList />}
/>
</EmojisContext.Provider>
</View>
</SafeAreaView>
</KeyboardAvoidingView>
)
}

View File

@ -2,49 +2,41 @@ import Icon from '@components/Icon'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React, { useContext } from 'react'
import { Pressable, StyleSheet } from 'react-native'
import { Keyboard, Pressable } from 'react-native'
import EmojisContext from './helpers/EmojisContext'
const EmojisButton = React.memo(
() => {
const { colors } = useTheme()
const { emojisState, emojisDispatch } = useContext(EmojisContext)
const EmojisButton: React.FC = () => {
const { colors } = useTheme()
const { emojisState, emojisDispatch } = useContext(EmojisContext)
return emojisState.enabled ? (
<Pressable
disabled={!emojisState.emojis || !emojisState.emojis.length}
onPress={() =>
emojisDispatch({ type: 'activate', payload: !emojisState.active })
return (
<Pressable
disabled={!emojisState.emojis || !emojisState.emojis.length}
onPress={() => {
const targetProps = emojisState.inputProps?.find(props => props.ref.current?.isFocused())
if (!targetProps) {
return
}
hitSlop={StyleConstants.Spacing.S}
style={styles.base}
children={
<Icon
name={
emojisState.emojis && emojisState.emojis.length
? emojisState.active
? 'Type'
: 'Smile'
: 'Meh'
}
size={StyleConstants.Font.Size.L}
color={
emojisState.emojis && emojisState.emojis.length
? colors.primaryDefault
: colors.disabled
}
/>
if (emojisState.targetProps === null) {
Keyboard.dismiss()
}
/>
) : null
},
() => true
)
const styles = StyleSheet.create({
base: {
paddingLeft: StyleConstants.Spacing.S
}
})
emojisDispatch({ type: 'target', payload: targetProps })
}}
hitSlop={StyleConstants.Spacing.S}
style={{ alignSelf: 'flex-end', padding: StyleConstants.Spacing.Global.PagePadding }}
children={
<Icon
name={emojisState.emojis && emojisState.emojis.length ? 'Smile' : 'Meh'}
size={24}
color={
emojisState.emojis && emojisState.emojis.length
? colors.primaryDefault
: colors.disabled
}
/>
}
/>
)
}
export default EmojisButton

View File

@ -7,13 +7,7 @@ import layoutAnimation from '@utils/styles/layoutAnimation'
import { useTheme } from '@utils/styles/ThemeManager'
import React, { useCallback, useContext, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import {
AccessibilityInfo,
findNodeHandle,
Pressable,
SectionList,
View
} from 'react-native'
import { AccessibilityInfo, findNodeHandle, Pressable, SectionList, View } from 'react-native'
import FastImage from 'react-native-fast-image'
import validUrl from 'valid-url'
import EmojisContext from './helpers/EmojisContext'
@ -27,6 +21,33 @@ const EmojisList = React.memo(
const { emojisState, emojisDispatch } = useContext(EmojisContext)
const { colors } = useTheme()
const addEmoji = (shortcode: string) => {
if (!emojisState.targetProps) {
return
}
const inputValue = emojisState.targetProps.value
const maxLength = emojisState.targetProps.maxLength
const selectionRange = emojisState.targetProps.selectionRange || {
start: emojisState.targetProps.value.length,
end: emojisState.targetProps.value.length
}
if (inputValue?.length) {
const contentFront = inputValue.slice(0, selectionRange.start)
const contentRear = inputValue.slice(selectionRange.end)
const whiteSpaceRear = /\s/g.test(contentRear.slice(-1))
const newTextWithSpace = ` ${shortcode}${whiteSpaceRear ? '' : ' '}`
emojisState.targetProps.setValue(
[contentFront, newTextWithSpace, contentRear].join('').slice(0, maxLength)
)
} else {
emojisState.targetProps.setValue(`${shortcode} `.slice(0, maxLength))
}
}
const listItem = useCallback(
({ index, item }: { item: Mastodon.Emoji[]; index: number }) => {
return (
@ -46,20 +67,14 @@ const EmojisList = React.memo(
<Pressable
key={emoji.shortcode}
onPress={() => {
emojisDispatch({
type: 'shortcode',
payload: `:${emoji.shortcode}:`
})
addEmoji(`:${emoji.shortcode}:`)
dispatch(countInstanceEmoji(emoji))
}}
>
<FastImage
accessibilityLabel={t(
'common:customEmoji.accessibilityLabel',
{
emoji: emoji.shortcode
}
)}
accessibilityLabel={t('common:customEmoji.accessibilityLabel', {
emoji: emoji.shortcode
})}
accessibilityHint={t(
'screenCompose:content.root.footer.emojis.accessibilityHint'
)}
@ -80,19 +95,19 @@ const EmojisList = React.memo(
</View>
)
},
[]
[emojisState.targetProps]
)
const listRef = useRef<SectionList>(null)
useEffect(() => {
layoutAnimation()
const tagEmojis = findNodeHandle(listRef.current)
if (emojisState.active) {
if (emojisState.targetProps) {
layoutAnimation()
tagEmojis && AccessibilityInfo.setAccessibilityFocus(tagEmojis)
}
}, [emojisState.active])
}, [emojisState.targetProps])
return emojisState.active ? (
return emojisState.targetProps ? (
<SectionList
accessible
ref={listRef}
@ -101,15 +116,13 @@ const EmojisList = React.memo(
sections={emojisState.emojis}
keyExtractor={item => item[0].shortcode}
renderSectionHeader={({ section: { title } }) => (
<CustomText
fontStyle='S'
style={{ position: 'absolute', color: colors.secondary }}
>
<CustomText fontStyle='S' style={{ position: 'absolute', color: colors.secondary }}>
{title}
</CustomText>
)}
renderItem={listItem}
windowSize={4}
contentContainerStyle={{ paddingHorizontal: StyleConstants.Spacing.Global.PagePadding }}
/>
) : null
},

View File

@ -1,28 +1,27 @@
import { createContext, Dispatch } from 'react'
import { createContext, Dispatch, RefObject, SetStateAction } from 'react'
import { TextInput } from 'react-native'
type inputProps = {
ref: RefObject<TextInput>
value: string
setValue: Dispatch<SetStateAction<string>>
selectionRange?: { start: number; end: number }
maxLength?: number
}
export type EmojisState = {
enabled: boolean
active: boolean
emojis: {
title: string
data: Pick<Mastodon.Emoji, 'shortcode' | 'url' | 'static_url'>[][]
}[]
shortcode: Mastodon.Emoji['shortcode'] | null
targetProps: inputProps | null
inputProps: inputProps[]
}
export type EmojisAction =
| {
type: 'load'
payload: NonNullable<EmojisState['emojis']>
}
| {
type: 'activate'
payload: EmojisState['active']
}
| {
type: 'shortcode'
payload: EmojisState['shortcode']
}
| { type: 'load'; payload: NonNullable<EmojisState['emojis']> }
| { type: 'target'; payload: EmojisState['targetProps'] }
| { type: 'input'; payload: EmojisState['inputProps'] }
type ContextType = {
emojisState: EmojisState
@ -32,12 +31,12 @@ const EmojisContext = createContext<ContextType>({} as ContextType)
export const emojisReducer = (state: EmojisState, action: EmojisAction) => {
switch (action.type) {
case 'activate':
return { ...state, active: action.payload }
case 'load':
return { ...state, emojis: action.payload }
case 'shortcode':
return { ...state, shortcode: action.payload }
case 'target':
return { ...state, targetProps: action.payload }
case 'input':
return { ...state, inputProps: action.payload }
}
}

View File

@ -1,99 +1,55 @@
import { StyleConstants } from '@utils/styles/constants'
import layoutAnimation from '@utils/styles/layoutAnimation'
import { useTheme } from '@utils/styles/ThemeManager'
import React, {
Dispatch,
SetStateAction,
useEffect,
useRef,
useState
} from 'react'
import React, { Dispatch, forwardRef, RefObject, SetStateAction, useRef } from 'react'
import { Platform, TextInput, TextInputProps, View } from 'react-native'
import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'
import { ComponentEmojis, EmojisButton, EmojisList } from './Emojis'
import EmojisContext from './Emojis/helpers/EmojisContext'
import CustomText from './Text'
export interface Props {
autoFocus?: boolean
export type Props = {
value: string
setValue: Dispatch<SetStateAction<string>>
selectionRange?: { start: number; end: number }
title?: string
multiline?: boolean
} & Omit<
TextInputProps,
| 'style'
| 'onChangeText'
| 'onSelectionChange'
| 'keyboardAppearance'
| 'textAlignVertical'
| 'multiline'
>
emoji?: boolean
const ComponentInput = forwardRef(
(
{ title, multiline = false, value, setValue, selectionRange, ...props }: Props,
ref: RefObject<TextInput>
) => {
const { colors, mode } = useTheme()
value?: string
setValue:
| Dispatch<SetStateAction<string | undefined>>
| Dispatch<SetStateAction<string>>
options?: Omit<
TextInputProps,
| 'autoFocus'
| 'onFocus'
| 'onBlur'
| 'style'
| 'onChangeText'
| 'onSelectionChange'
| 'keyboardAppearance'
| 'textAlignVertical'
>
}
const Input: React.FC<Props> = ({
autoFocus = true,
title,
multiline = false,
emoji = false,
value,
setValue,
options
}) => {
const { colors, mode } = useTheme()
const animateTitle = useAnimatedStyle(() => {
if (value) {
return {
fontSize: withTiming(StyleConstants.Font.Size.S),
paddingHorizontal: withTiming(StyleConstants.Spacing.XS),
left: withTiming(StyleConstants.Spacing.S),
top: withTiming(-(StyleConstants.Font.Size.S / 2) - 2),
backgroundColor: withTiming(colors.backgroundDefault)
}
} else {
return {
fontSize: withTiming(StyleConstants.Font.Size.M),
paddingHorizontal: withTiming(0),
left: withTiming(StyleConstants.Spacing.S),
top: withTiming(StyleConstants.Spacing.S + 1),
backgroundColor: withTiming(colors.backgroundDefaultTransparent)
}
}
}, [mode, value])
const selectionRange = useRef<{ start: number; end: number }>(
value
? {
start: value.length,
end: value.length
const animateTitle = useAnimatedStyle(() => {
if (value) {
return {
fontSize: withTiming(StyleConstants.Font.Size.S),
paddingHorizontal: withTiming(StyleConstants.Spacing.XS),
left: withTiming(StyleConstants.Spacing.S),
top: withTiming(-(StyleConstants.Font.Size.S / 2) - 2),
backgroundColor: withTiming(colors.backgroundDefault)
}
: { start: 0, end: 0 }
)
} else {
return {
fontSize: withTiming(StyleConstants.Font.Size.M),
paddingHorizontal: withTiming(0),
left: withTiming(StyleConstants.Spacing.S),
top: withTiming(StyleConstants.Spacing.S + 1),
backgroundColor: withTiming(colors.backgroundDefaultTransparent)
}
}
}, [mode, value])
const [inputFocused, setInputFocused] = useState(false)
useEffect(() => {
layoutAnimation()
}, [inputFocused])
return (
<ComponentEmojis
enabled={emoji}
value={value}
setValue={setValue}
selectionRange={selectionRange}
maxLength={options?.maxLength}
>
return (
<View
style={{
borderWidth: 1,
@ -104,51 +60,35 @@ const Input: React.FC<Props> = ({
alignItems: 'stretch'
}}
>
<EmojisContext.Consumer>
{({ emojisDispatch }) => (
<TextInput
autoFocus={autoFocus}
onFocus={() => setInputFocused(true)}
onBlur={() => {
setInputFocused(false)
emojisDispatch({ type: 'activate', payload: false })
}}
style={{
flex: 1,
fontSize: StyleConstants.Font.Size.M,
color: colors.primaryDefault,
minHeight:
Platform.OS === 'ios' && multiline
? StyleConstants.Font.LineHeight.M * 5
: undefined
}}
onChangeText={setValue}
onSelectionChange={({ nativeEvent: { selection } }) =>
(selectionRange.current = selection)
}
value={value}
{...(multiline && {
multiline,
numberOfLines: Platform.OS === 'android' ? 5 : undefined
})}
keyboardAppearance={mode}
textAlignVertical='top'
{...options}
/>
)}
</EmojisContext.Consumer>
<TextInput
ref={ref}
style={{
flex: 1,
fontSize: StyleConstants.Font.Size.M,
color: colors.primaryDefault,
minHeight:
Platform.OS === 'ios' && multiline ? StyleConstants.Font.LineHeight.M * 5 : undefined
}}
onChangeText={setValue}
onSelectionChange={({ nativeEvent: { selection } }) => (selectionRange = selection)}
value={value}
{...(multiline && {
multiline,
numberOfLines: Platform.OS === 'android' ? 5 : undefined
})}
keyboardAppearance={mode}
textAlignVertical='top'
{...props}
/>
{title ? (
<Animated.Text
style={[
animateTitle,
{ position: 'absolute', color: colors.secondary }
]}
>
<Animated.Text style={[animateTitle, { position: 'absolute', color: colors.secondary }]}>
{title}
</Animated.Text>
) : null}
<View style={{ flexDirection: 'row', alignSelf: 'flex-end' }}>
{options?.maxLength && value?.length ? (
{props?.maxLength && value?.length ? (
<CustomText
fontStyle='S'
style={{
@ -156,15 +96,13 @@ const Input: React.FC<Props> = ({
color: colors.secondary
}}
>
{value?.length} / {options.maxLength}
{value?.length} / {props.maxLength}
</CustomText>
) : null}
{inputFocused ? <EmojisButton /> : null}
</View>
</View>
<EmojisList />
</ComponentEmojis>
)
}
)
}
)
export default Input
export default ComponentInput

View File

@ -50,10 +50,7 @@ const MenuRow: React.FC<Props> = ({
const loadingSpinkit = useMemo(
() => (
<View style={{ position: 'absolute' }}>
<Flow
size={StyleConstants.Font.Size.M * 1.25}
color={colors.secondary}
/>
<Flow size={StyleConstants.Font.Size.M * 1.25} color={colors.secondary} />
</View>
),
[theme]
@ -111,11 +108,7 @@ const MenuRow: React.FC<Props> = ({
}}
/>
) : null}
<CustomText
fontStyle='M'
style={{ color: colors.primaryDefault }}
numberOfLines={1}
>
<CustomText fontStyle='M' style={{ color: colors.primaryDefault }} numberOfLines={1}>
{title}
</CustomText>
</View>
@ -127,7 +120,7 @@ const MenuRow: React.FC<Props> = ({
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
marginLeft: StyleConstants.Spacing.M
paddingLeft: StyleConstants.Spacing.L
}}
>
{content ? (

View File

@ -41,6 +41,7 @@ const TimelineAttachment = React.memo(
}
const [sensitiveShown, setSensitiveShown] = useState(defaultSensitive())
// @ts-ignore
const imageUrls: RootStackParamList['Screen-ImagesViewer']['imageUrls'] =
status.media_attachments
.map(attachment => {

View File

@ -1,27 +1,69 @@
import { ComponentEmojis } from '@components/Emojis'
import { EmojisState } from '@components/Emojis/helpers/EmojisContext'
import { HeaderLeft, HeaderRight } from '@components/Header'
import Input from '@components/Input'
import ComponentInput from '@components/Input'
import CustomText from '@components/Text'
import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators'
import { useProfileMutation } from '@utils/queryHooks/profile'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import { isEqual } from 'lodash'
import React, { RefObject, useEffect, useState } from 'react'
import React, { Dispatch, RefObject, SetStateAction, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Alert, View } from 'react-native'
import { Alert, TextInput, View } from 'react-native'
import FlashMessage from 'react-native-flash-message'
import { ScrollView } from 'react-native-gesture-handler'
const prepareFields = (
fields: Mastodon.Field[] | undefined
): Mastodon.Field[] => {
return Array.from(Array(4).keys()).map(index => {
if (fields && fields[index]) {
return fields[index]
} else {
return { name: '', value: '', verified_at: null }
}
})
const Field: React.FC<{
allProps: EmojisState['inputProps']
setDirty: Dispatch<SetStateAction<boolean>>
index: number
field?: Mastodon.Field
}> = ({ allProps, setDirty, index, field }) => {
const { colors } = useTheme()
const { t } = useTranslation('screenTabs')
const [name, setName] = useState(field?.name || '')
const [value, setValue] = useState(field?.value || '')
allProps[index * 2] = {
ref: useRef<TextInput>(null),
value: name,
setValue: setName,
selectionRange: name ? { start: name.length, end: name.length } : { start: 0, end: 0 },
maxLength: 255
}
allProps[index * 2 + 1] = {
ref: useRef<TextInput>(null),
value,
setValue,
selectionRange: value ? { start: value.length, end: value.length } : { start: 0, end: 0 },
maxLength: 255
}
useEffect(() => {
setDirty(dirty =>
dirty ? dirty : !isEqual(field?.name, name) || !isEqual(field?.value, value)
)
}, [name, value])
return (
<>
<CustomText
fontStyle='S'
style={{
marginBottom: StyleConstants.Spacing.XS,
color: colors.primaryDefault
}}
>
{t('me.profile.fields.group', { index: index + 1 })}
</CustomText>
<ComponentInput title={t('me.profile.fields.label')} {...allProps[index * 2]} />
<ComponentInput
title={t('me.profile.fields.content')}
{...allProps[index * 2 + 1]}
multiline
/>
</>
)
}
const TabMeProfileFields: React.FC<
@ -35,16 +77,13 @@ const TabMeProfileFields: React.FC<
},
navigation
}) => {
const { colors, theme } = useTheme()
const { theme } = useTheme()
const { t, i18n } = useTranslation('screenTabs')
const { mutateAsync, status } = useProfileMutation()
const [newFields, setNewFields] = useState(prepareFields(fields))
const allProps: EmojisState['inputProps'] = []
const [dirty, setDirty] = useState(false)
useEffect(() => {
setDirty(!isEqual(prepareFields(fields), newFields))
}, [newFields])
useEffect(() => {
navigation.setOptions({
@ -88,9 +127,15 @@ const TabMeProfileFields: React.FC<
failed: true
},
type: 'fields_attributes',
data: newFields
.filter(field => field.name.length && field.value.length)
.map(field => ({ name: field.name, value: field.value }))
data: Array.from(Array(4).keys())
.filter(
index =>
allProps[index * 2]?.value.length || allProps[index * 2 + 1]?.value.length
)
.map(index => ({
name: allProps[index * 2].value,
value: allProps[index * 2 + 1].value
}))
}).then(() => {
navigation.navigate('Tab-Me-Profile-Root')
})
@ -98,60 +143,22 @@ const TabMeProfileFields: React.FC<
/>
)
})
}, [theme, i18n.language, dirty, status, newFields])
}, [theme, i18n.language, dirty, status, allProps.map(p => p.value)])
return (
<ScrollView
style={{
paddingHorizontal: StyleConstants.Spacing.Global.PagePadding,
marginBottom: StyleConstants.Spacing.L
}}
keyboardShouldPersistTaps='always'
>
<View style={{ marginBottom: StyleConstants.Spacing.L * 2 }}>
<ComponentEmojis inputProps={allProps}>
<View style={{ paddingHorizontal: StyleConstants.Spacing.Global.PagePadding }}>
{Array.from(Array(4).keys()).map(index => (
<View key={index} style={{ marginBottom: StyleConstants.Spacing.M }}>
<CustomText
fontStyle='S'
style={{
marginBottom: StyleConstants.Spacing.XS,
color: colors.primaryDefault
}}
>
{t('me.profile.fields.group', { index: index + 1 })}
</CustomText>
<Input
title={t('me.profile.fields.label')}
autoFocus={false}
options={{ maxLength: 255 }}
value={newFields[index].name}
setValue={(v: any) =>
setNewFields(
newFields.map((field, i) =>
i === index ? { ...field, name: v } : field
)
)
}
emoji
/>
<Input
title={t('me.profile.fields.content')}
autoFocus={false}
options={{ maxLength: 255 }}
value={newFields[index].value}
setValue={(v: any) =>
setNewFields(
newFields.map((field, i) =>
i === index ? { ...field, value: v } : field
)
)
}
emoji
/>
</View>
<Field
key={index}
allProps={allProps}
setDirty={setDirty}
index={index}
field={fields?.[index]}
/>
))}
</View>
</ScrollView>
</ComponentEmojis>
)
}

View File

@ -1,14 +1,15 @@
import { ComponentEmojis } from '@components/Emojis'
import { EmojisState } from '@components/Emojis/helpers/EmojisContext'
import { HeaderLeft, HeaderRight } from '@components/Header'
import Input from '@components/Input'
import ComponentInput from '@components/Input'
import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators'
import { useProfileMutation } from '@utils/queryHooks/profile'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React, { RefObject, useEffect, useState } from 'react'
import React, { RefObject, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Alert, StyleSheet } from 'react-native'
import { Alert, TextInput, View } from 'react-native'
import FlashMessage from 'react-native-flash-message'
import { ScrollView } from 'react-native-gesture-handler'
const TabMeProfileName: React.FC<
TabMeProfileStackScreenProps<'Tab-Me-Profile-Name'> & {
@ -26,6 +27,15 @@ const TabMeProfileName: React.FC<
const { mutateAsync, status } = useProfileMutation()
const [displayName, setDisplayName] = useState(display_name)
const displayNameProps: NonNullable<EmojisState['targetProps']> = {
ref: useRef<TextInput>(null),
value: displayName,
setValue: setDisplayName,
selectionRange: displayName
? { start: displayName.length, end: displayName.length }
: { start: 0, end: 0 },
maxLength: 30
}
const [dirty, setDirty] = useState(false)
useEffect(() => {
@ -85,27 +95,18 @@ const TabMeProfileName: React.FC<
}, [theme, i18n.language, dirty, status, displayName])
return (
<ScrollView style={styles.base} keyboardShouldPersistTaps='always'>
<Input
value={displayName}
setValue={setDisplayName}
emoji
options={{
maxLength: 30,
autoCapitalize: 'none',
autoComplete: 'username',
textContentType: 'username',
autoCorrect: false
}}
/>
</ScrollView>
<ComponentEmojis inputProps={[displayNameProps]} focusRef={displayNameProps.ref}>
<View style={{ paddingHorizontal: StyleConstants.Spacing.Global.PagePadding }}>
<ComponentInput
{...displayNameProps}
autoCapitalize='none'
autoComplete='username'
textContentType='username'
autoCorrect={false}
/>
</View>
</ComponentEmojis>
)
}
const styles = StyleSheet.create({
base: {
paddingHorizontal: StyleConstants.Spacing.Global.PagePadding
}
})
export default TabMeProfileName

View File

@ -1,14 +1,15 @@
import { ComponentEmojis } from '@components/Emojis'
import { EmojisState } from '@components/Emojis/helpers/EmojisContext'
import { HeaderLeft, HeaderRight } from '@components/Header'
import Input from '@components/Input'
import ComponentInput from '@components/Input'
import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators'
import { useProfileMutation } from '@utils/queryHooks/profile'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React, { RefObject, useEffect, useState } from 'react'
import React, { RefObject, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Alert, StyleSheet, View } from 'react-native'
import { Alert, TextInput, View } from 'react-native'
import FlashMessage from 'react-native-flash-message'
import { ScrollView } from 'react-native-gesture-handler'
const TabMeProfileNote: React.FC<
TabMeProfileStackScreenProps<'Tab-Me-Profile-Note'> & {
@ -25,12 +26,19 @@ const TabMeProfileNote: React.FC<
const { t, i18n } = useTranslation('screenTabs')
const { mutateAsync, status } = useProfileMutation()
const [newNote, setNewNote] = useState(note)
const [notes, setNotes] = useState(note)
const notesProps: NonNullable<EmojisState['targetProps']> = {
ref: useRef<TextInput>(null),
value: notes,
setValue: setNotes,
selectionRange: notes ? { start: notes.length, end: notes.length } : { start: 0, end: 0 },
maxLength: 500
}
const [dirty, setDirty] = useState(false)
useEffect(() => {
setDirty(note !== newNote)
}, [newNote])
setDirty(note !== notes)
}, [notes])
useEffect(() => {
navigation.setOptions({
@ -74,7 +82,7 @@ const TabMeProfileNote: React.FC<
failed: true
},
type: 'note',
data: newNote
data: notes
}).then(() => {
navigation.navigate('Tab-Me-Profile-Root')
})
@ -82,27 +90,15 @@ const TabMeProfileNote: React.FC<
/>
)
})
}, [theme, i18n.language, dirty, status, newNote])
}, [theme, i18n.language, dirty, status, notes])
return (
<ScrollView style={styles.base} keyboardShouldPersistTaps='always'>
<View style={{ marginBottom: StyleConstants.Spacing.XL * 2 }}>
<Input
value={newNote}
setValue={setNewNote}
multiline
emoji
options={{ maxLength: 500 }}
/>
<ComponentEmojis inputProps={[notesProps]} focusRef={notesProps.ref}>
<View style={{ paddingHorizontal: StyleConstants.Spacing.Global.PagePadding }}>
<ComponentInput {...notesProps} multiline />
</View>
</ScrollView>
</ComponentEmojis>
)
}
const styles = StyleSheet.create({
base: {
paddingHorizontal: StyleConstants.Spacing.Global.PagePadding
}
})
export default TabMeProfileNote

View File

@ -1,18 +1,16 @@
import Input from '@components/Input'
import { ParseEmojis } from '@components/Parse'
import CustomText from '@components/Text'
import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager'
import React, { useMemo, useState } from 'react'
import React, { useMemo } from 'react'
import { View } from 'react-native'
import { PlaceholderLine } from 'rn-placeholder'
export interface Props {
account: Mastodon.Account | undefined
edit?: boolean // Editing mode
}
const AccountInformationName: React.FC<Props> = ({ account, edit }) => {
const AccountInformationName: React.FC<Props> = ({ account }) => {
const { colors } = useTheme()
const movedContent = useMemo(() => {
@ -30,8 +28,6 @@ const AccountInformationName: React.FC<Props> = ({ account, edit }) => {
}
}, [account?.moved])
const [displatName, setDisplayName] = useState(account?.display_name)
return (
<View
style={{
@ -42,25 +38,21 @@ const AccountInformationName: React.FC<Props> = ({ account, edit }) => {
}}
>
{account ? (
edit ? (
<Input title='昵称' value={displatName} setValue={setDisplayName} />
) : (
<>
<CustomText
style={{
textDecorationLine: account?.moved ? 'line-through' : undefined
}}
>
<ParseEmojis
content={account.display_name || account.username}
emojis={account.emojis}
size='L'
fontBold
/>
</CustomText>
{movedContent}
</>
)
<>
<CustomText
style={{
textDecorationLine: account?.moved ? 'line-through' : undefined
}}
>
<ParseEmojis
content={account.display_name || account.username}
emojis={account.emojis}
size='L'
fontBold
/>
</CustomText>
{movedContent}
</>
) : (
<PlaceholderLine
width={StyleConstants.Font.Size.L * 2}
@ -74,7 +66,4 @@ const AccountInformationName: React.FC<Props> = ({ account, edit }) => {
)
}
export default React.memo(
AccountInformationName,
(_, next) => next.account === undefined
)
export default React.memo(AccountInformationName, (_, next) => next.account === undefined)

View File

@ -1,4 +1,3 @@
import Input from '@components/Input'
import { ParseHTML } from '@components/Parse'
import { StyleConstants } from '@utils/styles/constants'
import React, { useState } from 'react'
@ -7,16 +6,11 @@ import { StyleSheet, View } from 'react-native'
export interface Props {
account: Mastodon.Account | undefined
myInfo?: boolean
edit?: boolean
}
const AccountInformationNote = React.memo(
({ account, myInfo, edit }: Props) => {
({ account, myInfo }: Props) => {
const [note, setNote] = useState(account?.source?.note)
if (edit) {
return <Input title='简介' value={note} setValue={setNote} multiline />
}
if (
myInfo ||
!account?.note ||