I have a next js project and in that i have this fn that i run on, onKeyDownCapture
NOTE- the Fn works fine when its being executed on the main thread in the same file but when i move it to the web worker that is when the problem arises.
the worker and the main thread are successfully connected and send messages to and fro, have verified this
Now as we know the communication of the main thread with the worker is asynchronous, so i guess that might be causing the problem, that even though the worker returns true when the computation is done because its async we’re kinda not being able to see its effect on the main thread
THE FN normally on the main thread (just for simplified context)
const handleBackspace1 = useCallback(
throttle((event, editor) => {
if (event.key === 'Backspace') {
const cursorPosition = editor.getTextCursorPosition();
if (
(cursorPosition.block.type === "paragraph" && cursorPosition.block.content.length === 0) &&
customComponentsRef.current.includes(cursorPosition?.prevBlock?.type)
) {
editor.setTextCursorPosition(cursorPosition.prevBlock, "end");
event.preventDefault();
event.stopPropagation();
return false;
} else {
return true;
}
}
}, 150),
[]
);
the actual web worker implementation part ->
useEffect(() => {
if (router.isReady) {
workerRef.current = new Worker(new URL('../../../../Workers/BackspaceWorkerForEditor.js', import.meta.url));
return () => {
workerRef.current.terminate();
};
}
}, []);
FN WITH THE WEB WORKER
const handleBackspace = (event) => {
console.log('1');
if (event.key === 'Backspace' && typeof window !== 'undefined' && router.isReady) {
console.log('2');
const cursorPosition = editor.getTextCursorPosition();
if (workerRef.current) {
workerRef.current.postMessage({
cursorPosition,
customComponents: customComponentsRef.current,
});
workerRef.current.onmessage = function (e) {
const { shouldPreventDefault, prevBlock } = e.data;
console.log(shouldPreventDefault);
if (shouldPreventDefault) {
console.log('prevent default', shouldPreventDefault);
editor.setTextCursorPosition(prevBlock, "end");
event.preventDefault();
}
};
}
}
};
the woker script
function handleMessage(event) {
const { cursorPosition, customComponents } = event.data;
if (
cursorPosition.block.type === "paragraph" &&
cursorPosition.block.content.length === 0 &&
customComponents.includes(cursorPosition.prevBlock?.type)
) {
postMessage({ shouldPreventDefault: true, prevBlock: cursorPosition.prevBlock });
} else {
postMessage({ shouldPreventDefault: false });
}
}
self.addEventListener('message', handleMessage);
sample logs showing that yes the worker and the main thread is connected and inspite of the worker returning true we’re not able to prevent default/stop propogation
2
Editor.jsx:189 true
Editor.jsx:192 prevent default true
Can somebody please help me with it