Update web worker for chat

This commit is contained in:
Bill 2022-11-13 21:49:52 -05:00
parent 1a8bf75a0d
commit 0905f88d60
8 changed files with 76 additions and 156 deletions

View File

@ -5,8 +5,6 @@ import { Base, TransitionAnimation, TransitionAnimationTypes } from './common';
import { LoadingView } from './components/loading/LoadingView'; import { LoadingView } from './components/loading/LoadingView';
import { MainView } from './components/main/MainView'; import { MainView } from './components/main/MainView';
import { useConfigurationEvent, useLocalizationEvent, useMainEvent, useRoomEngineEvent } from './hooks'; import { useConfigurationEvent, useLocalizationEvent, useMainEvent, useRoomEngineEvent } from './hooks';
import IntervalWebWorker from './workers/IntervalWebWorker';
import { WorkerBuilder } from './workers/WorkerBuilder';
NitroVersion.UI_VERSION = GetUIVersion(); NitroVersion.UI_VERSION = GetUIVersion();
@ -24,10 +22,6 @@ export const App: FC<{}> = props =>
if(!NitroConfig) throw new Error('NitroConfig is not defined!'); if(!NitroConfig) throw new Error('NitroConfig is not defined!');
Nitro.bootstrap(); Nitro.bootstrap();
const worker = new WorkerBuilder(IntervalWebWorker);
Nitro.instance.setWorker(worker);
} }
const handler = useCallback((event: NitroEvent) => const handler = useCallback((event: NitroEvent) =>

View File

@ -1,7 +0,0 @@
import { IWorkerEventTracker } from '@nitrots/nitro-renderer';
import { GetNitroInstance } from './GetNitroInstance';
export const AddWorkerEventTracker = (tracker: IWorkerEventTracker) =>
{
GetNitroInstance().addWorkerEventTracker(tracker);
}

View File

@ -1,7 +0,0 @@
import { IWorkerEventTracker } from '@nitrots/nitro-renderer';
import { GetNitroInstance } from './GetNitroInstance';
export const RemoveWorkerEventTracker = (tracker: IWorkerEventTracker) =>
{
GetNitroInstance().removeWorkerEventTracker(tracker);
}

View File

@ -1,6 +0,0 @@
import { GetNitroInstance } from './GetNitroInstance';
export const SendWorkerEvent = (message: { [index: string]: any }) =>
{
GetNitroInstance().sendWorkerEvent(message);
}

View File

@ -1,5 +1,4 @@
export * from './AddLinkEventTracker'; export * from './AddLinkEventTracker';
export * from './AddWorkerEventTracker';
export * from './avatar'; export * from './avatar';
export * from './camera'; export * from './camera';
export * from './core'; export * from './core';
@ -11,8 +10,6 @@ export * from './GetLocalization';
export * from './GetNitroInstance'; export * from './GetNitroInstance';
export * from './OpenUrl'; export * from './OpenUrl';
export * from './RemoveLinkEventTracker'; export * from './RemoveLinkEventTracker';
export * from './RemoveWorkerEventTracker';
export * from './room'; export * from './room';
export * from './SendMessageComposer'; export * from './SendMessageComposer';
export * from './SendWorkerEvent';
export * from './session'; export * from './session';

View File

@ -1,7 +1,9 @@
import { IWorkerEventTracker, RoomChatSettings } from '@nitrots/nitro-renderer'; import { RoomChatSettings } from '@nitrots/nitro-renderer';
import { FC, useCallback, useEffect, useRef, useState } from 'react'; import { FC, useCallback, useEffect, useRef, useState } from 'react';
import { AddWorkerEventTracker, ChatBubbleMessage, DoChatsOverlap, GetConfiguration, RemoveWorkerEventTracker, SendWorkerEvent } from '../../../../api'; import { ChatBubbleMessage, DoChatsOverlap, GetConfiguration } from '../../../../api';
import { useChatWidget } from '../../../../hooks'; import { useChatWidget } from '../../../../hooks';
import IntervalWebWorker from '../../../../workers/IntervalWebWorker';
import { WorkerBuilder } from '../../../../workers/WorkerBuilder';
import { ChatWidgetMessageView } from './ChatWidgetMessageView'; import { ChatWidgetMessageView } from './ChatWidgetMessageView';
let TIMER_TRACKER: number = 0; let TIMER_TRACKER: number = 0;
@ -9,7 +11,7 @@ let TIMER_TRACKER: number = 0;
export const ChatWidgetView: FC<{}> = props => export const ChatWidgetView: FC<{}> = props =>
{ {
const [ timerId, setTimerId ] = useState(TIMER_TRACKER++); const [ timerId, setTimerId ] = useState(TIMER_TRACKER++);
const { pendingChats = null, chatSettings = null, getScrollSpeed = 6000, moveAllChatsUp = null } = useChatWidget(); const { pendingChats = null, chatSettings = null, getScrollSpeed = 6000 } = useChatWidget();
const [ renderedChats, setRenderedChats ] = useState<ChatBubbleMessage[]>([]); const [ renderedChats, setRenderedChats ] = useState<ChatBubbleMessage[]>([]);
const elementRef = useRef<HTMLDivElement>(); const elementRef = useRef<HTMLDivElement>();
const isProcessing = useRef<boolean>(false); const isProcessing = useRef<boolean>(false);
@ -98,29 +100,6 @@ export const ChatWidgetView: FC<{}> = props =>
isProcessing.current = false; isProcessing.current = false;
}, []); }, []);
useEffect(() =>
{
const processNextChat = () =>
{
if(isProcessing.current) return;
const chat = pendingChats?.current?.shift();
if(!chat) return;
isProcessing.current = true;
setRenderedChats(prevValue => [ ...prevValue, chat ]);
}
const interval = setInterval(() => processNextChat(), 50);
return () =>
{
clearInterval(interval);
}
}, [ pendingChats ]);
useEffect(() => useEffect(() =>
{ {
const resize = (event: UIEvent = null) => const resize = (event: UIEvent = null) =>
@ -155,37 +134,69 @@ export const ChatWidgetView: FC<{}> = props =>
useEffect(() => useEffect(() =>
{ {
const workerTracker: IWorkerEventTracker = { const processNextChat = () =>
workerMessageReceived: (message: { [index: string]: any }) => {
{ if(isProcessing.current) return;
switch(message.type)
{
case 'MOVE_CHATS':
moveAllChatsUp(15);
return;
}
}
};
AddWorkerEventTracker(workerTracker); const chat = pendingChats?.current?.shift();
SendWorkerEvent({ if(!chat) return;
type: 'CREATE_INTERVAL',
time: getScrollSpeed, isProcessing.current = true;
timerId: timerId,
response: { type: 'MOVE_CHATS' } setRenderedChats(prevValue => [ ...prevValue, chat ]);
}); }
const worker = new WorkerBuilder(IntervalWebWorker);
worker.onmessage = () => processNextChat();
worker.postMessage({ action: 'START', content: 50 });
return () => return () =>
{ {
SendWorkerEvent({ worker.postMessage({ action: 'STOP' });
type: 'REMOVE_INTERVAL', }
timerId }, [ pendingChats ]);
useEffect(() =>
{
const moveAllChatsUp = (amount: number) =>
{
setRenderedChats(prevValue =>
{
prevValue.forEach(chat =>
{
if(chat.skipMovement)
{
chat.skipMovement = false;
return;
}
chat.top -= amount;
});
return prevValue;
}); });
RemoveWorkerEventTracker(workerTracker); removeHiddenChats();
} }
}, [ timerId, getScrollSpeed, moveAllChatsUp ]);
const worker = new WorkerBuilder(IntervalWebWorker);
worker.onmessage = () =>
{
moveAllChatsUp(15);
}
worker.postMessage({ action: 'START', content: getScrollSpeed });
return () =>
{
worker.postMessage({ action: 'STOP' });
}
}, [ getScrollSpeed, removeHiddenChats ]);
return ( return (
<div ref={ elementRef } className="nitro-chat-widget"> <div ref={ elementRef } className="nitro-chat-widget">

View File

@ -1,9 +1,9 @@
import { AvatarFigurePartType, AvatarScaleType, AvatarSetType, GetGuestRoomResultEvent, NitroPoint, PetFigureData, RoomChatSettings, RoomChatSettingsEvent, RoomDragEvent, RoomObjectCategory, RoomObjectType, RoomObjectVariable, RoomSessionChatEvent, RoomUserData, SystemChatStyleEnum, TextureUtils, Vector3d } from '@nitrots/nitro-renderer'; import { AvatarFigurePartType, AvatarScaleType, AvatarSetType, GetGuestRoomResultEvent, NitroPoint, PetFigureData, RoomChatSettings, RoomChatSettingsEvent, RoomDragEvent, RoomObjectCategory, RoomObjectType, RoomObjectVariable, RoomSessionChatEvent, RoomUserData, SystemChatStyleEnum, TextureUtils, Vector3d } from '@nitrots/nitro-renderer';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useEffect, useMemo, useRef, useState } from 'react';
import { ChatBubbleMessage, ChatEntryType, ChatHistoryCurrentDate, GetAvatarRenderManager, GetConfiguration, GetRoomEngine, GetRoomObjectScreenLocation, IRoomChatSettings, LocalizeText, PlaySound, RoomChatFormatter } from '../../../api'; import { ChatBubbleMessage, ChatEntryType, ChatHistoryCurrentDate, GetAvatarRenderManager, GetConfiguration, GetRoomEngine, GetRoomObjectScreenLocation, IRoomChatSettings, LocalizeText, PlaySound, RoomChatFormatter } from '../../../api';
import { useMessageEvent, useRoomEngineEvent, useRoomSessionManagerEvent } from '../../events'; import { useMessageEvent, useRoomEngineEvent, useRoomSessionManagerEvent } from '../../events';
import { useRoom } from '../useRoom'; import { useRoom } from '../useRoom';
import { useChatHistory } from './../../chat-history/useChatHistory'; import { useChatHistory } from './../../chat-history';
const avatarColorCache: Map<string, number> = new Map(); const avatarColorCache: Map<string, number> = new Map();
const avatarImageCache: Map<string, string> = new Map(); const avatarImageCache: Map<string, string> = new Map();
@ -96,46 +96,6 @@ const useChatWidgetState = () =>
return existing; return existing;
} }
const removeHiddenChats = useCallback(() =>
{
setChatMessages(prevValue =>
{
if(prevValue)
{
const newMessages = prevValue.filter(chat => ((chat.top > (-(chat.height) * 2))));
if(newMessages.length !== prevValue.length) return newMessages;
}
return prevValue;
})
}, []);
const moveAllChatsUp = (amount: number) =>
{
setChatMessages(prevValue =>
{
if(prevValue)
{
prevValue.forEach(chat =>
{
if(chat.skipMovement)
{
chat.skipMovement = false;
return;
}
chat.top -= amount;
});
}
return prevValue;
});
removeHiddenChats();
}
useRoomSessionManagerEvent<RoomSessionChatEvent>(RoomSessionChatEvent.CHAT_EVENT, event => useRoomSessionManagerEvent<RoomSessionChatEvent>(RoomSessionChatEvent.CHAT_EVENT, event =>
{ {
const roomObject = GetRoomEngine().getRoomObject(roomSession.roomId, event.objectId, RoomObjectCategory.UNIT); const roomObject = GetRoomEngine().getRoomObject(roomSession.roomId, event.objectId, RoomObjectCategory.UNIT);
@ -288,7 +248,7 @@ const useChatWidgetState = () =>
} }
}, []); }, []);
return { chatMessages, setChatMessages, chatSettings, getScrollSpeed, removeHiddenChats, moveAllChatsUp, pendingChats }; return { chatMessages, setChatMessages, chatSettings, getScrollSpeed, pendingChats };
} }
export const useChatWidget = useChatWidgetState; export const useChatWidget = useChatWidgetState;

View File

@ -1,9 +1,6 @@
export default () => export default () =>
{ {
const intervals: { let interval: ReturnType<typeof setInterval> = null;
id: number,
interval: ReturnType<typeof setInterval>
}[] = [];
// eslint-disable-next-line no-restricted-globals // eslint-disable-next-line no-restricted-globals
self.onmessage = (message: MessageEvent) => self.onmessage = (message: MessageEvent) =>
@ -12,37 +9,18 @@ export default () =>
const data: { [index: string]: any } = message.data; const data: { [index: string]: any } = message.data;
switch(data.type) switch(data.action)
{ {
case 'CREATE_INTERVAL': { case 'START':
const id = (data.timerId as number); interval = setInterval(() => postMessage(null), data.content);
const time = (data.time as number); break;
const response = (data.response as string); case 'STOP':
if(interval)
const interval = setInterval(() => postMessage(response), time);
intervals.push({ id, interval });
return;
}
case 'REMOVE_INTERVAL': {
const id = (data.timerId as number);
const i = 0;
while(i < intervals.length)
{ {
const interval = intervals[i]; clearInterval(interval);
interval = null;
if(interval.id === id)
{
clearInterval(interval.interval);
intervals.splice(i, 1);
return;
}
} }
} break;
} }
} }
} }