editor: fix replacing file when open in editor

When we import/replace a file that is open in an editor, instead of
modifying the file in storage, we need to modify the file in the editor.
This allows the modification to be pushed on the undo stack so that
the user can undo the change in case it wrote over any of their recent
changes.

Issue: https://github.com/pybricks/support/issues/975
This commit is contained in:
David Lechner
2023-05-18 17:06:31 -05:00
committed by David Lechner
parent 3fc275eaed
commit 7351dfb95c
4 changed files with 69 additions and 11 deletions
+19 -9
View File
@@ -20,6 +20,7 @@ import {
editorDidActivateFile,
editorDidCloseFile,
editorDidFailToActivateFile,
editorReplaceFile,
} from '../editor/actions';
import { EditorError } from '../editor/error';
import { getPybricksMicroPythonFileTemplate } from '../editor/pybricksMicroPython';
@@ -243,17 +244,26 @@ function* importPythonFile(
fileName = accepted.newName;
}
yield* put(fileStorageWriteFile(fileName, sourceFileContents));
const existingFileInfo = existingFiles.find((x) => x.path === fileName);
const openFileUuids = yield* select((s: RootState) => s.editor.openFileUuids);
const { didFailToWrite } = yield* race({
didWrite: take(fileStorageDidWriteFile.when((a) => a.path === fileName)),
didFailToWrite: take(
fileStorageDidFailToWriteFile.when((a) => a.path === fileName),
),
});
// If the file is open, modify contents in the editor so preserve undo
// history, otherwise write directly to storage.
if (existingFileInfo && openFileUuids.includes(existingFileInfo.uuid)) {
yield* put(editorReplaceFile(existingFileInfo.uuid, sourceFileContents));
} else {
yield* put(fileStorageWriteFile(fileName, sourceFileContents));
if (didFailToWrite) {
throw didFailToWrite.error;
const { didFailToWrite } = yield* race({
didWrite: take(fileStorageDidWriteFile.when((a) => a.path === fileName)),
didFailToWrite: take(
fileStorageDidFailToWriteFile.when((a) => a.path === fileName),
),
});
if (didFailToWrite) {
throw didFailToWrite.error;
}
}
}