improve livechat

This commit is contained in:
SrGooglo 2025-04-02 01:52:02 +00:00
parent bfd4e28d01
commit b43aa731ca
2 changed files with 399 additions and 372 deletions

View File

@ -8,327 +8,353 @@ import SessionModel from "@models/session"
import "./index.less"
const Line = (props) => {
const { user, content } = props
const { user, content } = props
return <div className="textRoom_line">
<div className="textRoom_line_user">
<h4>{user.fullName ?? user.username}</h4>
</div>
<div className="textRoom_line_content">
<span>{content}</span>
</div>
</div>
return (
<div className="textRoom_line">
<div className="textRoom_line_user">
<h4>{user.fullName ?? user.username}</h4>
</div>
<div className="textRoom_line_content">
<span>{content}</span>
</div>
</div>
)
}
export default class LiveChat extends React.Component {
state = {
joining: true,
roomInfo: null,
state = {
joining: true,
roomInfo: null,
timeline: [],
temporalTimeline: [],
maxTemporalLines: this.props.maxTemporalLines ?? 10,
timeline: [],
temporalTimeline: [],
maxTemporalLines: this.props.maxTemporalLines ?? 10,
lastSentMessage: null,
writtedMessage: "",
}
lastSentMessage: null,
writtedMessage: "",
}
debouncedIntervalTimelinePurge = null
debouncedIntervalTimelinePurge = null
timelineRef = React.createRef()
timelineRef = React.createRef()
socket = app.cores.api.client().sockets.chats
socket = app.cores.api.client().ws.sockets.get("chats")
roomEvents = {
"room:message": (message) => {
if (message.content === this.state.lastSentMessage) {
console.timeEnd("[CHATROOM] SUBMIT:MESSAGE")
}
roomEvents = {
"room:message": (message) => {
if (message.content === this.state.lastSentMessage) {
console.timeEnd("[CHATROOM] SUBMIT:MESSAGE")
}
this.pushToTimeline(message)
},
"room:joined": (info) => {
console.log("[CHATROOM] Room joined", info)
this.pushToTimeline(message)
},
"room:joined": (info) => {
console.log("[CHATROOM] Room joined", info)
this.setState({
joining: false,
roomInfo: info,
})
},
"room:leave": (info) => {
console.log("[CHATROOM] Room left", info)
this.setState({
joining: false,
roomInfo: info,
})
},
"room:leave": (info) => {
console.log("[CHATROOM] Room left", info)
this.setState({
joining: true,
roomInfo: null,
})
}
}
this.setState({
joining: true,
roomInfo: null,
})
},
}
joinSocketRoom = async () => {
if (!SessionModel.token) {
return this.setState({
noAuthed: true,
})
}
joinSocketRoom = async () => {
if (!SessionModel.token) {
return this.setState({
noAuthed: true,
})
}
console.log(`[CHATROOM] Joining socket room [${this.props.id}]...`)
console.log(`[CHATROOM] Joining socket room [${this.props.id}]...`)
for (const [eventName, eventHandler] of Object.entries(this.roomEvents)) {
this.socket.on(eventName, eventHandler)
}
for (const [eventName, eventHandler] of Object.entries(
this.roomEvents,
)) {
this.socket.on(eventName, eventHandler)
}
await this.setState({
joining: true,
})
await this.setState({
joining: true,
})
this.socket.emit(
"join:room",
{
room: this.props.id,
},
(error, info) => {
if (error) {
this.setState({ connectionEnd: true })
this.socket.emit(
"join:room",
{
room: this.props.id,
},
(error, info) => {
if (error) {
this.setState({ connectionEnd: true })
return console.error("Error joining room", error)
}
}
)
}
return console.error("Error joining room", error)
}
},
)
}
leaveSocketRoom = () => {
if (this.state.connectionEnd) {
return false
}
leaveSocketRoom = () => {
if (this.state.connectionEnd) {
return false
}
console.log(`[CHATROOM] Leaving socket room [${this.props.id}]...`)
console.log(`[CHATROOM] Leaving socket room [${this.props.id}]...`)
for (const [eventName, eventHandler] of Object.entries(this.roomEvents)) {
this.socket.off(eventName, eventHandler)
}
for (const [eventName, eventHandler] of Object.entries(
this.roomEvents,
)) {
this.socket.off(eventName, eventHandler)
}
this.socket.emit("leave:room")
}
this.socket.emit("leave:room")
}
submitMessage = (message) => {
console.time("[CHATROOM] SUBMIT:MESSAGE")
submitMessage = (message) => {
console.time("[CHATROOM] SUBMIT:MESSAGE")
this.socket.emit("room:send:message", {
message
})
this.socket.emit("room:send:message", {
message,
})
// remove writted message
this.setState({
lastSentMessage: message,
writtedMessage: ""
})
}
// remove writted message
this.setState({
lastSentMessage: message,
writtedMessage: "",
})
}
pushToTimeline = (message) => {
const { timeline } = this.state
pushToTimeline = (message) => {
const { timeline } = this.state
if (typeof message.key === "undefined") {
message.key = this.state.timeline.length
}
if (typeof message.key === "undefined") {
message.key = this.state.timeline.length
}
this.setState({
timeline: [...timeline, message]
})
this.setState({
timeline: [...timeline, message],
})
if (this.props.floatingMode) {
if (this.state.temporalTimeline.length >= this.state.maxTemporalLines) {
this.setState({
temporalTimeline: this.state.temporalTimeline.slice(1)
})
}
if (this.props.floatingMode) {
if (
this.state.temporalTimeline.length >=
this.state.maxTemporalLines
) {
this.setState({
temporalTimeline: this.state.temporalTimeline.slice(1),
})
}
// calculate duration based on message length (Minimum 3 second, maximum 10 seconds)
const calculatedDuration = Math.min(Math.max(message.content.length * 0.1, 3), 10) * 1000
// calculate duration based on message length (Minimum 3 second, maximum 10 seconds)
const calculatedDuration =
Math.min(Math.max(message.content.length * 0.1, 3), 10) * 1000
const temporalLine = {
expireTime: Date.now() + calculatedDuration,
duration: calculatedDuration,
messageKey: message.key
}
const temporalLine = {
expireTime: Date.now() + calculatedDuration,
duration: calculatedDuration,
messageKey: message.key,
}
this.setState({
temporalTimeline: [...this.state.temporalTimeline, temporalLine]
})
this.setState({
temporalTimeline: [
...this.state.temporalTimeline,
temporalLine,
],
})
if (this.debouncedIntervalTimelinePurge) {
clearInterval(this.debouncedIntervalTimelinePurge)
}
if (this.debouncedIntervalTimelinePurge) {
clearInterval(this.debouncedIntervalTimelinePurge)
}
this.debouncedIntervalTimelinePurge = setInterval(this.purgeLastTemporalLine, 3000)
}
this.debouncedIntervalTimelinePurge = setInterval(
this.purgeLastTemporalLine,
3000,
)
}
this.scrollTimelineToBottom()
}
this.scrollTimelineToBottom()
}
purgeLastTemporalLine = () => {
if (!this.props.floatingMode) {
return false
}
purgeLastTemporalLine = () => {
if (!this.props.floatingMode) {
return false
}
const { temporalTimeline } = this.state
const { temporalTimeline } = this.state
if (temporalTimeline.length === 0) {
clearInterval(this.debouncedIntervalTimelinePurge)
return false
}
if (temporalTimeline.length === 0) {
clearInterval(this.debouncedIntervalTimelinePurge)
return false
}
const lastTemporalLine = temporalTimeline[0]
const lastTemporalLine = temporalTimeline[0]
if (lastTemporalLine.expireTime < Date.now()) {
this.setState({
temporalTimeline: temporalTimeline.slice(1)
})
}
}
if (lastTemporalLine.expireTime < Date.now()) {
this.setState({
temporalTimeline: temporalTimeline.slice(1),
})
}
}
handleInputChange = (e) => {
if (e.target.value[0] === " " || e.target.value[0] === "\n") {
e.target.value = e.target.value.slice(1)
}
handleInputChange = (e) => {
if (e.target.value[0] === " " || e.target.value[0] === "\n") {
e.target.value = e.target.value.slice(1)
}
this.setState({
writtedMessage: e.target.value
})
}
this.setState({
writtedMessage: e.target.value,
})
}
handleOnEnter = (e) => {
e.preventDefault()
e.stopPropagation()
handleOnEnter = (e) => {
e.preventDefault()
e.stopPropagation()
if (e.target.value.length === 0) {
return
}
if (e.target.value.length === 0) {
return
}
this.submitMessage(e.target.value)
}
this.submitMessage(e.target.value)
}
scrollTimelineToBottom = () => {
const scrollingElement = document.getElementById("liveChat_timeline")
scrollTimelineToBottom = () => {
const scrollingElement = document.getElementById("liveChat_timeline")
if (scrollingElement) {
scrollingElement.scrollTo({
top: scrollingElement.scrollHeight,
behavior: "smooth"
})
}
}
if (scrollingElement) {
scrollingElement.scrollTo({
top: scrollingElement.scrollHeight,
behavior: "smooth",
})
}
}
componentDidMount = async () => {
this.joinSocketRoom()
componentDidMount = async () => {
this.joinSocketRoom()
app.ctx = {
submit: this.submitMessage
}
}
app.ctx = {
submit: this.submitMessage,
}
}
componentWillUnmount() {
this.leaveSocketRoom()
componentWillUnmount() {
this.leaveSocketRoom()
if (this.debouncedIntervalTimelinePurge) {
clearInterval(this.debouncedIntervalTimelinePurge)
}
if (this.debouncedIntervalTimelinePurge) {
clearInterval(this.debouncedIntervalTimelinePurge)
}
delete app.ctx
}
delete app.ctx
}
render() {
if (this.state.connectionEnd) {
return <div className="liveChat">
<antd.Result
status="error"
title="Connection error"
subTitle="Cannot connect to the server"
/>
</div>
}
render() {
if (this.state.connectionEnd) {
return (
<div className="liveChat">
<antd.Result
status="error"
title="Connection error"
subTitle="Cannot connect to the server"
/>
</div>
)
}
if (this.state.connecting) {
return <div className="liveChat">
<antd.Skeleton active />
</div>
}
if (this.state.connecting) {
return (
<div className="liveChat">
<antd.Skeleton active />
</div>
)
}
if (this.props.floatingMode) {
return <div className="liveChat floating">
<TransitionGroup
ref={this.timelineRef}
className="liveChat_timeline"
id="liveChat_timeline"
>
{
this.state.temporalTimeline.map((line, index) => {
return <CSSTransition
key={index}
timeout={300}
classNames={{
enterActive: "transverse-enter",
exitActive: "transverse-out"
}}
>
<Line {...this.state.timeline[line.messageKey]} />
</CSSTransition>
})
}
</TransitionGroup>
</div>
}
if (this.props.floatingMode) {
return (
<div className="liveChat floating">
<TransitionGroup
ref={this.timelineRef}
className="liveChat_timeline"
id="liveChat_timeline"
>
{this.state.temporalTimeline.map((line, index) => {
return (
<CSSTransition
key={index}
timeout={300}
classNames={{
enterActive: "transverse-enter",
exitActive: "transverse-out",
}}
>
<Line
{...this.state.timeline[
line.messageKey
]}
/>
</CSSTransition>
)
})}
</TransitionGroup>
</div>
)
}
if (this.state.noAuthed) {
return <div className="liveChat empty">
<antd.Empty description="You must be logged in to use this feature" />
</div>
}
if (this.state.noAuthed) {
return (
<div className="liveChat empty">
<antd.Empty description="You must be logged in to use this feature" />
</div>
)
}
return <div
className={classnames(
"liveChat",
{
["empty"]: this.state.timeline.length === 0,
["compact"]: this.props.compact
}
)}
>
{
!this.props.compact && this.state.timeline.length === 0 && <antd.Empty description="Welcome to the room" />
}
return (
<div
className={classnames("liveChat", {
["empty"]: this.state.timeline.length === 0,
["compact"]: this.props.compact,
})}
>
{!this.props.compact && this.state.timeline.length === 0 && (
<antd.Empty description="Welcome to the room" />
)}
{
this.props.compact && this.state.timeline.length === 0 && <p>
Welcome to the room
</p>
}
{this.props.compact && this.state.timeline.length === 0 && (
<p>Welcome to the room</p>
)}
{
this.state.timeline.length !== 0 && <div
className="liveChat_timeline"
ref={this.timelineRef}
id="liveChat_timeline"
>
{
this.state.timeline.map((line, index) => {
return <Line key={index} {...line} />
})
}
</div>
}
{this.state.timeline.length !== 0 && (
<div
className="liveChat_timeline"
ref={this.timelineRef}
id="liveChat_timeline"
>
{this.state.timeline.map((line, index) => {
return <Line key={index} {...line} />
})}
</div>
)}
<div className="liveChat_textInput">
<antd.Input.TextArea
placeholder="Type your message here"
autoSize={{ minRows: 1, maxRows: 3 }}
value={this.state.writtedMessage}
onChange={this.handleInputChange}
onPressEnter={this.handleOnEnter}
maxLength={this.state.roomInfo?.limitations?.maxMessageLength ?? 100}
showCount
/>
</div>
</div>
}
<div className="liveChat_textInput">
<antd.Input.TextArea
placeholder="Type your message here"
autoSize={{ minRows: 1, maxRows: 3 }}
value={this.state.writtedMessage}
onChange={this.handleInputChange}
onPressEnter={this.handleOnEnter}
maxLength={
this.state.roomInfo?.limitations
?.maxMessageLength ?? 100
}
showCount
/>
</div>
</div>
)
}
}

View File

@ -1,153 +1,154 @@
.liveChat {
position: relative;
position: relative;
display: flex;
flex-direction: column;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
width: 100%;
height: 100%;
overflow: hidden;
overflow: hidden;
transition: all 250ms ease-in-out;
transition: all 250ms ease-in-out;
&.empty {
justify-content: center;
align-items: center;
&.empty {
justify-content: center;
align-items: center;
&.compact {
height: 5vh !important;
}
}
&.compact {
height: 5vh !important;
}
}
&.compact {
height: 15vh;
&.compact {
height: 15vh;
justify-content: flex-end;
justify-content: flex-end;
.liveChat_timeline {
position: relative;
.liveChat_timeline {
position: relative;
display: flex;
flex-direction: column;
display: flex;
flex-direction: column;
padding: 0;
margin: 0;
padding: 0;
margin: 0;
margin-bottom: 10px;
gap: 5px;
gap: 5px;
.textRoom_line {
padding: 0;
margin: 0;
.textRoom_line {
padding: 0;
margin: 0;
h4 {
font-size: 0.8rem;
}
}
}
h4 {
font-size: 0.8rem;
}
}
}
.liveChat_textInput {
position: relative;
.liveChat_textInput {
position: relative;
bottom: 0;
left: 0;
bottom: 0;
left: 0;
margin-bottom: 0;
}
}
margin-bottom: 0;
}
}
&.floating {
.textRoom_line {
display: relative;
&.floating {
.textRoom_line {
display: relative;
background-color: rgba(var(--layoutBackgroundColor), 0.7);
backdrop-filter: blur(20px);
}
background-color: rgba(var(--layoutBackgroundColor), 0.7);
backdrop-filter: blur(20px);
}
.liveChat_timeline {
display: flex;
.liveChat_timeline {
display: flex;
flex-direction: column;
padding-top: 0;
flex-direction: column;
padding-top: 0;
overflow-x: hidden;
overflow-y: hidden;
overflow-x: hidden;
overflow-y: hidden;
//justify-content: flex-end;
//justify-content: flex-end;
margin-bottom: 0;
margin-bottom: 0;
transition: all 250ms ease-in-out;
}
}
transition: all 250ms ease-in-out;
}
}
.liveChat_timeline {
position: relative;
.liveChat_timeline {
position: relative;
height: 100%;
display: flex;
flex-direction: column;
overflow-y: scroll;
gap: 10px;
margin-bottom: 70px;
}
height: 100%;
overflow-y: scroll;
.liveChat_textInput {
position: absolute;
bottom: 0;
left: 0;
margin-bottom: 70px;
}
margin-bottom: 20px;
.liveChat_textInput {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: fit-content;
margin-bottom: 20px;
color: var(--text-color);
width: 100%;
height: fit-content;
.ant-input-textarea-show-count::after {
color: var(--text-color);
}
}
color: var(--text-color);
.ant-input-textarea-show-count::after {
color: var(--text-color);
}
}
}
.textRoom_line {
display: flex;
flex-direction: column;
display: flex;
flex-direction: column;
padding: 5px 10px;
margin-bottom: 10px;
padding: 5px 7px;
border-radius: 12px;
border-radius: 12px;
background-color: rgba(var(--bg_color_1), 0.7);
background-color: var(--background-color-accent);
h1,
h2,
h3,
h4,
span {
margin: 0;
user-select: text;
}
h1,
h2,
h3,
h4,
span {
margin: 0;
user-select: text;
}
.textRoom_line_user {
font-weight: bold;
font-size: 0.9rem;
.textRoom_line_user {
font-weight: bold;
font-size: 1rem;
color: var(--background-color-contrast);
color: var(--text-color);
overflow: hidden;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
text-overflow: ellipsis;
white-space: nowrap;
}
.textRoom_line_content {
font-size: 0.8rem;
color: var(--text-color);
.textRoom_line_content {
font-size: 0.8rem;
color: var(--text-color);
padding: 0 10px;
padding: 0 10px;
word-break: break-all;
white-space: pre-wrap;
}
word-break: break-all;
white-space: pre-wrap;
}
}