@@ -266,16 +266,54 @@ const useChatStore = create((set, get) => ({
266266
267267 switch ( event . detail . event ) {
268268 case "App\\Events\\ChatMessageEvent" :
269- // Add user to chatters list if they're not already in there
269+ if ( ! window . __chatMessageBatch ) {
270+ window . __chatMessageBatch = { } ;
271+ }
272+ if ( ! window . __chatMessageBatch [ chatroom . id ] ) {
273+ window . __chatMessageBatch [ chatroom . id ] = {
274+ queue : [ ] ,
275+ timer : null ,
276+ } ;
277+ }
278+ // batching setting from settings
279+ const batchingInterval = window . __chatMessageBatchInterval ?? 1000 ; // 0 = instant
270280 get ( ) . addChatter ( chatroom . id , parsedEvent ?. sender ) ;
271-
272- // Add Message to Chatroom
273- get ( ) . addMessage ( chatroom . id , {
281+ // queue batch
282+ window . __chatMessageBatch [ chatroom . id ] . queue . push ( {
274283 ...parsedEvent ,
275284 timestamp : new Date ( ) . toISOString ( ) ,
276285 } ) ;
277-
278- // Add Message to User Logs
286+ console . log (
287+ `[Batching] Added message to queue for chatroom ${ chatroom . id } . Queue length:` ,
288+ window . __chatMessageBatch [ chatroom . id ] . queue . length ,
289+ "Batching interval:" ,
290+ batchingInterval ,
291+ ) ;
292+ // flusher
293+ const flushBatch = ( ) => {
294+ const batch = window . __chatMessageBatch [ chatroom . id ] . queue ;
295+ if ( batch . length > 0 ) {
296+ console . log ( `[Batching] Flushing ${ batch . length } messages for chatroom ${ chatroom . id } ` ) ;
297+ batch . forEach ( ( msg ) => get ( ) . addMessage ( chatroom . id , msg ) ) ;
298+ window . __chatMessageBatch [ chatroom . id ] . queue = [ ] ;
299+ }
300+ } ;
301+ if ( batchingInterval === 0 ) {
302+ // If someone wants it instantly then it just basically always flushes and batches instantly
303+ console . log ( "[Batching] Instant mode, flushing immediately" ) ;
304+ flushBatch ( ) ;
305+ } else {
306+ if ( ! window . __chatMessageBatch [ chatroom . id ] . timer ) {
307+ console . log ( `[Batching] Starting timer for chatroom ${ chatroom . id } with interval ${ batchingInterval } ms` ) ;
308+ window . __chatMessageBatch [ chatroom . id ] . timer = setTimeout ( ( ) => {
309+ flushBatch ( ) ;
310+ window . __chatMessageBatch [ chatroom . id ] . timer = null ;
311+ console . log ( `[Batching] Timer ended for chatroom ${ chatroom . id } ` ) ;
312+ } , batchingInterval ) ;
313+ } else {
314+ console . log ( `[Batching] Timer already running for chatroom ${ chatroom . id } ` ) ;
315+ }
316+ }
279317 if ( parsedEvent ?. type === "reply" ) {
280318 window . app . replyLogs . add ( {
281319 chatroomId : chatroom . id ,
@@ -288,7 +326,6 @@ const useChatStore = create((set, get) => ({
288326 message : parsedEvent ,
289327 } ) ;
290328 }
291-
292329 break ;
293330 case "App\\Events\\MessageDeletedEvent" :
294331 get ( ) . handleMessageDelete ( chatroom . id , parsedEvent . message . id ) ;
0 commit comments