Skip to content

Commit

Permalink
Merge pull request #366 from reorproject/cleanup-absolute-path-stuff
Browse files Browse the repository at this point in the history
Cleanup absolute path stuff
  • Loading branch information
joseplayero authored Aug 20, 2024
2 parents a9b09b8 + 50b559c commit 3e7b116
Show file tree
Hide file tree
Showing 12 changed files with 95 additions and 147 deletions.
1 change: 1 addition & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
echo "\nRunning some lint checks on your (hopefully) beautiful code 😅\n"
npm run lint:fix && npm run type-check
4 changes: 2 additions & 2 deletions electron/main/path/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ function addExtensionToFilenameIfNoExtensionPresent(
acceptableExtensions: string[],
defaultExtension: string,
): string {
const extension = path.extname(filename).slice(1).toLowerCase()

const extension = path.extname(filename).toLowerCase()
if (acceptableExtensions.includes(extension)) {
return filename
}

return `${filename}${defaultExtension}`
}

Expand Down
9 changes: 3 additions & 6 deletions src/components/Common/TitleBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ interface TitleBarProps {
toggleSimilarFiles: () => void
history: string[]
setHistory: (string: string[]) => void
openAbsolutePath: (path: string) => void
openFileLayout: () => void
openFileAndOpenEditor: (path: string) => void
}

const TitleBar: React.FC<TitleBarProps> = ({
Expand All @@ -24,8 +23,7 @@ const TitleBar: React.FC<TitleBarProps> = ({
toggleSimilarFiles,
history,
setHistory,
openAbsolutePath,
openFileLayout,
openFileAndOpenEditor,
}) => {
const [platform, setPlatform] = useState('')

Expand Down Expand Up @@ -56,8 +54,7 @@ const TitleBar: React.FC<TitleBarProps> = ({
<DraggableTabs
currentTab={currentTab || ''}
openTabContent={openTabContent}
openAbsolutePath={openAbsolutePath}
openFileLayout={openFileLayout}
openFileAndOpenEditor={openFileAndOpenEditor}
/>
</ModalProvider>
</div>
Expand Down
8 changes: 3 additions & 5 deletions src/components/EmptyPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import NewNoteComponent from './File/NewNote'
import NewDirectoryComponent from './File/NewDirectory'

interface EmptyPageProps {
openAbsolutePath: (filePath: string, optionalContentToWriteOnCreate?: string) => Promise<void>
openFileLayout: () => void
openFileAndOpenEditor: (filePath: string, optionalContentToWriteOnCreate?: string) => Promise<void>
}

const EmptyPage: React.FC<EmptyPageProps> = ({ openAbsolutePath, openFileLayout }) => {
const EmptyPage: React.FC<EmptyPageProps> = ({ openFileAndOpenEditor }) => {
const { isNewNoteModalOpen, setIsNewNoteModalOpen, isNewDirectoryModalOpen, setIsNewDirectoryModalOpen } =
useModalOpeners()

Expand Down Expand Up @@ -39,8 +38,7 @@ const EmptyPage: React.FC<EmptyPageProps> = ({ openAbsolutePath, openFileLayout
<NewNoteComponent
isOpen={isNewNoteModalOpen}
onClose={() => setIsNewNoteModalOpen(false)}
openAbsolutePath={openAbsolutePath}
openFileLayout={openFileLayout}
openFileAndOpenEditor={openFileAndOpenEditor}
currentOpenFilePath=""
/>
<NewDirectoryComponent
Expand Down
13 changes: 5 additions & 8 deletions src/components/File/NewNote.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,15 @@ import { getInvalidCharacterInFilePath } from '@/utils/strings'
interface NewNoteComponentProps {
isOpen: boolean
onClose: () => void
openAbsolutePath: (path: string) => void
openFileAndOpenEditor: (path: string) => void
currentOpenFilePath: string | null
openFileLayout: () => void
}

const NewNoteComponent: React.FC<NewNoteComponentProps> = ({
isOpen,
onClose,
openAbsolutePath,
openFileAndOpenEditor,
currentOpenFilePath,
openFileLayout,
}) => {
const [fileName, setFileName] = useState<string>('')
const [errorMessage, setErrorMessage] = useState<string | null>(null)
Expand All @@ -46,16 +44,15 @@ const NewNoteComponent: React.FC<NewNoteComponentProps> = ({
}

const sendNewNoteMsg = async () => {
if (!fileName || errorMessage || currentOpenFilePath === null) {
if (!fileName || errorMessage) {
return
}
let finalPath = fileName
if (currentOpenFilePath !== '') {
if (currentOpenFilePath !== '' && currentOpenFilePath !== null) {
const directoryName = await window.path.dirname(currentOpenFilePath)
finalPath = await window.path.join(directoryName, fileName)
}
openFileLayout()
openAbsolutePath(finalPath)
openFileAndOpenEditor(finalPath)
posthog.capture('created_new_note_from_new_note_modal')
onClose()
}
Expand Down
87 changes: 35 additions & 52 deletions src/components/File/hooks/use-file-by-filepath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,69 +71,53 @@ const useFileByFilepath = () => {
3. when the file is deleted
*/

const openFileByPath = async (newFilePath: string) => {
setCurrentlyChangingFilePath(true)
await writeEditorContentToDisk(editor, currentlyOpenedFilePath)
if (currentlyOpenedFilePath && needToIndexEditorContent) {
window.fileSystem.indexFileInDatabase(currentlyOpenedFilePath)
setNeedToIndexEditorContent(false)
}
const newFileContent = (await window.fileSystem.readFile(newFilePath)) ?? ''
editor?.commands.setContent(newFileContent)
setCurrentlyOpenedFilePath(newFilePath)
setCurrentlyChangingFilePath(false)
}

const openRelativePath = async (relativePath: string, optionalContentToWriteOnCreate?: string): Promise<void> => {
const invalidChars = await getInvalidCharacterInFilePath(relativePath)
// This function handles the creation of a file if it doesn't exist
const createFileIfNotExists = async (filePath: string, optionalContent?: string): Promise<string> => {
const invalidChars = await getInvalidCharacterInFilePath(filePath)
if (invalidChars) {
toast.error(`Could not create note ${relativePath}. Character ${invalidChars} cannot be included in note name.`)
throw new Error(
`Could not create note ${relativePath}. Character ${invalidChars} cannot be included in note name.`,
)
const errorMessage = `Could not create note ${filePath}. Character ${invalidChars} cannot be included in note name.`
toast.error(errorMessage)
throw new Error(errorMessage)
}
const relativePathWithExtension = await window.path.addExtensionIfNoExtensionPresent(relativePath)
const absolutePath = await window.path.join(
await window.electronStore.getVaultDirectoryForWindow(),
relativePathWithExtension,
)
const filePathWithExtension = await window.path.addExtensionIfNoExtensionPresent(filePath)
const isAbsolutePath = await window.path.isAbsolute(filePathWithExtension)
const absolutePath = isAbsolutePath
? filePathWithExtension
: await window.path.join(await window.electronStore.getVaultDirectoryForWindow(), filePathWithExtension)

const fileExists = await window.fileSystem.checkFileExists(absolutePath)
if (!fileExists) {
const basename = await window.path.basename(absolutePath)
const content = optionalContentToWriteOnCreate || `## ${removeFileExtension(basename)}\n`
const content = optionalContent || `## ${removeFileExtension(basename)}\n`
await window.fileSystem.createFile(absolutePath, content)
setNeedToIndexEditorContent(true)
}
openFileByPath(absolutePath)

return absolutePath
}

const openAbsolutePath = async (filePath: string, optionalContentToWriteOnCreate?: string): Promise<void> => {
const invalidChars = await getInvalidCharacterInFilePath(filePath)
if (invalidChars) {
toast.error(`Could not create note ${filePath}. Character ${invalidChars} cannot be included in note name.`)
throw new Error(`Could not create note ${filePath}. Character ${filePath} cannot be included in note name.`)
}
const filePathWithExtension = await window.path.addExtensionIfNoExtensionPresent(filePath)
let absolutePath = filePathWithExtension
// If we create a newNote on an empty page (no file open).
if (!(await window.path.isAbsolute(filePath))) {
absolutePath = await window.path.join(
await window.electronStore.getVaultDirectoryForWindow(),
filePathWithExtension,
)
}
const fileExists = await window.fileSystem.checkFileExists(absolutePath)
if (!fileExists) {
const basename = await window.path.basename(absolutePath)
const content = optionalContentToWriteOnCreate || `## ${removeFileExtension(basename)}\n`
await window.fileSystem.createFile(absolutePath, content)
setNeedToIndexEditorContent(true)
// This function handles the actual loading of a file into the editor
const loadFileIntoEditor = async (filePath: string) => {
setCurrentlyChangingFilePath(true)
await writeEditorContentToDisk(editor, currentlyOpenedFilePath)
if (currentlyOpenedFilePath && needToIndexEditorContent) {
window.fileSystem.indexFileInDatabase(currentlyOpenedFilePath)
setNeedToIndexEditorContent(false)
}
openFileByPath(absolutePath)
const fileContent = (await window.fileSystem.readFile(filePath)) ?? ''
editor?.commands.setContent(fileContent)
setCurrentlyOpenedFilePath(filePath)
setCurrentlyChangingFilePath(false)
}

// This is the main function that combines file creation (if necessary) and loading into the editor
const openOrCreateFile = async (filePath: string, optionalContentToWriteOnCreate?: string): Promise<void> => {
const absolutePath = await createFileIfNotExists(filePath, optionalContentToWriteOnCreate)
await loadFileIntoEditor(absolutePath)
}

const openRelativePathRef = useRef<(newFilePath: string) => Promise<void>>()
openRelativePathRef.current = openRelativePath
// openRelativePathRef.current = openOrCreateFile

const handleSuggestionsStateWithEventCapture = (suggState: SuggestionsState | null): void => {
setSuggestionsState(suggState)
Expand Down Expand Up @@ -269,7 +253,7 @@ const useFileByFilepath = () => {

if (!hasOpened) {
await window.electronStore.setHasUserOpenedAppBefore()
openRelativePath('Welcome to Reor', welcomeNote)
openOrCreateFile('Welcome to Reor', welcomeNote)
}
}

Expand Down Expand Up @@ -329,8 +313,7 @@ const useFileByFilepath = () => {
editor,
navigationHistory,
setNavigationHistory,
openFileByPath,
openAbsolutePath,
openOrCreateFile,
suggestionsState,
spellCheckEnabled,
highlightData,
Expand Down
64 changes: 26 additions & 38 deletions src/components/MainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ const MainPageComponent: React.FC = () => {
const [showSimilarFiles, setShowSimilarFiles] = useState(true)
const [sidebarShowing, setSidebarShowing] = useState<SidebarAbleToShow>('files')
const [currentTab, setCurrentTab] = useState<string>('')
const [vaultDirectory, setVaultDirectory] = useState<string>('')
const [chatFilters, setChatFilters] = useState<ChatFilters>({
files: [],
numberOfChunksToFetch: 15,
minDate: new Date(0),
maxDate: new Date(),
})
const [sidebarWidth, setSidebarWidth] = useState<number>(40)

const filePathRef = React.useRef<string>('')
const chatIDRef = React.useRef<string>('')
Expand All @@ -34,8 +42,7 @@ const MainPageComponent: React.FC = () => {
filePath,
setFilePath,
editor,
openFileByPath,
openAbsolutePath,
openOrCreateFile,
saveCurrentlyOpenedFile,
suggestionsState,
highlightData,
Expand Down Expand Up @@ -72,56 +79,39 @@ const MainPageComponent: React.FC = () => {
setShowSimilarFiles(!showSimilarFiles)
}

const openFileLayout = () => {
setShowChatbot(false)
setSidebarShowing('files')
const getChatIdFromPath = (path: string) => {
if (chatHistoriesMetadata.length === 0) return UNINITIALIZED_STATE
const metadata = chatHistoriesMetadata.find((chat) => chat.displayName === path)
if (metadata) return metadata.id
return ''
}

const openChatLayout = () => {
const openChatSidebarAndChat = (chatHistory: ChatHistory | undefined) => {
setShowChatbot(true)
setSidebarShowing('chats')
}

const openFileAndOpenEditor = async (path: string) => {
openFileLayout()
openFileByPath(path)
}

const openChatAndOpenChat = (chatHistory: ChatHistory | undefined) => {
openChatLayout()
setCurrentChatHistory(chatHistory)
}

const getChatIdFromPath = (path: string) => {
if (chatHistoriesMetadata.length === 0) return UNINITIALIZED_STATE
const metadata = chatHistoriesMetadata.find((chat) => chat.displayName === path)
if (metadata) return metadata.id
return ''
const openFileAndOpenEditor = async (path: string) => {
setShowChatbot(false)
setSidebarShowing('files')
openOrCreateFile(path)
}

const openTabContent = async (path: string) => {
// generically opens a chat or a file
if (!path) return
const chatID = getChatIdFromPath(path)
if (chatID) {
if (chatID === UNINITIALIZED_STATE) return
const chat = await window.electronStore.getChatHistory(chatID)
openChatAndOpenChat(chat)
openChatSidebarAndChat(chat)
} else {
openFileAndOpenEditor(path)
}
setCurrentTab(path)
}

const [vaultDirectory, setVaultDirectory] = useState<string>('')
const [chatFilters, setChatFilters] = useState<ChatFilters>({
files: [],
numberOfChunksToFetch: 15,
minDate: new Date(0),
maxDate: new Date(),
})

const [sidebarWidth, setSidebarWidth] = useState<number>(40)

// find all available files
useEffect(() => {
const updateWidth = async () => {
Expand Down Expand Up @@ -186,8 +176,7 @@ const MainPageComponent: React.FC = () => {
openTabContent={openTabContent}
similarFilesOpen={showSimilarFiles} // This might need to be managed differently now
toggleSimilarFiles={toggleSimilarFiles} // This might need to be managed differently now
openAbsolutePath={openAbsolutePath}
openFileLayout={openFileLayout}
openFileAndOpenEditor={openFileAndOpenEditor}
/>
</TabProvider>

Expand All @@ -198,8 +187,7 @@ const MainPageComponent: React.FC = () => {
>
<ModalProvider>
<IconsSidebar
openAbsolutePath={openAbsolutePath}
openFileLayout={openFileLayout}
openFileAndOpenEditor={openFileAndOpenEditor}
sidebarShowing={sidebarShowing}
makeSidebarShow={setSidebarShowing}
currentFilePath={filePath}
Expand All @@ -223,7 +211,7 @@ const MainPageComponent: React.FC = () => {
setFileDirToBeRenamed={setFileDirToBeRenamed}
currentChatHistory={currentChatHistory}
chatHistoriesMetadata={chatHistoriesMetadata}
setCurrentChatHistory={openChatAndOpenChat}
setCurrentChatHistory={openChatSidebarAndChat}
setChatFilters={setChatFilters}
setShowChatbot={setShowChatbot}
/>
Expand Down Expand Up @@ -251,7 +239,7 @@ const MainPageComponent: React.FC = () => {
<SimilarFilesSidebarComponent
filePath={filePath}
highlightData={highlightData}
openFileByPath={openFileByPath}
openFileAndOpenEditor={openFileAndOpenEditor}
saveCurrentlyOpenedFile={saveCurrentlyOpenedFile}
/>
</div>
Expand All @@ -261,7 +249,7 @@ const MainPageComponent: React.FC = () => {
!showChatbot && (
<div className="relative flex size-full overflow-hidden">
<ModalProvider>
<EmptyPage openAbsolutePath={openAbsolutePath} openFileLayout={openFileLayout} />
<EmptyPage openFileAndOpenEditor={openFileAndOpenEditor} />
</ModalProvider>
</div>
)
Expand Down
17 changes: 6 additions & 11 deletions src/components/Providers/TabProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,19 +124,14 @@ export const TabProvider: React.FC<TabProviderProps> = ({

const nextTabs = prevTabs.filter((_, idx) => idx !== findIdx)

let fileTabCount = 0
let chatTabCount = 0
nextTabs.forEach((tab) => {
if (getChatIdFromPath(tab.path)) {
chatTabCount += 1
} else {
fileTabCount += 1
}
})
if (!fileTabCount) {
const hasFileTabs = nextTabs.some((tab) => !getChatIdFromPath(tab.path))
const hasChatTabs = nextTabs.some((tab) => getChatIdFromPath(tab.path))

if (!hasFileTabs) {
setFilePath('')
}
if (!chatTabCount) {

if (!hasChatTabs) {
setCurrentChatHistory(undefined)
}

Expand Down
Loading

0 comments on commit 3e7b116

Please sign in to comment.