From ba02940a30422682223d4cb2f5601590de4fb627 Mon Sep 17 00:00:00 2001 From: blurfx Date: Sat, 21 Oct 2023 01:09:44 +0900 Subject: [PATCH] fix: prevent fileinfo being overwritten with null when selecting a file --- utils/exampleFileUtils.ts | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/utils/exampleFileUtils.ts b/utils/exampleFileUtils.ts index 3b1c9fb..068fd80 100644 --- a/utils/exampleFileUtils.ts +++ b/utils/exampleFileUtils.ts @@ -90,18 +90,27 @@ export const setFirstFileOpen = (directoryInfo: DirectoryInfo): [DirectoryInfo, return [directoryInfoResult, openedFileInfo]; }; -export const setFileOpen = (directoryInfo: DirectoryInfo, targetFile: string): [DirectoryInfo, FileInfo | null] => { - const cloneDirectoryInfo = cloneDeep(directoryInfo); - let _openedFileInfo: FileInfo | null = null; - cloneDirectoryInfo.children.forEach((child, i) => { +export const setFileOpen = (directoryInfo: DirectoryInfo, targetFilePath: string): [DirectoryInfo, FileInfo | null] => { + const clonedDirectoryInfo = cloneDeep(directoryInfo); + const openedFileInfo = findOpenedFileInfo(clonedDirectoryInfo, targetFilePath); + return [clonedDirectoryInfo, openedFileInfo]; +}; + +const findOpenedFileInfo = (directoryInfo: DirectoryInfo, targetFilePath: string): FileInfo | null => { + let opendFileInfo: FileInfo | null = null; + for (const child of directoryInfo.children) { + if (opendFileInfo != null) { + break; + } if (child.isFile) { - child.isOpen = child.path === targetFile; - _openedFileInfo = child.path === targetFile ? child : _openedFileInfo; + child.isOpen = child.path === targetFilePath; + if (child.isOpen) { + opendFileInfo = child; + break; + } } else { - const [childInfo, openedFileInfo] = setFileOpen(child, targetFile); - cloneDirectoryInfo.children[i] = childInfo; - _openedFileInfo = openedFileInfo; + opendFileInfo = opendFileInfo ?? findOpenedFileInfo(child, targetFilePath); } - }); - return [cloneDirectoryInfo, _openedFileInfo]; -}; + } + return opendFileInfo; +}