1
0
mirror of https://github.com/tooot-app/app synced 2025-06-05 22:19:13 +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 { 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 => {