import { _ as _objectSpread2 } from '../_rollupPluginBabelHelpers-a69fd1ce.js';
import React__default, { useCallback, useRef, useState, useMemo, useEffect } from 'react';
import PropTypes from 'prop-types';
import { N as NodeTypes, M as MessageInputKeys, a as NodeNames } from '../const-ddd9d461.js';
import { U as USER_MENTION_TEMP_CHAR } from '../const-9982664a.js';
import IconButton from './IconButton.js';
import Button, { ButtonTypes, ButtonSizes } from './Button.js';
import DOMPurify from 'dompurify';
import { M as MENTION_USER_LABEL_CLASSNAME } from '../consts-15e764c0.js';
import Icon, { IconTypes, IconColors } from './Icon.js';
import { L as Label, a as LabelTypography, b as LabelColors } from '../index-4105bc4d.js';
import { u as useLocalization } from '../LocalizationContext-426f3d58.js';
import useSendbirdStateContext from '../useSendbirdStateContext.js';
import { j as arrayEqual, h as getClassName } from '../index-f83f0aac.js';
import { T as TEXT_MESSAGE_BODY_CLASSNAME } from '../consts-f99cd0da.js';
import { O as OG_MESSAGE_BODY_CLASSNAME } from '../consts-2eeaa3de.js';
import { t as tokenizeMessage, T as TOKEN_TYPES, U as USER_MENTION_PREFIX } from '../tokenize-eec42500.js';
import { K } from '../index.module-8bb7760e.js';
import '../stringSet-a62108b2.js';
import '../index-90420b99.js';
import '../withSendbird.js';
import '../utils/message/getOutgoingMessageState.js';

// cretes a sanitized string from a mention user label
function renderToString(_ref) {
  let {
    userId,
    nickname
  } = _ref;
  // donot change this template, it wont work
  const el = `<span data-userid="${userId}" data-sb-mention="true" class="${MENTION_USER_LABEL_CLASSNAME}">${nickname}</span>`;
  const purifier = DOMPurify(window);
  const sanitized_ = purifier.sanitize(el);
  const token = sanitized_.split(' ');
  const [spanTag, ...rest] = token;
  // we do this because DOMPurify removes the contenteditable attribute
  const sanitized = [spanTag, 'contenteditable="false"', ...rest].join(' ');
  return sanitized;
}

// https://davidwalsh.name/javascript-debounce-function

// Sanitize that special characters of HTML tags cause XSS issue
const sanitizeString = str => str === null || str === void 0 ? void 0 : str.replace(/[\u00A0-\u9999<>]/gim, i => ''.concat('&#', i.charCodeAt(0), ';'));

/**
 * NodeList cannot be used with Array methods
 * @param {childNodes} NodeList
 * @returns Array of child nodes
 */
const nodeListToArray = childNodes => {
  try {
    return Array.from(childNodes);
  } catch (error) {
    return [];
  }
};

function inserTemplateToDOM(templateList) {
  const nodes = templateList.map(template => {
    const {
      text,
      userId
    } = template;
    if (userId) {
      return renderToString({
        userId,
        nickname: text
      });
    }
    return sanitizeString(text);
  }).join(' ')
  // add a space at the end of the mention, else cursor/caret wont work
  .concat(' ');
  document.execCommand('insertHTML', false, nodes);
}

const PASTE_NODE = 'sendbird-uikit__paste-node';
const TEXT_MESSAGE_CLASS = 'sendbird-word';
const MENTION_CLASS = 'sendbird-word__mention';
const MENTION_CLASS_IN_INPUT = 'sendbird-mention-user-label';
const MENTION_CLASS_COMBINED_QUERY = `.${MENTION_CLASS}, .${MENTION_CLASS_IN_INPUT}`;

function querySelectorIncludingSelf(master, selector) {
  const result = [master, ...Array.from(master.querySelectorAll(selector))].find(el => el.matches(selector));
  return result;
}

// Pasted dom node can be OG_MESSAGE or partial message or full message
// full messsage would have TEXT_MESSAGE_BODY_CLASSNAME and have childNodes
// partial message would not have TEXT_MESSAGE_BODY_CLASSNAME
function getLeafNodes(master) {
  // og message
  const ogMessage = querySelectorIncludingSelf(master, `.${OG_MESSAGE_BODY_CLASSNAME}`);
  if (ogMessage) {
    return nodeListToArray(ogMessage.childNodes);
  }
  const textMessageBody = querySelectorIncludingSelf(master, `.${TEXT_MESSAGE_BODY_CLASSNAME}`);
  if (textMessageBody) {
    return nodeListToArray(textMessageBody.childNodes);
  }
  return nodeListToArray(master.childNodes);
}
function createPasteNode() {
  const pasteNode = document.body.querySelector(`#${PASTE_NODE}`);
  // remove existing paste node
  if (pasteNode) {
    pasteNode === null || pasteNode === void 0 ? void 0 : pasteNode.remove();
  }

  // create new paste node and return
  const node = document.createElement('div');
  node.id = PASTE_NODE;
  node.style.display = 'none';
  return node;
}
function hasMention(parent) {
  return parent !== null && parent !== void 0 && parent.querySelector(MENTION_CLASS_COMBINED_QUERY) ? true : false;
}
const extractTextFromNodes = nodes => {
  let text = '';
  nodes.forEach(node => {
    // to preserve space between words
    const textNodes = node.querySelectorAll(`.${TEXT_MESSAGE_CLASS}`);
    if (textNodes.length > 0) {
      text += extractTextFromNodes(Array.from(textNodes)) + ' ';
    }
    text += node.innerText + ' ';
  });
  return text;
};
function domToMessageTemplate(nodeArray) {
  const templates = nodeArray === null || nodeArray === void 0 ? void 0 : nodeArray.reduce((accumulator, currentValue) => {
    // currentValue can be node(from messageBody or messageInput) or text
    let mentionNode;
    // this looks awkward, but it is a fallback to set default text
    let text = currentValue === null || currentValue === void 0 ? void 0 : currentValue.innerText;

    // if text node, set text
    if (currentValue instanceof Text) {
      mentionNode = false;
      text = currentValue.textContent;
    }
    if (currentValue instanceof HTMLElement) {
      mentionNode = currentValue.classList.contains(MENTION_CLASS) || currentValue.classList.contains(MENTION_CLASS_IN_INPUT) ? currentValue : currentValue.querySelector(MENTION_CLASS_COMBINED_QUERY);
    }

    // if mentionNode is not null, it is a mention
    if (mentionNode) {
      var _mentionNode$dataset;
      const text = currentValue === null || currentValue === void 0 ? void 0 : currentValue.innerText;
      const userId = (_mentionNode$dataset = mentionNode.dataset) === null || _mentionNode$dataset === void 0 ? void 0 : _mentionNode$dataset.userid;
      return [...accumulator, {
        text,
        userId
      }];
    }
    return [...accumulator, {
      text
    }];
  }, []);
  return templates;
}
function getUsersFromWords(templates, channel) {
  const userMap = {};
  const users = channel.members;
  templates.forEach(template => {
    if (template.userId) {
      const mentionedMember = users.find(user => user.userId === template.userId);
      // Object.values would return array-> [undefined] if the user is not in the channel
      if (mentionedMember) {
        userMap[template.userId] = mentionedMember;
      }
    }
  });
  return Object.values(userMap);
}

// conditions to test:
// 1. paste simple text
// 2. paste text with mention
// 3. paste text with mention and text
// 4. paste text with mention and text and paste again before and after
// 5. copy message with mention(only one mention, no other text) and paste
// 6. copy message with mention from input and paste(before and after)
function usePaste(_ref) {
  let {
    ref,
    setIsInput,
    setHeight,
    channel,
    setMentionedUsers
  } = _ref;
  return useCallback(e => {
    e.preventDefault();
    const html = e === null || e === void 0 ? void 0 : e.clipboardData.getData('text/html');
    // simple text, continue as normal
    if (!html) {
      const text = e === null || e === void 0 ? void 0 : e.clipboardData.getData('text');
      document.execCommand('insertHTML', false, sanitizeString(text));
      setIsInput(true);
      setHeight();
      return;
    }

    // has html, check if there are mentions, sanitize and insert
    const purifier = DOMPurify(window);
    const clean = purifier.sanitize(html);
    const pasteNode = createPasteNode();
    pasteNode.innerHTML = clean;
    // does not have mention, continue as normal
    if (!hasMention(pasteNode)) {
      // to preserve space between words
      const text = extractTextFromNodes(Array.from(pasteNode.children));
      document.execCommand('insertHTML', false, sanitizeString(text));
      pasteNode.remove();
      setIsInput(true);
      setHeight();
      return;
    }

    // has mention, collect leaf nodes and parse words
    const leafNodes = getLeafNodes(pasteNode);
    const words = domToMessageTemplate(leafNodes);
    const mentionedUsers = getUsersFromWords(words, channel);

    // side effects
    setMentionedUsers(mentionedUsers);
    inserTemplateToDOM(words);
    pasteNode.remove();
    setIsInput(true);
    setHeight();
  }, [ref, setIsInput, setHeight, channel, setMentionedUsers]);
}

/**
 * Write new utils here
 * Migrate old utils as needed, and delete utils.js
 */
/**
 * FIXME:
 * Import this ChannelType enum from @sendbird/chat
 * once MessageInput.spec unit tests can be run \wo jest <-> ESM issue
 */
var ChannelType = /*#__PURE__*/function (ChannelType) {
  ChannelType["BASE"] = "base";
  ChannelType["GROUP"] = "group";
  ChannelType["OPEN"] = "open";
  return ChannelType;
}(ChannelType || {});
/**
 * FIXME: Simplify this in UIKit@v4
 * If customer is using MessageInput inside our modules(ie: Channel, Thread, etc),
 * we should use the config from the module.
 * If customer is using MessageInput outside our modules(ie: custom UI),
 * we expect Channel to be undefined and customer gets control to show/hide file-upload.
 * @param {*} channel GroupChannel | OpenChannel
 * @param {*} config SendBirdStateConfig
 * @returns boolean
 */
const checkIfFileUploadEnabled = _ref => {
  let {
    channel,
    config
  } = _ref;
  const isEnabled = K(channel === null || channel === void 0 ? void 0 : channel.channelType).with(ChannelType.GROUP, () => {
    var _config$groupChannel;
    return config === null || config === void 0 ? void 0 : (_config$groupChannel = config.groupChannel) === null || _config$groupChannel === void 0 ? void 0 : _config$groupChannel.enableDocument;
  }).with(ChannelType.OPEN, () => {
    var _config$openChannel;
    return config === null || config === void 0 ? void 0 : (_config$openChannel = config.openChannel) === null || _config$openChannel === void 0 ? void 0 : _config$openChannel.enableDocument;
  }).otherwise(() => true);
  return isEnabled;
};

const TEXT_FIELD_ID = 'sendbird-message-input-text-field';
const LINE_HEIGHT = 76;
const noop = () => {};
const handleUploadFile = callback => event => {
  if (event.target.files && event.target.files[0]) {
    callback(event.target.files[0]);
  }
  // eslint-disable-next-line no-param-reassign
  event.target.value = '';
};
const displayCaret = (element, position) => {
  const range = document.createRange();
  const sel = window.getSelection();
  range.setStart(element.childNodes[0], position);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
  element.focus();
};
const resetInput = ref => {
  try {
    /* eslint-disable no-param-reassign */
    ref.current.innerHTML = '';
  } catch (_unused) {
    //
  }
};
const initialTargetStringInfo = {
  targetString: '',
  startNodeIndex: null,
  startOffsetIndex: null,
  endNodeIndex: null,
  endOffsetIndex: null
};
const MessageInput = /*#__PURE__*/React__default.forwardRef((props, ref) => {
  var _ref$current, _ref$current$textCont, _textField$innerText;
  const {
    className,
    messageFieldId,
    isEdit,
    isMentionEnabled,
    isVoiceMessageEnabled,
    disabled,
    message,
    placeholder,
    maxLength,
    onFileUpload,
    onSendMessage,
    onUpdateMessage,
    onCancelEdit,
    onStartTyping,
    channelUrl,
    channel,
    mentionSelectedUser,
    onUserMentioned,
    onMentionStringChange,
    onMentionedUserIdsUpdated,
    onVoiceMessageIconClick,
    onKeyUp,
    onKeyDown,
    renderFileUploadIcon,
    renderVoiceMessageIcon,
    renderSendMessageIcon,
    setMentionedUsers
  } = props;
  const textFieldId = messageFieldId || TEXT_FIELD_ID;
  const {
    stringSet
  } = useLocalization();
  const {
    config
  } = useSendbirdStateContext();
  const isFileUploadEnabled = checkIfFileUploadEnabled({
    channel,
    config
  });
  const fileInputRef = useRef(null);
  const [isInput, setIsInput] = useState(false);
  const [mentionedUserIds, setMentionedUserIds] = useState([]);
  const [targetStringInfo, setTargetStringInfo] = useState(_objectSpread2({}, initialTargetStringInfo));
  const setHeight = useMemo(() => () => {
    try {
      const elem = ref === null || ref === void 0 ? void 0 : ref.current;
      const MAX_HEIGHT = window.document.body.offsetHeight * 0.6;
      if (elem && elem.scrollHeight >= LINE_HEIGHT) {
        if (MAX_HEIGHT < elem.scrollHeight) {
          elem.style.height = 'auto';
          elem.style.height = `${MAX_HEIGHT}px`;
        } else {
          elem.style.height = 'auto';
          elem.style.height = `${elem.scrollHeight}px`;
        }
      } else {
        elem.style.height = '';
      }
    } catch (error) {
      // error
    }
  }, []);

  // #Edit mode
  // for easilly initialize input value from outside, but
  // useEffect(_, [channelUrl]) erase it
  const initialValue = props === null || props === void 0 ? void 0 : props.value;
  useEffect(() => {
    var _textField$textConten;
    const textField = ref === null || ref === void 0 ? void 0 : ref.current;
    try {
      textField.innerHTML = initialValue;
      displayCaret(textField, initialValue === null || initialValue === void 0 ? void 0 : initialValue.length);
    } catch (_unused2) {
      //
    }
    setMentionedUserIds([]);
    setIsInput((textField === null || textField === void 0 ? void 0 : (_textField$textConten = textField.textContent) === null || _textField$textConten === void 0 ? void 0 : _textField$textConten.trim().length) > 0);
    setHeight();
  }, [initialValue]);

  // #Mention | Clear input value when channel changes
  useEffect(() => {
    if (!isEdit) {
      setIsInput(false);
      resetInput(ref);
    }
  }, [channelUrl]);

  // #Mention & #Edit | Fill message input values
  useEffect(() => {
    if (isEdit && message !== null && message !== void 0 && message.messageId) {
      var _message$mentionedUse, _message$mentionedMes, _textField$textConten2;
      // const textField = document.getElementById(textFieldId);
      const textField = ref === null || ref === void 0 ? void 0 : ref.current;
      if (isMentionEnabled && (message === null || message === void 0 ? void 0 : (_message$mentionedUse = message.mentionedUsers) === null || _message$mentionedUse === void 0 ? void 0 : _message$mentionedUse.length) > 0 && (message === null || message === void 0 ? void 0 : (_message$mentionedMes = message.mentionedMessageTemplate) === null || _message$mentionedMes === void 0 ? void 0 : _message$mentionedMes.length) > 0) {
        /* mention enabled */
        const {
          mentionedUsers = []
        } = message;
        const tokens = tokenizeMessage({
          messageText: message === null || message === void 0 ? void 0 : message.mentionedMessageTemplate,
          mentionedUsers
        });
        textField.innerHTML = tokens.map(token => {
          if (token.type === TOKEN_TYPES.mention) {
            const mentionedUser = mentionedUsers.find(user => user.userId === token.userId);
            const nickname = `${USER_MENTION_PREFIX}${(mentionedUser === null || mentionedUser === void 0 ? void 0 : mentionedUser.nickname) || token.value || stringSet.MENTION_NAME__NO_NAME}`;
            return renderToString({
              userId: token.userId,
              nickname
            });
          }
          return sanitizeString(token.value);
        }).join(' ');
      } else {
        /* mention disabled */
        try {
          textField.innerHTML = sanitizeString(message === null || message === void 0 ? void 0 : message.message);
        } catch (_unused3) {
          //
        }
        setMentionedUserIds([]);
      }
      setIsInput((textField === null || textField === void 0 ? void 0 : (_textField$textConten2 = textField.textContent) === null || _textField$textConten2 === void 0 ? void 0 : _textField$textConten2.trim().length) > 0);
      setHeight();
    }
  }, [isEdit, message]);

  // #Mention | Detect MentionedLabel modified
  const useMentionedLabelDetection = useCallback(() => {
    var _textField$textConten3;
    const textField = ref === null || ref === void 0 ? void 0 : ref.current;
    if (isMentionEnabled) {
      const newMentionedUserIds = [...textField.getElementsByClassName('sendbird-mention-user-label')].map(node => {
        var _node$dataset;
        return node === null || node === void 0 ? void 0 : (_node$dataset = node.dataset) === null || _node$dataset === void 0 ? void 0 : _node$dataset.userid;
      });
      if (!arrayEqual(mentionedUserIds, newMentionedUserIds) || newMentionedUserIds.length === 0) {
        onMentionedUserIdsUpdated(newMentionedUserIds);
        setMentionedUserIds(newMentionedUserIds);
      }
    }
    setIsInput(((_textField$textConten3 = textField.textContent) === null || _textField$textConten3 === void 0 ? void 0 : _textField$textConten3.trim().length) > 0);
  }, [targetStringInfo, isMentionEnabled]);

  // #Mention | Replace selected user nickname to the MentionedUserLabel
  useEffect(() => {
    if (isMentionEnabled && mentionSelectedUser) {
      const {
        targetString,
        startNodeIndex,
        startOffsetIndex,
        endNodeIndex,
        endOffsetIndex
      } = targetStringInfo;
      if (targetString && startNodeIndex !== null && startOffsetIndex !== null) {
        var _document, _childNodes$startNode, _document2, _childNodes$endNodeIn;
        // const textField = document.getElementById(textFieldId);
        const textField = ref === null || ref === void 0 ? void 0 : ref.current;
        const childNodes = nodeListToArray(textField === null || textField === void 0 ? void 0 : textField.childNodes);
        const frontTextNode = (_document = document) === null || _document === void 0 ? void 0 : _document.createTextNode((_childNodes$startNode = childNodes[startNodeIndex]) === null || _childNodes$startNode === void 0 ? void 0 : _childNodes$startNode.textContent.slice(0, startOffsetIndex));
        const backTextNode = (_document2 = document) === null || _document2 === void 0 ? void 0 : _document2.createTextNode(`\u00A0${(_childNodes$endNodeIn = childNodes[endNodeIndex]) === null || _childNodes$endNodeIn === void 0 ? void 0 : _childNodes$endNodeIn.textContent.slice(endOffsetIndex)}`);
        const mentionLabel = renderToString({
          userId: mentionSelectedUser === null || mentionSelectedUser === void 0 ? void 0 : mentionSelectedUser.userId,
          nickname: `${USER_MENTION_TEMP_CHAR}${(mentionSelectedUser === null || mentionSelectedUser === void 0 ? void 0 : mentionSelectedUser.nickname) || stringSet.MENTION_NAME__NO_NAME}`
        });
        const div = document.createElement('div');
        div.innerHTML = mentionLabel;
        const newNodes = [...childNodes.slice(0, startNodeIndex), frontTextNode, div.childNodes[0], backTextNode, ...childNodes.slice(endNodeIndex + 1)];
        textField.innerHTML = '';
        newNodes.forEach(newNode => {
          textField.appendChild(newNode);
        });
        onUserMentioned(mentionSelectedUser);
        if (window.getSelection || document.getSelection) {
          // set caret postion
          const selection = window.getSelection() || document.getSelection();
          selection.removeAllRanges();
          const range = new Range();
          range.selectNodeContents(textField);
          range.setStart(textField.childNodes[startNodeIndex + 2], 1);
          range.setEnd(textField.childNodes[startNodeIndex + 2], 1);
          range.collapse(false);
          selection.addRange(range);
          textField.focus();
        }
        setTargetStringInfo(_objectSpread2({}, initialTargetStringInfo));
        setHeight();
        useMentionedLabelDetection();
      }
    }
  }, [mentionSelectedUser, isMentionEnabled]);

  // #Mention | Detect mentioning user nickname
  const useMentionInputDetection = useCallback(() => {
    var _window, _window$getSelection, _document3, _document3$getSelecti;
    const selection = ((_window = window) === null || _window === void 0 ? void 0 : (_window$getSelection = _window.getSelection) === null || _window$getSelection === void 0 ? void 0 : _window$getSelection.call(_window)) || ((_document3 = document) === null || _document3 === void 0 ? void 0 : (_document3$getSelecti = _document3.getSelection) === null || _document3$getSelecti === void 0 ? void 0 : _document3$getSelecti.call(_document3));
    const textField = ref === null || ref === void 0 ? void 0 : ref.current;
    if (selection.anchorNode === textField) {
      onMentionStringChange('');
    }
    if (isMentionEnabled && selection && selection.anchorNode === selection.focusNode && selection.anchorOffset === selection.focusOffset) {
      let textStack = '';
      let startNodeIndex = null;
      let startOffsetIndex = null;
      for (let index = 0; index < textField.childNodes.length; index += 1) {
        const currentNode = textField.childNodes[index];
        if (currentNode.nodeType === NodeTypes.TextNode) {
          /* text node */
          const textContent = currentNode === selection.anchorNode ? (currentNode === null || currentNode === void 0 ? void 0 : currentNode.textContent.slice(0, selection.anchorOffset)) || '' : (currentNode === null || currentNode === void 0 ? void 0 : currentNode.textContent) || '';
          if (textStack.length > 0) {
            textStack += textContent;
          } else {
            let charLastIndex = textContent.lastIndexOf(USER_MENTION_TEMP_CHAR);
            for (let i = charLastIndex - 1; i > -1; i -= 1) {
              if (textContent[i] === USER_MENTION_TEMP_CHAR) {
                charLastIndex = i;
              } else {
                break;
              }
            }
            if (charLastIndex > -1) {
              textStack = textContent;
              startNodeIndex = index;
              startOffsetIndex = charLastIndex;
            }
          }
        } else {
          /* other nodes */
          textStack = '';
          startNodeIndex = null;
          startOffsetIndex = null;
        }
        if (currentNode === selection.anchorNode) {
          /**
           * targetString could be ''
           * startNodeIndex and startOffsetIndex could be null
           */
          const targetString = textStack ? textStack.slice(startOffsetIndex) : ''; // include template character
          setTargetStringInfo({
            targetString,
            startNodeIndex,
            startOffsetIndex,
            endNodeIndex: index,
            endOffsetIndex: selection.anchorOffset
          });
          onMentionStringChange(targetString);
          return;
        }
      }
    }
  }, [isMentionEnabled]);
  const sendMessage = () => {
    const textField = ref === null || ref === void 0 ? void 0 : ref.current;
    if (!isEdit && textField !== null && textField !== void 0 && textField.textContent) {
      let messageText = '';
      let mentionTemplate = '';
      textField.childNodes.forEach(node => {
        if (node.nodeType === NodeTypes.ElementNode && node.nodeName === NodeNames.Span) {
          const {
            innerText,
            dataset = {}
          } = node;
          const {
            userid = ''
          } = dataset;
          messageText += innerText;
          mentionTemplate += `${USER_MENTION_TEMP_CHAR}{${userid}}`;
        } else if (node.nodeType === NodeTypes.ElementNode && node.nodeName === NodeNames.Br) {
          messageText += '\n';
          mentionTemplate += '\n';
        } else if ((node === null || node === void 0 ? void 0 : node.nodeType) === NodeTypes.ElementNode && (node === null || node === void 0 ? void 0 : node.nodeName) === NodeNames.Div) {
          // handles newline in safari
          const {
            textContent = ''
          } = node;
          messageText += `\n${textContent}`;
          mentionTemplate += `\n${textContent}`;
        } else {
          // other nodes including text node
          const {
            textContent = ''
          } = node;
          messageText += textContent;
          mentionTemplate += textContent;
        }
      });
      const params = {
        message: messageText,
        mentionTemplate
      };
      onSendMessage(params);
      resetInput(ref);
      // important: keeps the keyboard open -> must add test on refactor
      textField.focus();
      setIsInput(false);
      setHeight();
    }
  };
  const isEditDisabled = !(ref !== null && ref !== void 0 && (_ref$current = ref.current) !== null && _ref$current !== void 0 && (_ref$current$textCont = _ref$current.textContent) !== null && _ref$current$textCont !== void 0 && _ref$current$textCont.trim());
  const editMessage = () => {
    const textField = ref === null || ref === void 0 ? void 0 : ref.current;
    const messageId = message === null || message === void 0 ? void 0 : message.messageId;
    if (isEdit && messageId) {
      let messageText = '';
      let mentionTemplate = '';
      textField.childNodes.forEach(node => {
        if (node.nodeType === NodeTypes.ElementNode && node.nodeName === NodeNames.Span) {
          const {
            innerText,
            dataset = {}
          } = node;
          const {
            userid = ''
          } = dataset;
          messageText += innerText;
          mentionTemplate += `${USER_MENTION_TEMP_CHAR}{${userid}}`;
          messageText += '\n';
          mentionTemplate += '\n';
        } else {
          // other nodes including text node
          const {
            textContent = ''
          } = node;
          messageText += textContent;
          mentionTemplate += textContent;
        }
      });
      const params = {
        messageId,
        message: messageText,
        mentionTemplate
      };
      onUpdateMessage(params);
      resetInput(ref);
    }
  };
  const onPaste = usePaste({
    ref,
    setMentionedUserIds,
    setMentionedUsers,
    channel,
    setIsInput,
    setHeight
  });
  const textField = ref === null || ref === void 0 ? void 0 : ref.current;
  return /*#__PURE__*/React__default.createElement("form", {
    className: getClassName([className, isEdit ? 'sendbird-message-input__edit' : '', disabled ? 'sendbird-message-input-form__disabled' : ''])
  }, /*#__PURE__*/React__default.createElement("div", {
    className: getClassName(['sendbird-message-input', disabled ? 'sendbird-message-input__disabled' : ''])
  }, /*#__PURE__*/React__default.createElement("div", {
    id: `${textFieldId}${isEdit ? message === null || message === void 0 ? void 0 : message.messageId : ''}`,
    className: `sendbird-message-input--textarea ${textFieldId}`,
    contentEditable: !disabled,
    role: "textbox",
    "aria-label": "Text Input",
    disabled: disabled,
    ref: ref,
    maxLength: maxLength,
    onKeyDown: e => {
      const preventEvent = onKeyDown(e);
      if (preventEvent) {
        e.preventDefault();
      } else {
        var _textField$textConten4, _e$nativeEvent, _ref$current2, _ref$current2$childNo, _ref$current3, _ref$current3$childNo, _ref$current3$childNo2, _ref$current$childNod, _ref$current$childNod2;
        if (!e.shiftKey && e.key === MessageInputKeys.Enter && (textField === null || textField === void 0 ? void 0 : (_textField$textConten4 = textField.textContent) === null || _textField$textConten4 === void 0 ? void 0 : _textField$textConten4.trim().length) > 0 && (e === null || e === void 0 ? void 0 : (_e$nativeEvent = e.nativeEvent) === null || _e$nativeEvent === void 0 ? void 0 : _e$nativeEvent.isComposing) !== true) {
          e.preventDefault();
          sendMessage();
        }
        if (e.key === MessageInputKeys.Backspace && (ref === null || ref === void 0 ? void 0 : (_ref$current2 = ref.current) === null || _ref$current2 === void 0 ? void 0 : (_ref$current2$childNo = _ref$current2.childNodes) === null || _ref$current2$childNo === void 0 ? void 0 : _ref$current2$childNo.length) === 2 && !(ref !== null && ref !== void 0 && (_ref$current3 = ref.current) !== null && _ref$current3 !== void 0 && (_ref$current3$childNo = _ref$current3.childNodes) !== null && _ref$current3$childNo !== void 0 && (_ref$current3$childNo2 = _ref$current3$childNo[0]) !== null && _ref$current3$childNo2 !== void 0 && _ref$current3$childNo2.textContent) && (ref === null || ref === void 0 ? void 0 : (_ref$current$childNod = ref.current.childNodes) === null || _ref$current$childNod === void 0 ? void 0 : (_ref$current$childNod2 = _ref$current$childNod[1]) === null || _ref$current$childNod2 === void 0 ? void 0 : _ref$current$childNod2.nodeType) === NodeTypes.ElementNode) {
          ref === null || ref === void 0 ? void 0 : ref.current.removeChild(ref === null || ref === void 0 ? void 0 : ref.current.childNodes[1]);
        }
      }
    },
    onKeyUp: e => {
      const preventEvent = onKeyUp(e);
      if (preventEvent) {
        e.preventDefault();
      } else {
        useMentionInputDetection();
      }
    },
    onClick: () => {
      useMentionInputDetection();
    },
    onInput: () => {
      var _textField$textConten5;
      setHeight();
      onStartTyping();
      setIsInput((textField === null || textField === void 0 ? void 0 : (_textField$textConten5 = textField.textContent) === null || _textField$textConten5 === void 0 ? void 0 : _textField$textConten5.trim().length) > 0);
      useMentionedLabelDetection();
    },
    onPaste: onPaste
  }), (textField === null || textField === void 0 ? void 0 : (_textField$innerText = textField.innerText) === null || _textField$innerText === void 0 ? void 0 : _textField$innerText.length) === 0 && /*#__PURE__*/React__default.createElement(Label, {
    className: "sendbird-message-input--placeholder",
    type: LabelTypography.BODY_1,
    color: disabled ? LabelColors.ONBACKGROUND_4 : LabelColors.ONBACKGROUND_3
  }, placeholder || stringSet.MESSAGE_INPUT__PLACE_HOLDER), !isEdit && isInput && /*#__PURE__*/React__default.createElement(IconButton, {
    className: "sendbird-message-input--send",
    height: "32px",
    width: "32px",
    onClick: () => sendMessage()
  }, (renderSendMessageIcon === null || renderSendMessageIcon === void 0 ? void 0 : renderSendMessageIcon()) || /*#__PURE__*/React__default.createElement(Icon, {
    type: IconTypes.SEND,
    fillColor: disabled ? IconColors.ON_BACKGROUND_4 : IconColors.PRIMARY,
    width: "20px",
    height: "20px"
  })), !isEdit && !isInput && ((renderFileUploadIcon === null || renderFileUploadIcon === void 0 ? void 0 : renderFileUploadIcon() // UIKit Dashboard configuration should have lower priority than
  // renderFileUploadIcon which is set in code level
  ) || isFileUploadEnabled && /*#__PURE__*/React__default.createElement(IconButton, {
    className: `sendbird-message-input--attach ${isVoiceMessageEnabled ? 'is-voice-message-enabled' : ''}`,
    height: "32px",
    width: "32px",
    onClick: () => {
      var _fileInputRef$current, _fileInputRef$current2;
      // todo: clear previous input
      fileInputRef === null || fileInputRef === void 0 ? void 0 : (_fileInputRef$current = fileInputRef.current) === null || _fileInputRef$current === void 0 ? void 0 : (_fileInputRef$current2 = _fileInputRef$current.click) === null || _fileInputRef$current2 === void 0 ? void 0 : _fileInputRef$current2.call(_fileInputRef$current);
    }
  }, /*#__PURE__*/React__default.createElement(Icon, {
    type: IconTypes.ATTACH,
    fillColor: disabled ? IconColors.ON_BACKGROUND_4 : IconColors.CONTENT_INVERSE,
    width: "20px",
    height: "20px"
  }), /*#__PURE__*/React__default.createElement("input", {
    className: "sendbird-message-input--attach-input",
    type: "file",
    ref: fileInputRef,
    onChange: handleUploadFile(onFileUpload)
  }))), isVoiceMessageEnabled && !isEdit && !isInput && /*#__PURE__*/React__default.createElement(IconButton, {
    className: "sendbird-message-input--voice-message",
    width: "32px",
    height: "32px",
    onClick: onVoiceMessageIconClick
  }, (renderVoiceMessageIcon === null || renderVoiceMessageIcon === void 0 ? void 0 : renderVoiceMessageIcon()) || /*#__PURE__*/React__default.createElement(Icon, {
    type: IconTypes.AUDIO_ON_LINED,
    fillColor: disabled ? IconColors.ON_BACKGROUND_4 : IconColors.CONTENT_INVERSE,
    width: "20px",
    height: "20px"
  }))), isEdit && /*#__PURE__*/React__default.createElement("div", {
    className: "sendbird-message-input--edit-action"
  }, /*#__PURE__*/React__default.createElement(Button, {
    className: "sendbird-message-input--edit-action__cancel",
    type: ButtonTypes.SECONDARY,
    size: ButtonSizes.SMALL,
    onClick: onCancelEdit
  }, stringSet.BUTTON__CANCEL), /*#__PURE__*/React__default.createElement(Button, {
    className: "sendbird-message-input--edit-action__save",
    type: ButtonTypes.PRIMARY,
    size: ButtonSizes.SMALL,
    disabled: isEditDisabled,
    onClick: () => editMessage()
  }, stringSet.BUTTON__SAVE)));
});
MessageInput.propTypes = {
  className: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  messageFieldId: PropTypes.string,
  placeholder: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  value: PropTypes.string,
  isEdit: PropTypes.bool,
  isMentionEnabled: PropTypes.bool,
  isVoiceMessageEnabled: PropTypes.bool,
  onVoiceMessageIconClick: PropTypes.func,
  message: PropTypes.shape({
    messageId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    message: PropTypes.string,
    mentionedMessageTemplate: PropTypes.string,
    mentionedUsers: PropTypes.arrayOf(PropTypes.shape({}))
  }),
  disabled: PropTypes.bool,
  maxLength: PropTypes.number,
  onFileUpload: PropTypes.func,
  onSendMessage: PropTypes.func,
  onUpdateMessage: PropTypes.func,
  onStartTyping: PropTypes.func,
  onCancelEdit: PropTypes.func,
  channelUrl: PropTypes.string,
  mentionSelectedUser: PropTypes.shape({
    userId: PropTypes.string,
    nickname: PropTypes.string
  }),
  setMentionedUsers: PropTypes.func,
  onUserMentioned: PropTypes.func,
  onMentionStringChange: PropTypes.func,
  onMentionedUserIdsUpdated: PropTypes.func,
  onKeyUp: PropTypes.func,
  onKeyDown: PropTypes.func,
  renderVoiceMessageIcon: PropTypes.func,
  renderSendMessageIcon: PropTypes.func,
  renderFileUploadIcon: PropTypes.func,
  channel: PropTypes.shape({
    channelType: PropTypes.string
  }).isRequired
};
MessageInput.defaultProps = {
  className: '',
  messageFieldId: '',
  channelUrl: '',
  onSendMessage: noop,
  onUpdateMessage: noop,
  value: null,
  message: null,
  isEdit: false,
  isMentionEnabled: false,
  isVoiceMessageEnabled: true,
  onVoiceMessageIconClick: noop,
  disabled: false,
  placeholder: '',
  maxLength: 5000,
  onFileUpload: noop,
  onCancelEdit: noop,
  onStartTyping: noop,
  mentionSelectedUser: null,
  onUserMentioned: noop,
  onMentionStringChange: noop,
  onMentionedUserIdsUpdated: noop,
  onKeyUp: noop,
  onKeyDown: noop,
  setMentionedUsers: noop,
  renderVoiceMessageIcon: noop,
  renderFileUploadIcon: noop,
  renderSendMessageIcon: noop
};

export { MessageInput as default };
//# sourceMappingURL=MessageInput.js.map
