1
0
mirror of https://github.com/tooot-app/app synced 2025-05-10 14:58:51 +02: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 { useEmojisQuery } from '@utils/queryHooks/emojis'
import { getInstanceFrequentEmojis } from '@utils/slices/instancesSlice' import { getInstanceFrequentEmojis } from '@utils/slices/instancesSlice'
import { chunk, forEach, groupBy, sortBy } from 'lodash' import { chunk, forEach, groupBy, sortBy } from 'lodash'
import React, { import React, { PropsWithChildren, RefObject, useEffect, useReducer, useState } from 'react'
Dispatch,
MutableRefObject,
PropsWithChildren,
SetStateAction,
useCallback,
useEffect,
useReducer
} from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { Keyboard, KeyboardAvoidingView, Text, TextInput, View } from 'react-native'
import FastImage from 'react-native-fast-image' 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 { useSelector } from 'react-redux'
import EmojisContext, { emojisReducer } from './Emojis/helpers/EmojisContext' import EmojisContext, { emojisReducer, EmojisState } from './Emojis/helpers/EmojisContext'
const prefetchEmojis = ( const prefetchEmojis = (
sortedEmojis: { sortedEmojis: {
@ -45,71 +40,29 @@ const prefetchEmojis = (
} catch {} } catch {}
} }
export interface Props { export type Props = {
enabled?: boolean inputProps: EmojisState['inputProps']
value?: string focusRef?: RefObject<TextInput>
setValue:
| Dispatch<SetStateAction<string | undefined>>
| Dispatch<SetStateAction<string>>
selectionRange: MutableRefObject<{
start: number
end: number
}>
maxLength?: number
} }
const ComponentEmojis: React.FC<Props & PropsWithChildren> = ({ const ComponentEmojis: React.FC<Props & PropsWithChildren> = ({
enabled = false, children,
value, inputProps,
setValue, focusRef
selectionRange,
maxLength,
children
}) => { }) => {
const { reduceMotionEnabled } = useAccessibility() const { reduceMotionEnabled } = useAccessibility()
const [emojisState, emojisDispatch] = useReducer(emojisReducer, { const [emojisState, emojisDispatch] = useReducer(emojisReducer, {
enabled,
active: false,
emojis: [], emojis: [],
shortcode: null targetProps: null,
inputProps
}) })
useEffect(() => { useEffect(() => {
if (emojisState.shortcode) { emojisDispatch({ type: 'input', payload: inputProps })
addEmoji(emojisState.shortcode) }, [inputProps])
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]
)
const { t } = useTranslation() const { t } = useTranslation()
const { data } = useEmojisQuery({ options: { enabled } }) const { data } = useEmojisQuery({})
const frequentEmojis = useSelector(getInstanceFrequentEmojis, () => true) const frequentEmojis = useSelector(getInstanceFrequentEmojis, () => true)
useEffect(() => { useEffect(() => {
if (data && data.length) { if (data && data.length) {
@ -117,9 +70,8 @@ const ComponentEmojis: React.FC<Props & PropsWithChildren> = ({
title: string title: string
data: Pick<Mastodon.Emoji, 'shortcode' | 'url' | 'static_url'>[][] data: Pick<Mastodon.Emoji, 'shortcode' | 'url' | 'static_url'>[][]
}[] = [] }[] = []
forEach( forEach(groupBy(sortBy(data, ['category', 'shortcode']), 'category'), (value, key) =>
groupBy(sortBy(data, ['category', 'shortcode']), 'category'), sortedEmojis.push({ title: key, data: chunk(value, 5) })
(value, key) => sortedEmojis.push({ title: key, data: chunk(value, 5) })
) )
if (frequentEmojis.length) { if (frequentEmojis.length) {
sortedEmojis.unshift({ sortedEmojis.unshift({
@ -130,19 +82,56 @@ const ComponentEmojis: React.FC<Props & PropsWithChildren> = ({
) )
}) })
} }
emojisDispatch({ emojisDispatch({ type: 'load', payload: sortedEmojis })
type: 'load',
payload: sortedEmojis
})
prefetchEmojis(sortedEmojis, reduceMotionEnabled) prefetchEmojis(sortedEmojis, reduceMotionEnabled)
} }
}, [data, 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 ( return (
<EmojisContext.Provider <KeyboardAvoidingView style={{ flex: 1 }}>
value={{ emojisState, emojisDispatch }} <SafeAreaView style={{ flex: 1 }} edges={['bottom']}>
children={children} <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 { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager' import { useTheme } from '@utils/styles/ThemeManager'
import React, { useContext } from 'react' import React, { useContext } from 'react'
import { Pressable, StyleSheet } from 'react-native' import { Keyboard, Pressable } from 'react-native'
import EmojisContext from './helpers/EmojisContext' import EmojisContext from './helpers/EmojisContext'
const EmojisButton = React.memo( const EmojisButton: React.FC = () => {
() => { const { colors } = useTheme()
const { colors } = useTheme() const { emojisState, emojisDispatch } = useContext(EmojisContext)
const { emojisState, emojisDispatch } = useContext(EmojisContext)
return emojisState.enabled ? ( return (
<Pressable <Pressable
disabled={!emojisState.emojis || !emojisState.emojis.length} disabled={!emojisState.emojis || !emojisState.emojis.length}
onPress={() => onPress={() => {
emojisDispatch({ type: 'activate', payload: !emojisState.active }) const targetProps = emojisState.inputProps?.find(props => props.ref.current?.isFocused())
if (!targetProps) {
return
} }
hitSlop={StyleConstants.Spacing.S} if (emojisState.targetProps === null) {
style={styles.base} Keyboard.dismiss()
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
}
/>
} }
/> emojisDispatch({ type: 'target', payload: targetProps })
) : null }}
}, hitSlop={StyleConstants.Spacing.S}
() => true style={{ alignSelf: 'flex-end', padding: StyleConstants.Spacing.Global.PagePadding }}
) children={
<Icon
const styles = StyleSheet.create({ name={emojisState.emojis && emojisState.emojis.length ? 'Smile' : 'Meh'}
base: { size={24}
paddingLeft: StyleConstants.Spacing.S color={
} emojisState.emojis && emojisState.emojis.length
}) ? colors.primaryDefault
: colors.disabled
}
/>
}
/>
)
}
export default EmojisButton export default EmojisButton

View File

@ -7,13 +7,7 @@ import layoutAnimation from '@utils/styles/layoutAnimation'
import { useTheme } from '@utils/styles/ThemeManager' import { useTheme } from '@utils/styles/ThemeManager'
import React, { useCallback, useContext, useEffect, useRef } from 'react' import React, { useCallback, useContext, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { import { AccessibilityInfo, findNodeHandle, Pressable, SectionList, View } from 'react-native'
AccessibilityInfo,
findNodeHandle,
Pressable,
SectionList,
View
} from 'react-native'
import FastImage from 'react-native-fast-image' import FastImage from 'react-native-fast-image'
import validUrl from 'valid-url' import validUrl from 'valid-url'
import EmojisContext from './helpers/EmojisContext' import EmojisContext from './helpers/EmojisContext'
@ -27,6 +21,33 @@ const EmojisList = React.memo(
const { emojisState, emojisDispatch } = useContext(EmojisContext) const { emojisState, emojisDispatch } = useContext(EmojisContext)
const { colors } = useTheme() 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( const listItem = useCallback(
({ index, item }: { item: Mastodon.Emoji[]; index: number }) => { ({ index, item }: { item: Mastodon.Emoji[]; index: number }) => {
return ( return (
@ -46,20 +67,14 @@ const EmojisList = React.memo(
<Pressable <Pressable
key={emoji.shortcode} key={emoji.shortcode}
onPress={() => { onPress={() => {
emojisDispatch({ addEmoji(`:${emoji.shortcode}:`)
type: 'shortcode',
payload: `:${emoji.shortcode}:`
})
dispatch(countInstanceEmoji(emoji)) dispatch(countInstanceEmoji(emoji))
}} }}
> >
<FastImage <FastImage
accessibilityLabel={t( accessibilityLabel={t('common:customEmoji.accessibilityLabel', {
'common:customEmoji.accessibilityLabel', emoji: emoji.shortcode
{ })}
emoji: emoji.shortcode
}
)}
accessibilityHint={t( accessibilityHint={t(
'screenCompose:content.root.footer.emojis.accessibilityHint' 'screenCompose:content.root.footer.emojis.accessibilityHint'
)} )}
@ -80,19 +95,19 @@ const EmojisList = React.memo(
</View> </View>
) )
}, },
[] [emojisState.targetProps]
) )
const listRef = useRef<SectionList>(null) const listRef = useRef<SectionList>(null)
useEffect(() => { useEffect(() => {
layoutAnimation()
const tagEmojis = findNodeHandle(listRef.current) const tagEmojis = findNodeHandle(listRef.current)
if (emojisState.active) { if (emojisState.targetProps) {
layoutAnimation()
tagEmojis && AccessibilityInfo.setAccessibilityFocus(tagEmojis) tagEmojis && AccessibilityInfo.setAccessibilityFocus(tagEmojis)
} }
}, [emojisState.active]) }, [emojisState.targetProps])
return emojisState.active ? ( return emojisState.targetProps ? (
<SectionList <SectionList
accessible accessible
ref={listRef} ref={listRef}
@ -101,15 +116,13 @@ const EmojisList = React.memo(
sections={emojisState.emojis} sections={emojisState.emojis}
keyExtractor={item => item[0].shortcode} keyExtractor={item => item[0].shortcode}
renderSectionHeader={({ section: { title } }) => ( renderSectionHeader={({ section: { title } }) => (
<CustomText <CustomText fontStyle='S' style={{ position: 'absolute', color: colors.secondary }}>
fontStyle='S'
style={{ position: 'absolute', color: colors.secondary }}
>
{title} {title}
</CustomText> </CustomText>
)} )}
renderItem={listItem} renderItem={listItem}
windowSize={4} windowSize={4}
contentContainerStyle={{ paddingHorizontal: StyleConstants.Spacing.Global.PagePadding }}
/> />
) : null ) : 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 = { export type EmojisState = {
enabled: boolean
active: boolean
emojis: { emojis: {
title: string title: string
data: Pick<Mastodon.Emoji, 'shortcode' | 'url' | 'static_url'>[][] data: Pick<Mastodon.Emoji, 'shortcode' | 'url' | 'static_url'>[][]
}[] }[]
shortcode: Mastodon.Emoji['shortcode'] | null targetProps: inputProps | null
inputProps: inputProps[]
} }
export type EmojisAction = export type EmojisAction =
| { | { type: 'load'; payload: NonNullable<EmojisState['emojis']> }
type: 'load' | { type: 'target'; payload: EmojisState['targetProps'] }
payload: NonNullable<EmojisState['emojis']> | { type: 'input'; payload: EmojisState['inputProps'] }
}
| {
type: 'activate'
payload: EmojisState['active']
}
| {
type: 'shortcode'
payload: EmojisState['shortcode']
}
type ContextType = { type ContextType = {
emojisState: EmojisState emojisState: EmojisState
@ -32,12 +31,12 @@ const EmojisContext = createContext<ContextType>({} as ContextType)
export const emojisReducer = (state: EmojisState, action: EmojisAction) => { export const emojisReducer = (state: EmojisState, action: EmojisAction) => {
switch (action.type) { switch (action.type) {
case 'activate':
return { ...state, active: action.payload }
case 'load': case 'load':
return { ...state, emojis: action.payload } return { ...state, emojis: action.payload }
case 'shortcode': case 'target':
return { ...state, shortcode: action.payload } 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 { StyleConstants } from '@utils/styles/constants'
import layoutAnimation from '@utils/styles/layoutAnimation'
import { useTheme } from '@utils/styles/ThemeManager' import { useTheme } from '@utils/styles/ThemeManager'
import React, { import React, { Dispatch, forwardRef, RefObject, SetStateAction, useRef } from 'react'
Dispatch,
SetStateAction,
useEffect,
useRef,
useState
} from 'react'
import { Platform, TextInput, TextInputProps, View } from 'react-native' import { Platform, TextInput, TextInputProps, View } from 'react-native'
import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated' import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'
import { ComponentEmojis, EmojisButton, EmojisList } from './Emojis'
import EmojisContext from './Emojis/helpers/EmojisContext'
import CustomText from './Text' import CustomText from './Text'
export interface Props { export type Props = {
autoFocus?: boolean value: string
setValue: Dispatch<SetStateAction<string>>
selectionRange?: { start: number; end: number }
title?: string title?: string
multiline?: boolean 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 const animateTitle = useAnimatedStyle(() => {
setValue: if (value) {
| Dispatch<SetStateAction<string | undefined>> return {
| Dispatch<SetStateAction<string>> fontSize: withTiming(StyleConstants.Font.Size.S),
paddingHorizontal: withTiming(StyleConstants.Spacing.XS),
options?: Omit< left: withTiming(StyleConstants.Spacing.S),
TextInputProps, top: withTiming(-(StyleConstants.Font.Size.S / 2) - 2),
| 'autoFocus' backgroundColor: withTiming(colors.backgroundDefault)
| '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
} }
: { 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) return (
useEffect(() => {
layoutAnimation()
}, [inputFocused])
return (
<ComponentEmojis
enabled={emoji}
value={value}
setValue={setValue}
selectionRange={selectionRange}
maxLength={options?.maxLength}
>
<View <View
style={{ style={{
borderWidth: 1, borderWidth: 1,
@ -104,51 +60,35 @@ const Input: React.FC<Props> = ({
alignItems: 'stretch' alignItems: 'stretch'
}} }}
> >
<EmojisContext.Consumer> <TextInput
{({ emojisDispatch }) => ( ref={ref}
<TextInput style={{
autoFocus={autoFocus} flex: 1,
onFocus={() => setInputFocused(true)} fontSize: StyleConstants.Font.Size.M,
onBlur={() => { color: colors.primaryDefault,
setInputFocused(false) minHeight:
emojisDispatch({ type: 'activate', payload: false }) Platform.OS === 'ios' && multiline ? StyleConstants.Font.LineHeight.M * 5 : undefined
}} }}
style={{ onChangeText={setValue}
flex: 1, onSelectionChange={({ nativeEvent: { selection } }) => (selectionRange = selection)}
fontSize: StyleConstants.Font.Size.M, value={value}
color: colors.primaryDefault, {...(multiline && {
minHeight: multiline,
Platform.OS === 'ios' && multiline numberOfLines: Platform.OS === 'android' ? 5 : undefined
? StyleConstants.Font.LineHeight.M * 5 })}
: undefined keyboardAppearance={mode}
}} textAlignVertical='top'
onChangeText={setValue} {...props}
onSelectionChange={({ nativeEvent: { selection } }) => />
(selectionRange.current = selection)
}
value={value}
{...(multiline && {
multiline,
numberOfLines: Platform.OS === 'android' ? 5 : undefined
})}
keyboardAppearance={mode}
textAlignVertical='top'
{...options}
/>
)}
</EmojisContext.Consumer>
{title ? ( {title ? (
<Animated.Text <Animated.Text style={[animateTitle, { position: 'absolute', color: colors.secondary }]}>
style={[
animateTitle,
{ position: 'absolute', color: colors.secondary }
]}
>
{title} {title}
</Animated.Text> </Animated.Text>
) : null} ) : null}
<View style={{ flexDirection: 'row', alignSelf: 'flex-end' }}> <View style={{ flexDirection: 'row', alignSelf: 'flex-end' }}>
{options?.maxLength && value?.length ? ( {props?.maxLength && value?.length ? (
<CustomText <CustomText
fontStyle='S' fontStyle='S'
style={{ style={{
@ -156,15 +96,13 @@ const Input: React.FC<Props> = ({
color: colors.secondary color: colors.secondary
}} }}
> >
{value?.length} / {options.maxLength} {value?.length} / {props.maxLength}
</CustomText> </CustomText>
) : null} ) : null}
{inputFocused ? <EmojisButton /> : null}
</View> </View>
</View> </View>
<EmojisList /> )
</ComponentEmojis> }
) )
}
export default Input export default ComponentInput

View File

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

View File

@ -41,6 +41,7 @@ const TimelineAttachment = React.memo(
} }
const [sensitiveShown, setSensitiveShown] = useState(defaultSensitive()) const [sensitiveShown, setSensitiveShown] = useState(defaultSensitive())
// @ts-ignore
const imageUrls: RootStackParamList['Screen-ImagesViewer']['imageUrls'] = const imageUrls: RootStackParamList['Screen-ImagesViewer']['imageUrls'] =
status.media_attachments status.media_attachments
.map(attachment => { .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 { HeaderLeft, HeaderRight } from '@components/Header'
import Input from '@components/Input' import ComponentInput from '@components/Input'
import CustomText from '@components/Text' import CustomText from '@components/Text'
import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators' import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators'
import { useProfileMutation } from '@utils/queryHooks/profile' import { useProfileMutation } from '@utils/queryHooks/profile'
import { StyleConstants } from '@utils/styles/constants' import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager' import { useTheme } from '@utils/styles/ThemeManager'
import { isEqual } from 'lodash' 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 { 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 FlashMessage from 'react-native-flash-message'
import { ScrollView } from 'react-native-gesture-handler'
const prepareFields = ( const Field: React.FC<{
fields: Mastodon.Field[] | undefined allProps: EmojisState['inputProps']
): Mastodon.Field[] => { setDirty: Dispatch<SetStateAction<boolean>>
return Array.from(Array(4).keys()).map(index => { index: number
if (fields && fields[index]) { field?: Mastodon.Field
return fields[index] }> = ({ allProps, setDirty, index, field }) => {
} else { const { colors } = useTheme()
return { name: '', value: '', verified_at: null } 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< const TabMeProfileFields: React.FC<
@ -35,16 +77,13 @@ const TabMeProfileFields: React.FC<
}, },
navigation navigation
}) => { }) => {
const { colors, theme } = useTheme() const { theme } = useTheme()
const { t, i18n } = useTranslation('screenTabs') const { t, i18n } = useTranslation('screenTabs')
const { mutateAsync, status } = useProfileMutation() const { mutateAsync, status } = useProfileMutation()
const [newFields, setNewFields] = useState(prepareFields(fields)) const allProps: EmojisState['inputProps'] = []
const [dirty, setDirty] = useState(false) const [dirty, setDirty] = useState(false)
useEffect(() => {
setDirty(!isEqual(prepareFields(fields), newFields))
}, [newFields])
useEffect(() => { useEffect(() => {
navigation.setOptions({ navigation.setOptions({
@ -88,9 +127,15 @@ const TabMeProfileFields: React.FC<
failed: true failed: true
}, },
type: 'fields_attributes', type: 'fields_attributes',
data: newFields data: Array.from(Array(4).keys())
.filter(field => field.name.length && field.value.length) .filter(
.map(field => ({ name: field.name, value: field.value })) 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(() => { }).then(() => {
navigation.navigate('Tab-Me-Profile-Root') 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 ( return (
<ScrollView <ComponentEmojis inputProps={allProps}>
style={{ <View style={{ paddingHorizontal: StyleConstants.Spacing.Global.PagePadding }}>
paddingHorizontal: StyleConstants.Spacing.Global.PagePadding,
marginBottom: StyleConstants.Spacing.L
}}
keyboardShouldPersistTaps='always'
>
<View style={{ marginBottom: StyleConstants.Spacing.L * 2 }}>
{Array.from(Array(4).keys()).map(index => ( {Array.from(Array(4).keys()).map(index => (
<View key={index} style={{ marginBottom: StyleConstants.Spacing.M }}> <Field
<CustomText key={index}
fontStyle='S' allProps={allProps}
style={{ setDirty={setDirty}
marginBottom: StyleConstants.Spacing.XS, index={index}
color: colors.primaryDefault field={fields?.[index]}
}} />
>
{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>
))} ))}
</View> </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 { HeaderLeft, HeaderRight } from '@components/Header'
import Input from '@components/Input' import ComponentInput from '@components/Input'
import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators' import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators'
import { useProfileMutation } from '@utils/queryHooks/profile' import { useProfileMutation } from '@utils/queryHooks/profile'
import { StyleConstants } from '@utils/styles/constants' import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager' 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 { 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 FlashMessage from 'react-native-flash-message'
import { ScrollView } from 'react-native-gesture-handler'
const TabMeProfileName: React.FC< const TabMeProfileName: React.FC<
TabMeProfileStackScreenProps<'Tab-Me-Profile-Name'> & { TabMeProfileStackScreenProps<'Tab-Me-Profile-Name'> & {
@ -26,6 +27,15 @@ const TabMeProfileName: React.FC<
const { mutateAsync, status } = useProfileMutation() const { mutateAsync, status } = useProfileMutation()
const [displayName, setDisplayName] = useState(display_name) 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) const [dirty, setDirty] = useState(false)
useEffect(() => { useEffect(() => {
@ -85,27 +95,18 @@ const TabMeProfileName: React.FC<
}, [theme, i18n.language, dirty, status, displayName]) }, [theme, i18n.language, dirty, status, displayName])
return ( return (
<ScrollView style={styles.base} keyboardShouldPersistTaps='always'> <ComponentEmojis inputProps={[displayNameProps]} focusRef={displayNameProps.ref}>
<Input <View style={{ paddingHorizontal: StyleConstants.Spacing.Global.PagePadding }}>
value={displayName} <ComponentInput
setValue={setDisplayName} {...displayNameProps}
emoji autoCapitalize='none'
options={{ autoComplete='username'
maxLength: 30, textContentType='username'
autoCapitalize: 'none', autoCorrect={false}
autoComplete: 'username', />
textContentType: 'username', </View>
autoCorrect: false </ComponentEmojis>
}}
/>
</ScrollView>
) )
} }
const styles = StyleSheet.create({
base: {
paddingHorizontal: StyleConstants.Spacing.Global.PagePadding
}
})
export default TabMeProfileName 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 { HeaderLeft, HeaderRight } from '@components/Header'
import Input from '@components/Input' import ComponentInput from '@components/Input'
import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators' import { TabMeProfileStackScreenProps } from '@utils/navigation/navigators'
import { useProfileMutation } from '@utils/queryHooks/profile' import { useProfileMutation } from '@utils/queryHooks/profile'
import { StyleConstants } from '@utils/styles/constants' import { StyleConstants } from '@utils/styles/constants'
import { useTheme } from '@utils/styles/ThemeManager' 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 { 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 FlashMessage from 'react-native-flash-message'
import { ScrollView } from 'react-native-gesture-handler'
const TabMeProfileNote: React.FC< const TabMeProfileNote: React.FC<
TabMeProfileStackScreenProps<'Tab-Me-Profile-Note'> & { TabMeProfileStackScreenProps<'Tab-Me-Profile-Note'> & {
@ -25,12 +26,19 @@ const TabMeProfileNote: React.FC<
const { t, i18n } = useTranslation('screenTabs') const { t, i18n } = useTranslation('screenTabs')
const { mutateAsync, status } = useProfileMutation() 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) const [dirty, setDirty] = useState(false)
useEffect(() => { useEffect(() => {
setDirty(note !== newNote) setDirty(note !== notes)
}, [newNote]) }, [notes])
useEffect(() => { useEffect(() => {
navigation.setOptions({ navigation.setOptions({
@ -74,7 +82,7 @@ const TabMeProfileNote: React.FC<
failed: true failed: true
}, },
type: 'note', type: 'note',
data: newNote data: notes
}).then(() => { }).then(() => {
navigation.navigate('Tab-Me-Profile-Root') 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 ( return (
<ScrollView style={styles.base} keyboardShouldPersistTaps='always'> <ComponentEmojis inputProps={[notesProps]} focusRef={notesProps.ref}>
<View style={{ marginBottom: StyleConstants.Spacing.XL * 2 }}> <View style={{ paddingHorizontal: StyleConstants.Spacing.Global.PagePadding }}>
<Input <ComponentInput {...notesProps} multiline />
value={newNote}
setValue={setNewNote}
multiline
emoji
options={{ maxLength: 500 }}
/>
</View> </View>
</ScrollView> </ComponentEmojis>
) )
} }
const styles = StyleSheet.create({
base: {
paddingHorizontal: StyleConstants.Spacing.Global.PagePadding
}
})
export default TabMeProfileNote export default TabMeProfileNote

View File

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

View File

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