From 6cb2702e6b1e6b03e7d003c468518d3644d96859 Mon Sep 17 00:00:00 2001 From: Anthony LC Date: Fri, 20 Dec 2024 14:37:21 +0100 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F(frontend)=20update=20already?= =?UTF-8?q?=20existing=20tasks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a task was already existing, we were not updating it. This commit fixes that. --- .../impress/src/stores/useBroadcastStore.tsx | 50 ++++++++++++++++--- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/src/frontend/apps/impress/src/stores/useBroadcastStore.tsx b/src/frontend/apps/impress/src/stores/useBroadcastStore.tsx index a6230ea6..7e8812f7 100644 --- a/src/frontend/apps/impress/src/stores/useBroadcastStore.tsx +++ b/src/frontend/apps/impress/src/stores/useBroadcastStore.tsx @@ -8,7 +8,20 @@ interface BroadcastState { getBroadcastProvider: () => HocuspocusProvider | undefined; provider?: HocuspocusProvider; setBroadcastProvider: (provider: HocuspocusProvider) => void; - tasks: { [taskLabel: string]: Y.Array }; + setTask: ( + taskLabel: string, + task: Y.Array, + action: () => void, + ) => void; + tasks: { + [taskLabel: string]: { + task: Y.Array; + observer: ( + event: Y.YArrayEvent, + transaction: Y.Transaction, + ) => void; + }; + }; } export const useBroadcastStore = create((set, get) => ({ @@ -25,26 +38,47 @@ export const useBroadcastStore = create((set, get) => ({ return provider; }, addTask: (taskLabel, action) => { - const taskExistAlready = get().tasks[taskLabel]; const provider = get().getBroadcastProvider(); - if (taskExistAlready || !provider) { + if (!provider) { + return; + } + + const existingTask = get().tasks[taskLabel]; + if (existingTask) { + existingTask.task.unobserve(existingTask.observer); + get().setTask(taskLabel, existingTask.task, action); return; } const task = provider.document.getArray(taskLabel); - task.observe(() => { - action(); - }); + get().setTask(taskLabel, task, action); + }, + setTask: (taskLabel: string, task: Y.Array, action: () => void) => { + let isInitializing = true; + const observer = () => { + if (!isInitializing) { + action(); + } + }; + + task.observe(observer); + + setTimeout(() => { + isInitializing = false; + }, 1000); set((state) => ({ tasks: { ...state.tasks, - [taskLabel]: task, + [taskLabel]: { + task, + observer, + }, }, })); }, broadcast: (taskLabel) => { - const task = get().tasks[taskLabel]; + const { task } = get().tasks[taskLabel]; if (!task) { console.warn(`Task ${taskLabel} is not defined`); return;