ChatPanel.js (3775B) [raw]
1 import React from 'react'; 2 import PropTypes from 'prop-types'; 3 import { Tile, TextInput, Button } from 'carbon-components-react'; 4 import {SendFilled16} from '@carbon/icons-react'; 5 6 const MAX_POSTS = 40; 7 8 class ChatPanel extends React.Component { 9 10 constructor(props) { 11 super(props); 12 this.state = { 13 post: '', 14 numPosts: 0, 15 postArray: [] 16 } 17 }; 18 19 componentDidMount () { 20 this.chatIn.onkeydown = this.checkKey; 21 } 22 23 checkKey = event => { 24 const code = event.keyCode || event.which; 25 if (code == 13) { 26 this.handleSendPost(); 27 } 28 } 29 30 componentDidUpdate (prevProps) { 31 const { receivedChat } = this.props; 32 const { postArray, numPosts } = this.state; 33 let nextArray = postArray; 34 if (receivedChat && (receivedChat != prevProps.receivedChat)){ 35 const nextNum = numPosts + 1; 36 const id = 'post-' + nextNum; 37 let clsName = 'chat__post'; 38 let postMsg = receivedChat; 39 if (receivedChat.startsWith('<<Error')){ 40 clsName = 'err__post'; 41 postMsg = receivedChat.substring(2); 42 } 43 nextArray.push( 44 <p className={clsName} 45 key={nextNum} 46 id={id}>{postMsg}</p> 47 ); 48 if (nextArray.length > MAX_POSTS){ 49 nextArray = nextArray.slice(1); 50 } 51 this.setState({ 52 postArray: nextArray, 53 numPosts: nextNum 54 }, () => { 55 const element = document.getElementById(id); 56 if (element) { 57 setTimeout(()=>{ 58 element.scrollIntoView(); 59 }, 100); 60 } 61 }); 62 } 63 } 64 65 handleChatIn = event => { 66 const val = event.target.value; 67 this.setState({ post: val}); 68 } 69 70 handleSendPost = () => { 71 const { post } = this.state; 72 if (post && post != ''){ 73 this.props.sendChat(post); 74 } 75 this.setState({ 76 post: '' 77 }); 78 this.chatIn.value = ''; 79 this.postButton.blur(); 80 } 81 82 render () { 83 const { post, postArray } = this.state; 84 return ( 85 <div className="cp__outer"> 86 <div className="chat__panel"> 87 <div className="chat__holder"> 88 <div className="chat__tile"> 89 {postArray} 90 </div> 91 </div> 92 <div className="chat__input__row"> 93 <TextInput 94 id="chat__in" 95 light 96 className="chat__in__input" 97 labelText="text input for chat" 98 hideLabel={true} 99 placeholder="enter chat posts here" 100 size="sm" 101 onChange={this.handleChatIn} 102 ref={(input) => {this.chatIn = input;}} 103 /> 104 <Button 105 className="post__button" 106 size="small" 107 hasIconOnly={true} 108 onClick={this.handleSendPost} 109 renderIcon={SendFilled16} 110 iconDescription="send chat" 111 tooltipPosition="bottom" 112 ref={(button) => {this.postButton = button;}} 113 /> 114 </div> 115 </div> 116 </div> 117 ) 118 } 119 120 } 121 ChatPanel.propTypes = { 122 receivedChat: PropTypes.string, 123 sendChat: PropTypes.func 124 } 125 export default ChatPanel;