Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

show file preview on MentionableBadge & go to file on click #31

Merged
merged 7 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/components/chat-view/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ import {
LLMAPIKeyInvalidException,
LLMAPIKeyNotSetException,
} from '../../utils/llm/exception'
import {
getMentionableKey,
serializeMentionable,
} from '../../utils/mentionable'
import { readTFileContent } from '../../utils/obsidian'
import { PromptGenerator } from '../../utils/promptGenerator'

Expand Down Expand Up @@ -98,6 +102,16 @@ const Chat = forwardRef<ChatRef, ChatProps>((props, ref) => {
}
return newMessage
})
const [addedBlockKey, setAddedBlockKey] = useState<string | null>(
props.selectedBlock
? getMentionableKey(
serializeMentionable({
type: 'block',
...props.selectedBlock,
}),
)
: null,
)
const [chatMessages, setChatMessages] = useState<ChatMessage[]>([])
const [focusedMessageId, setFocusedMessageId] = useState<string | null>(null)
const [currentConversationId, setCurrentConversationId] =
Expand Down Expand Up @@ -404,6 +418,8 @@ const Chat = forwardRef<ChatRef, ChatProps>((props, ref) => {
...data,
}

setAddedBlockKey(getMentionableKey(serializeMentionable(mentionable)))

if (focusedMessageId === inputMessage.id) {
setInputMessage((prevInputMessage) => ({
...prevInputMessage,
Expand Down Expand Up @@ -553,6 +569,7 @@ const Chat = forwardRef<ChatRef, ChatProps>((props, ref) => {
}))
}}
autoFocus
addedBlockKey={addedBlockKey}
/>
</div>
)
Expand Down
25 changes: 2 additions & 23 deletions src/components/chat-view/MarkdownReferenceBlock.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { MarkdownView } from 'obsidian'
import { PropsWithChildren, useEffect, useMemo, useState } from 'react'

import { useApp } from '../../contexts/app-context'
import { useDarkModeContext } from '../../contexts/dark-mode-context'
import { readTFileContent } from '../../utils/obsidian'
import { openMarkdownFile, readTFileContent } from '../../utils/obsidian'

import { MemoizedSyntaxHighlighterWrapper } from './SyntaxHighlighterWrapper'

Expand Down Expand Up @@ -45,27 +44,7 @@ export default function MarkdownReferenceBlock({
}, [filename, startLine, endLine, app.vault])

const handleClick = () => {
const file = app.vault.getFileByPath(filename)
if (!file) return

const existingLeaf = app.workspace
.getLeavesOfType('markdown')
.find(
(leaf) =>
leaf.view instanceof MarkdownView &&
leaf.view.file?.path === file.path,
)

if (existingLeaf) {
app.workspace.setActiveLeaf(existingLeaf, { focus: true })
const view = existingLeaf.view as MarkdownView
view.setEphemeralState({ line: startLine })
} else {
const leaf = app.workspace.getLeaf('tab')
leaf.openFile(file, {
eState: { line: startLine },
})
}
openMarkdownFile(app, filename, startLine)
}

// TODO: Update styles
Expand Down
91 changes: 91 additions & 0 deletions src/components/chat-view/chat-input/ChatUserInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,28 @@ import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin'
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin'
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'
import { useQuery } from '@tanstack/react-query'
import { $nodesOfType, LexicalEditor, SerializedEditorState } from 'lexical'
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useRef,
useState,
} from 'react'
import {
deserializeMentionable,
serializeMentionable,
} from 'src/utils/mentionable'

import { useApp } from '../../../contexts/app-context'
import { useDarkModeContext } from '../../../contexts/dark-mode-context'
import { Mentionable, SerializedMentionable } from '../../../types/mentionable'
import { fuzzySearch } from '../../../utils/fuzzy-search'
import { getMentionableKey } from '../../../utils/mentionable'
import { openMarkdownFile, readTFileContent } from '../../../utils/obsidian'
import { MemoizedSyntaxHighlighterWrapper } from '../SyntaxHighlighterWrapper'

import MentionableBadge from './MentionableBadge'
import { ModelSelect } from './ModelSelect'
Expand Down Expand Up @@ -54,6 +59,7 @@ export type ChatUserInputProps = {
mentionables: Mentionable[]
setMentionables: (mentionables: Mentionable[]) => void
autoFocus?: boolean
addedBlockKey?: string | null
}

const ChatUserInput = forwardRef<ChatUserInputRef, ChatUserInputProps>(
Expand All @@ -66,15 +72,27 @@ const ChatUserInput = forwardRef<ChatUserInputRef, ChatUserInputProps>(
mentionables,
setMentionables,
autoFocus = false,
addedBlockKey,
},
ref,
) => {
const app = useApp()
const { isDarkMode } = useDarkModeContext()

const editorRef = useRef<LexicalEditor | null>(null)
const contentEditableRef = useRef<HTMLDivElement>(null)
const updaterRef = useRef<UpdaterPluginRef | null>(null)

const [displayedMentionableKey, setDisplayedMentionableKey] = useState<
string | null
>(addedBlockKey ?? null)

useEffect(() => {
if (addedBlockKey) {
setDisplayedMentionableKey(addedBlockKey)
}
}, [addedBlockKey])

useImperativeHandle(ref, () => ({
focus: () => {
contentEditableRef.current?.focus()
Expand Down Expand Up @@ -121,6 +139,7 @@ const ChatUserInput = forwardRef<ChatUserInputRef, ChatUserInputProps>(
return
}
setMentionables([...mentionables, mentionable])
setDisplayedMentionableKey(mentionableKey)
}

const handleMentionNodeMutation = (
Expand Down Expand Up @@ -197,6 +216,48 @@ const ChatUserInput = forwardRef<ChatUserInputRef, ChatUserInputProps>(
})
}

const { data: fileContent } = useQuery({
queryKey: [
'file',
displayedMentionableKey,
mentionables.map((m) => getMentionableKey(serializeMentionable(m))), // should be updated when mentionables change (especially on delete)
],
queryFn: async () => {
if (!displayedMentionableKey) return null

const displayedMentionable = mentionables.find(
(m) =>
getMentionableKey(serializeMentionable(m)) ===
displayedMentionableKey,
)

if (!displayedMentionable) return null

if (
displayedMentionable.type === 'file' ||
displayedMentionable.type === 'current-file'
) {
if (!displayedMentionable.file) return null
return await readTFileContent(displayedMentionable.file, app.vault)
} else if (displayedMentionable.type === 'block') {
const fileContent = await readTFileContent(
displayedMentionable.file,
app.vault,
)

return fileContent
.split('\n')
.slice(
displayedMentionable.startLine - 1,
displayedMentionable.endLine,
)
.join('\n')
}

return null
},
})

const handleSubmit = (useVaultSearch?: boolean) => {
const content = editorRef.current?.getEditorState()?.toJSON()
content && onSubmit(content, useVaultSearch)
Expand All @@ -211,11 +272,41 @@ const ChatUserInput = forwardRef<ChatUserInputRef, ChatUserInputProps>(
key={getMentionableKey(serializeMentionable(m))}
mentionable={m}
onDelete={() => handleMentionableDelete(m)}
onClick={() => {
const mentionableKey = getMentionableKey(
serializeMentionable(m),
)
if (
(m.type === 'current-file' ||
m.type === 'file' ||
m.type === 'block') &&
m.file &&
mentionableKey === displayedMentionableKey
) {
// open file on click again
openMarkdownFile(app, m.file.path)
} else {
setDisplayedMentionableKey(mentionableKey)
}
}}
/>
))}
</div>
)}

{fileContent && (
<div className="smtcmp-chat-user-input-file-content-preview">
<MemoizedSyntaxHighlighterWrapper
isDarkMode={isDarkMode}
language="markdown"
hasFilename={false}
wrapLines={false}
>
{fileContent}
</MemoizedSyntaxHighlighterWrapper>
</div>
)}

<LexicalComposer initialConfig={initialConfig}>
{/*
There was two approach to make mentionable node copy and pasteable.
Expand Down
Loading
Loading