diff --git a/services/web/frontend/js/features/history/context/hooks/use-restore-deleted-file.ts b/services/web/frontend/js/features/history/context/hooks/use-restore-deleted-file.ts index 4998f4d8b1..79584b79b5 100644 --- a/services/web/frontend/js/features/history/context/hooks/use-restore-deleted-file.ts +++ b/services/web/frontend/js/features/history/context/hooks/use-restore-deleted-file.ts @@ -4,6 +4,7 @@ import { useLayoutContext } from '../../../../shared/context/layout-context' import useAsync from '../../../../shared/hooks/use-async' import { restoreFile } from '../../services/api' import { isFileRemoved } from '../../utils/file-diff' +import { waitFor } from '../../utils/wait-for' import { useHistoryContext } from '../history-context' import type { HistoryContextValue } from '../types/history-context-value' @@ -22,10 +23,13 @@ export function useRestoreDeletedFile() { await runAsync( restoreFile(projectId, selectedFile) - .then(data => { + .then(async data => { const { id, type } = data - const entity = ide.fileTreeManager.findEntityById(id) + const entity = await waitFor( + () => ide.fileTreeManager.findEntityById(id), + 3000 + ) if (type === 'doc') { ide.editorManager.openDoc(entity) diff --git a/services/web/frontend/js/features/history/utils/wait-for.ts b/services/web/frontend/js/features/history/utils/wait-for.ts new file mode 100644 index 0000000000..48365c9608 --- /dev/null +++ b/services/web/frontend/js/features/history/utils/wait-for.ts @@ -0,0 +1,33 @@ +export function waitFor( + testFunction: () => T, + timeout: number, + pollInterval = 500 +): Promise { + const iterationLimit = Math.floor(timeout / pollInterval) + let iterations = 0 + + return new Promise((resolve, reject) => { + const tryIteration = () => { + if (iterations > iterationLimit) { + reject( + console.error( + `waiting too long, ${JSON.stringify({ timeout, pollInterval })}` + ) + ) + return + } + + iterations += 1 + const result = testFunction() + + if (result) { + resolve(result) + return + } + + setTimeout(tryIteration, pollInterval) + } + + tryIteration() + }) +}