import {
AttachmentKindEnum,
AttachmentType,
FileType,
LinkPreviewType,
LinkType,
MessageBundleType,
MessageKindEnum,
MessageMetadataType,
MessageType,
PollType,
RoomKindEnum,
RoomType,
StickerType,
} from "@openchat/types"
import { CryptoUtils, DateUtils, RandomUtils } from "@openchat/core"
import {
CurrentRoomUISettingsModel,
useAccountId,
useCurrentRoomUISettings,
useRoomMetadata,
} from "@openchat/ui"
import React, { useEffect, useRef, useState } from "react"
import {
Image,
Keyboard,
NativeSyntheticEvent,
Pressable,
TextInput,
TextInputKeyPressEventData,
TouchableOpacity,
useWindowDimensions,
View,
} from "react-native"
import { useModal } from "../../../ui-components/modal/modal.hook"
import { EmotionCategoryType } from "../../emoji/emoji-type/emotion-category.types"
import Animated, {
Easing,
ReduceMotion,
useAnimatedStyle,
useSharedValue,
withTiming,
} from "react-native-reanimated"
import { SvgXml } from "react-native-svg"
import TrackPlayer from "react-native-track-player"
import { AppController, AppStore } from "../../../app/app.globals"
import {
arrowUpIcon,
cameraActiveIcon,
chervonDown,
chervonUp,
keywordIcon,
regularStickerIcon,
} from "../../../ui-components/svg-icons/svg-icons"
import { MessageInputDecorator } from "../message-input-decorator/message-input-decorator.component"
import { MessageInputQuote } from "../message-input-quote/message-input-quote.component"
import { useStyles } from "./message-input.style"
import { MessageTextAreaUtils } from "../message-textarea/message-textarea.utils"
import { MessageInputPreviewContainer } from "../message-input-preview-container/message-input-preview-container.component"
import { MessageInputPopup } from "../message-input-popup/message-input-popup.component"
import { Icon } from "../../../ui-components/icon/icon.component"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { EmojiBox } from "../../emoji/emoji-box/emoji-box.component"
import { AppColors } from "../../../app/app.colors"
import { MessageInputEditable } from "../message-input-editable/message-input-editable.component"
import { Tooltip } from "../../../ui-components/tooltip/tooltip.provider"
import { launchImageLibrary } from "react-native-image-picker"
import { ViewIf } from "../../../ui-components/view-if/view-if.component"
import { MessageInputAudio } from "../message-input-audio/message-input-audio.component"
export function MessageInput({
room,
scrollToMessage,
newMessageBundles,
}: {
room: RoomType
scrollToMessage: (messageId: string) => void
newMessageBundles: (messageBundle: MessageBundleType) => void
}) {
// ---------------------------------------------------------------------------
// variables
// ---------------------------------------------------------------------------
const styles = useStyles()
const modal = useModal()
const dimensions = useWindowDimensions()
const insets = useSafeAreaInsets()
const accountId = useAccountId()
const currentRoomUISettings = useCurrentRoomUISettings(room.id)
const quoteMessage = currentRoomUISettings.quotedMessage
const editMessage = currentRoomUISettings.editMessage
const screenHeight = dimensions.height
const { channel } = useRoomMetadata(room.id)
const [newInputHeight, setNewInputHeight] = useState(0)
const [isShowEmojiBox, setIsShowEmojiBox] = useState(false)
const [maxShowEmoji, setMaxShowEmoji] = useState(false)
const [expanded, setExpanded] = useState(false)
const [attachmentKind, setAttachmentKind] = useState()
const [textMessage, setTextMessage] = useState("")
const [editTextMessage, setEditTextMessage] = useState("")
const [editMessageInput, setEditMessageInput] = useState<MessageType | null>()
const [files, setFiles] = useState<FileType[]>([])
const [messageLinks, setMessageLinks] = useState<LinkPreviewType[]>([])
const [linkIgnoreList, setLinkIgnoreList] = useState([""])
const [emotionCategory, setEmotionCategory] =
useState("emoji")
const [currentType, setCurrentType] = useState<
"emoji" | "keyboard" | "sticker" | "gif"
("keyboard")
const [deviceState, setDeviceState] = useState({
camera: false,
microphone: false,
})
const [deviceActiveState, setDeviceActiveState] = useState({
cameraActive: false,
microphoneActive: false,
})
const [selection, setSelection] = useState({
start: 0,
end: 0,
})
const [showTools, setShowTools] = useState(false)
const [selectedToolbarIcon, setSelectedToolbarIcon] = useState<
"bold" | "italic" | "strikethrough" | "code" | "bulletList" | "orderedList"
("bold")
const [toggleMarkdownList, setToggleMarkdownList] = useState("")
const [slowModeTime, setSlowModeTime] = useState(0)
const inputRef = useRef<TextInput | null>(null)
const inputWrapperRef = useRef(null)
const slowModeInterval = useRef<NodeJS.Timeout>()
// ---------------------------------------------------------------------------
// animations
// ---------------------------------------------------------------------------
const inputHeight = useSharedValue(newInputHeight)
const animatedInputStyles = useAnimatedStyle(() => ({
height: maxShowEmoji ? inputHeight.value : "auto",
}))
const animatedEmojiStyles = useAnimatedStyle(() =>
maxShowEmoji
? { height: "auto" }
: isShowEmojiBox
? {
height: 320,
}
: {},
)
// ---------------------------------------------------------------------------
// effects
// ---------------------------------------------------------------------------
useEffect(() => {
if (channel && channel.slowMode) {
const lastMessageSendTime = room.lastMessageSendTime
const slowMode = channel ? channel.slowMode : 0
code Copy code
slowModeInterval.current = setInterval(() => {
const timeLeft =
slowMode - Math.floor((Date.now() - lastMessageSendTime) / 1000)
if (timeLeft < 0) {
clearInterval(slowModeInterval.current)
setSlowModeTime(timeLeft)
} else {
setSlowModeTime(timeLeft)
}
}, 1000)
}
return () => {
clearInterval(slowModeInterval.current)
}
}, [room.lastMessageSendTime])
useEffect(() => {
loadDraft()
}, [room.id])
useEffect(() => {
setEditMessageInput(editMessage)
code Copy code
if (editMessage) setEditTextMessage(editMessage.text)
}, [editMessage])
useEffect(() => {
if (!files.length) return
code Copy code
onMessageTyping(textMessage)
}, [files.length])
// ---------------------------------------------------------------------------
// functions
// ---------------------------------------------------------------------------
function goDown() {
inputHeight.value = withTiming(newInputHeight, {
duration: 0,
easing: Easing.inOut(Easing.quad),
reduceMotion: ReduceMotion.System,
})
code Copy code
setMaxShowEmoji(false)
setExpanded(false)
}
function goUp() {
if (!inputWrapperRef.current) return
code Copy code
inputWrapperRef.current.measure((x, y, width, height, pageX, pageY) => {
setNewInputHeight(height)
})
setTimeout(() => setMaxShowEmoji(true), 0)
inputHeight.value = withTiming(
screenHeight - insets.top - insets.bottom - 20,
{
duration: 0,
easing: Easing.inOut(Easing.quad),
reduceMotion: ReduceMotion.System,
},
)
setExpanded(true)
}
async function sendMessage(
kind: MessageKindEnum,
messageText: string,
mediaFile: FileType[],
sticker?: { sticker: StickerType; stickerPackId: string },
user?: {
id: string
name: string
photo: FileType | null
},
) {
if (!accountId || !currentRoomUISettings) return
code Copy code
if (channel && channel.slowMode) {
if (Date.now() - room.lastMessageSendTime > channel.slowMode * 1000) {
await AppController.room.update({
id: room.id,
lastMessageSendTime: Date.now(),
})
} else {
return
}
}
let attachments: AttachmentType[] = []
for (let file of mediaFile) {
if (!attachmentKind) return
const attachment: AttachmentType = {
id: RandomUtils.uuid(),
createdAt: Date.now(),
kind: attachmentKind,
name: file.name,
size: file.size,
roomId: room.id,
messageId: null,
senderId: accountId,
mimeType:
kind === MessageKindEnum.audio
? "audio-record"
: kind === MessageKindEnum.video
? "video-record"
: file.mimeType.startsWith("application")
? file.mimeType.split("/")[1]
: file.mimeType.split("/")[0],
preview: file.data,
fileId: file.id,
}
attachments.push(attachment)
}
let links: LinkType[] = []
for (let messageLink of messageLinks) {
const link: LinkType = {
id: RandomUtils.uuid(),
createdAt: Date.now(),
roomId: room.id,
...messageLink,
}
links.push(link)
}
const metadata: MessageMetadataType = {
id: RandomUtils.uuid(),
replyCount: 0,
}
const message: MessageType = {
id: RandomUtils.uuid(),
createdAt: Date.now(),
text: messageText,
roomId: room.id,
isEdited: false,
isDeleted: false,
isDelivered: false,
senderId: accountId,
attachmentIds: attachments.map((attachment) => attachment.id),
metadataId: metadata.id,
reactions: [],
forward: null,
regular: {
kind: kind,
isDeleted: false,
isUnread: [],
quote: quoteMessage
? {
id: quoteMessage.id,
text: quoteMessage.text,
senderId: quoteMessage.senderId,
sharedUser:
quoteMessage.regular && quoteMessage.regular.sharedUser
? true
: false,
pollId: quoteMessage.regular && quoteMessage.regular.pollId,
attachmentIds: quoteMessage.attachmentIds,
sticker: quoteMessage.regular && quoteMessage.regular.sticker,
}
: null,
pollId: null,
sharedUser: user ? user : null,
linkIds: links.map((link) => link.id),
sticker: sticker ? sticker : null,
},
question: null,
answer:
room.kind === RoomKindEnum.QUESTION_ANSWERS
? {
negativeVotes: [],
positiveVotes: [],
}
: null,
news: null,
issue: null,
board: null,
}
newMessageBundles({
links,
message,
metadata,
attachments,
})
await AppController.message.insert({
links,
message,
metadata,
attachments,
files: mediaFile,
})
AppStore.for(CurrentRoomUISettingsModel).add({
...currentRoomUISettings,
quotedMessage: undefined,
})
MessageTextAreaUtils.setDraft(room.id, null, room.draftMessage)
setTextMessage("")
await TrackPlayer.add({
id: "send",
url: require("../../../../public/sounds/message_send.wav"),
title: "Track Title",
artist: "Track Artist",
})
// Start playing it
await TrackPlayer.play()
removeAttachedData()
}
async function onMessageUpdate(
editedMessage: MessageType,
value: string,
attachments: AttachmentType[],
files: FileType[],
poll?: PollType,
) {
let links: LinkType[] = []
for (let messageLink of messageLinks) {
const link: LinkType = {
id: RandomUtils.uuid(),
createdAt: Date.now(),
roomId: room.id,
...messageLink,
}
code Copy code
links.push(link)
}
await AppController.message.update({
message: {
...editedMessage,
text: value,
isEdited: true,
attachmentIds: [],
},
files,
attachments,
links,
})
AppStore.for(CurrentRoomUISettingsModel).add({
...currentRoomUISettings,
editMessage: undefined,
})
setEditTextMessage("")
}
function removeAttachedData() {
setEditMessageInput(undefined)
setFiles([])
setMessageLinks([])
}
async function shareProfile(
users: {
id: string
name: string
photo: FileType | null
}[],
) {
for (let user of users) {
sendMessage(MessageKindEnum.sharedUser, "", [], undefined, user)
}
}
function onKeyPress(e: NativeSyntheticEvent) {
if (e.nativeEvent.key === "Enter") {
if (
selectedToolbarIcon === "bulletList" ||
selectedToolbarIcon === "orderedList"
) {
setToggleMarkdownList(selectedToolbarIcon)
}
}
}
async function loadDraft() {
if (!room.draftMessage) return
setTextMessage(room.draftMessage.text)
setFiles(room.draftMessage.files)
}
async function onMessageTyping(value: string) {
setTextMessage(value)
if (value.trim() !== "" || files.length !== 0) {
MessageTextAreaUtils.setDraft(
room.id,
{
text: value,
files,
},
room.draftMessage,
)
} else {
MessageTextAreaUtils.setDraft(room.id, null, room.draftMessage)
}
MessageTextAreaUtils.extractMessageLinks({
text: value,
ignoreList: linkIgnoreList,
onLinkExist: (links) => {
setMessageLinks(links)
},
onLinkIgnore: (links) => {
setLinkIgnoreList(links)
},
})
await AppController.message.typing(room.id)
}
async function onGallerySelect() {
const files = await launchImageLibrary({
mediaType: "mixed",
includeBase64: true,
includeExtra: true,
selectionLimit: 50,
maxHeight: 110,
})
code Copy code
if (!files.assets) return
for (let selectedFile of files.assets) {
if (!selectedFile.uri) return
const file = await fetch(selectedFile.uri).then((response) => {
return response.blob()
})
const reader = new FileReader()
reader.onload = () => {
const dataUrl = reader.result as string
setFiles([
{
id: CryptoUtils.sha256(dataUrl),
name: selectedFile.fileName ? selectedFile.fileName : "",
size: file.size,
mimeType: file.type,
data: dataUrl,
duration: null,
},
])
}
reader.readAsDataURL(file)
}
}
function openMessageInputPopup() {
modal.open({
component: (
<MessageInputPopup
roomId={room.id}
newMessageBundles={newMessageBundles}
isShowFileAndProfile={true}
onProfileSelect={shareProfile}
onFilesSelected={(files, kind) => {
setAttachmentKind(kind)
setFiles((prev) => [...prev, ...files])
}}
/>
),
code Copy code
height: 180,
})
}
// ---------------------------------------------------------------------------
return (
<>
{maxShowEmoji && }
)
}
after pressing on deleteLink in MessageLinkInputPreview component it also set setLinkIgnoreList to empty array but somehow not seting to empty array from TextInput not clearing. How to fix it ?