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

Listen to active note changes #1015

Merged
merged 1 commit into from
Jan 7, 2025
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
21 changes: 10 additions & 11 deletions src/components/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { updateChatMemory } from "@/chatUtils";
import ChatInput from "@/components/chat-components/ChatInput";
import ChatMessages from "@/components/chat-components/ChatMessages";
import { ABORT_REASON, AI_SENDER, EVENT_NAMES, LOADING_MESSAGES, USER_SENDER } from "@/constants";
import { AppContext } from "@/context";
import { AppContext, EventTargetContext } from "@/context";
import { ContextProcessor } from "@/contextProcessor";
import { CustomPromptProcessor } from "@/customPromptProcessor";
import { getAIResponse } from "@/langchainStream";
Expand Down Expand Up @@ -44,7 +44,6 @@ interface CreateEffectOptions {
interface ChatProps {
sharedState: SharedState;
chainManager: ChainManager;
emitter: EventTarget;
onSaveChat: (saveAsNote: () => Promise<void>) => void;
updateUserMessageHistory: (newMessage: string) => void;
fileParserManager: FileParserManager;
Expand All @@ -54,13 +53,13 @@ interface ChatProps {
const Chat: React.FC<ChatProps> = ({
sharedState,
chainManager,
emitter,
onSaveChat,
updateUserMessageHistory,
fileParserManager,
plugin,
}) => {
const settings = useSettingsValue();
const eventTarget = useContext(EventTargetContext);
const [chatHistory, addMessage, clearMessages] = useSharedState(sharedState);
const [currentModelKey] = useModelKey();
const [currentChain] = useChainType();
Expand All @@ -85,13 +84,13 @@ const Chat: React.FC<ChatProps> = ({
inputRef.current.focus();
}
};
emitter.addEventListener(EVENT_NAMES.CHAT_IS_VISIBLE, handleChatVisibility);
eventTarget?.addEventListener(EVENT_NAMES.CHAT_IS_VISIBLE, handleChatVisibility);

// Cleanup function
return () => {
emitter.removeEventListener(EVENT_NAMES.CHAT_IS_VISIBLE, handleChatVisibility);
eventTarget?.removeEventListener(EVENT_NAMES.CHAT_IS_VISIBLE, handleChatVisibility);
};
}, [emitter]);
}, [eventTarget]);

const appContext = useContext(AppContext);
const app = plugin.app || appContext;
Expand Down Expand Up @@ -450,13 +449,13 @@ ${chatContent}`;
addMessage(tokenCountMessage);
}

emitter.addEventListener("countTokensSelection", handleSelection);
eventTarget?.addEventListener("countTokensSelection", handleSelection);

// Cleanup function to remove the event listener when the component unmounts
return () => {
emitter.removeEventListener("countTokensSelection", handleSelection);
eventTarget?.removeEventListener("countTokensSelection", handleSelection);
};
}, [addMessage, chainManager.chatModelManager, emitter]);
}, [addMessage, chainManager.chatModelManager, eventTarget]);

// Create an effect for each event type (Copilot command on selected text)
const createEffect = (
Expand Down Expand Up @@ -501,11 +500,11 @@ ${chatContent}`;
setLoading(false);
};

emitter.addEventListener(eventType, handleSelection);
eventTarget?.addEventListener(eventType, handleSelection);

// Cleanup function to remove the event listener when the component unmounts
return () => {
emitter.removeEventListener(eventType, handleSelection);
eventTarget?.removeEventListener(eventType, handleSelection);
};
};
};
Expand Down
33 changes: 17 additions & 16 deletions src/components/CopilotView.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ChainManager from "@/LLMProviders/chainManager";
import Chat from "@/components/Chat";
import { CHAT_VIEWTYPE } from "@/constants";
import { AppContext } from "@/context";
import { AppContext, EventTargetContext } from "@/context";
import CopilotPlugin from "@/main";
import SharedState from "@/sharedState";
import { FileParserManager } from "@/tools/FileParserManager";
Expand All @@ -16,7 +16,7 @@ export default class CopilotView extends ItemView {
private root: Root | null = null;
private handleSaveAsNote: (() => Promise<void>) | null = null;
sharedState: SharedState;
emitter: EventTarget;
eventTarget: EventTarget;

constructor(
leaf: WorkspaceLeaf,
Expand All @@ -27,7 +27,7 @@ export default class CopilotView extends ItemView {
this.app = plugin.app;
this.chainManager = plugin.chainManager;
this.fileParserManager = plugin.fileParserManager;
this.emitter = new EventTarget();
this.eventTarget = new EventTarget();
this.plugin = plugin;
}

Expand Down Expand Up @@ -59,19 +59,20 @@ export default class CopilotView extends ItemView {
};
root.render(
<AppContext.Provider value={this.app}>
<React.StrictMode>
<Tooltip.Provider delayDuration={0}>
<Chat
sharedState={this.sharedState}
chainManager={this.chainManager}
emitter={this.emitter}
updateUserMessageHistory={updateUserMessageHistory}
fileParserManager={this.fileParserManager}
plugin={this.plugin}
onSaveChat={handleSaveAsNote}
/>
</Tooltip.Provider>
</React.StrictMode>
<EventTargetContext.Provider value={this.eventTarget}>
<React.StrictMode>
<Tooltip.Provider delayDuration={0}>
<Chat
sharedState={this.sharedState}
chainManager={this.chainManager}
updateUserMessageHistory={updateUserMessageHistory}
fileParserManager={this.fileParserManager}
plugin={this.plugin}
onSaveChat={handleSaveAsNote}
/>
</Tooltip.Provider>
</React.StrictMode>
</EventTargetContext.Provider>
</AppContext.Provider>
);
}
Expand Down
5 changes: 3 additions & 2 deletions src/components/chat-components/RelevantNotes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@ import React, { forwardRef, memo, useEffect, useState } from "react";
import { Notice, TFile } from "obsidian";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { useActiveFile } from "@/hooks/useActiveFile";

function useRelevantNotes(refresher: number) {
const [relevantNotes, setRelevantNotes] = useState<RelevantNoteEntry[]>([]);
const activeFile = app.workspace.getActiveFile();
const activeFile = useActiveFile();

useEffect(() => {
async function fetchNotes() {
Expand Down Expand Up @@ -198,7 +199,7 @@ export const RelevantNotes = memo(
const [refresher, setRefresher] = useState(0);
const [isOpen, setIsOpen] = useState(defaultOpen);
const relevantNotes = useRelevantNotes(refresher);
const activeFile = app.workspace.getActiveFile();
const activeFile = useActiveFile();
const hasIndex = useHasIndex(activeFile?.path ?? "", refresher);
const navigateToNote = (notePath: string) => {
const file = app.vault.getAbstractFileByPath(notePath);
Expand Down
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,7 @@ export const DEFAULT_SETTINGS: CopilotSettings = {

export const EVENT_NAMES = {
CHAT_IS_VISIBLE: "chat-is-visible",
ACTIVE_LEAF_CHANGE: "active-leaf-change",
};

export enum ABORT_REASON {
Expand Down
3 changes: 3 additions & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ import * as React from "react";

// App context
export const AppContext = React.createContext<App | undefined>(undefined);

// Event target context
export const EventTargetContext = React.createContext<EventTarget | undefined>(undefined);
22 changes: 22 additions & 0 deletions src/hooks/useActiveFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { EVENT_NAMES } from "@/constants";
import { EventTargetContext } from "@/context";
import { TFile } from "obsidian";
import { useContext, useEffect, useState } from "react";

export function useActiveFile() {
const [activeFile, setActiveFile] = useState<TFile | null>(null);
const eventTarget = useContext(EventTargetContext);

useEffect(() => {
const handleActiveLeafChange = () => {
const activeFile = app.workspace.getActiveFile();
setActiveFile(activeFile);
};
eventTarget?.addEventListener(EVENT_NAMES.ACTIVE_LEAF_CHANGE, handleActiveLeafChange);
return () => {
eventTarget?.removeEventListener(EVENT_NAMES.ACTIVE_LEAF_CHANGE, handleActiveLeafChange);
};
}, [eventTarget]);

return activeFile;
}
21 changes: 19 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,23 @@ export default class CopilotPlugin extends Plugin {
});

this.registerEvent(this.app.workspace.on("editor-menu", this.handleContextMenu));
this.registerEvent(
this.app.workspace.on("active-leaf-change", (leaf) => {
if (leaf && leaf.view instanceof MarkdownView) {
const file = leaf.view.file;
if (file) {
const activeCopilotView = this.app.workspace
.getLeavesOfType(CHAT_VIEWTYPE)
.find((leaf) => leaf.view instanceof CopilotView)?.view as CopilotView;

if (activeCopilotView) {
const event = new CustomEvent(EVENT_NAMES.ACTIVE_LEAF_CHANGE);
activeCopilotView.eventTarget.dispatchEvent(event);
}
}
}
})
);
}

async onunload() {
Expand Down Expand Up @@ -490,7 +507,7 @@ export default class CopilotPlugin extends Plugin {
.find((leaf) => leaf.view instanceof CopilotView)?.view as CopilotView;
if (activeCopilotView && (!checkSelectedText || selectedText)) {
const event = new CustomEvent(eventType, { detail: { selectedText, eventSubtype } });
activeCopilotView.emitter.dispatchEvent(event);
activeCopilotView.eventTarget.dispatchEvent(event);
}
}, 0);
}
Expand All @@ -506,7 +523,7 @@ export default class CopilotPlugin extends Plugin {

if (activeCopilotView) {
const event = new CustomEvent(EVENT_NAMES.CHAT_IS_VISIBLE);
activeCopilotView.emitter.dispatchEvent(event);
activeCopilotView.eventTarget.dispatchEvent(event);
}
}

Expand Down
Loading