Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
57 changes: 41 additions & 16 deletions app/[docs_id]/chatForm.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,54 @@
"use client";

import { useState, FormEvent } from "react";
import { useState, FormEvent, useEffect } from "react";
import { askAI } from "@/app/actions/chatActions";
import { StyledMarkdown } from "./markdown";
import { useChatHistory } from "../context/ChatHistoryContext";

interface Message {
sender: "user" | "ai";
text: string;
}

interface ChatFormProps {
documentContent: string;
sectionId: string;
}

export function ChatForm({ documentContent, sectionId }: ChatFormProps) {
const { chatHistories, setChatHistory } = useChatHistory();
const messages = chatHistories[sectionId] || [];

export function ChatForm({ documentContent }: { documentContent: string }) {
const [inputValue, setInputValue] = useState("");
const [response, setResponse] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [isFormVisible, setIsFormVisible] = useState(false);
const [isMounted, setIsMounted] = useState(false);

useEffect(() => {
setIsMounted(true);
}, []);

const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
setIsLoading(true);
setResponse("");

const userMessage: Message = { sender: "user", text: inputValue };
setChatHistory(sectionId, [userMessage]);

const result = await askAI({
userQuestion: inputValue,
documentContent: documentContent,
});

if (result.error) {
setResponse(`エラー: ${result.error}`);
const errorMessage: Message = { sender: "ai", text: `エラー: ${result.error}` };
setChatHistory(sectionId, [userMessage, errorMessage]);
} else {
setResponse(result.response);
const aiMessage: Message = { sender: "ai", text: result.response };
setChatHistory(sectionId, [userMessage, aiMessage]);
}

setInputValue("");
setIsLoading(false);
};
return (
Expand All @@ -51,8 +74,8 @@ export function ChatForm({ documentContent }: { documentContent: string }) {
<button
className="btn btn-soft btn-secondary rounded-full"
onClick={() => setIsFormVisible(false)}
type="button"
>

閉じる
</button>
</div>
Expand All @@ -62,7 +85,7 @@ export function ChatForm({ documentContent }: { documentContent: string }) {
className="btn btn-soft btn-circle btn-accent border-2 border-accent rounded-full"
title="送信"
style={{marginTop:"10px"}}
disabled={isLoading}
disabled={isLoading || !inputValue.trim()}
>
<span className="icon">➤</span>
</button>
Expand All @@ -79,14 +102,16 @@ export function ChatForm({ documentContent }: { documentContent: string }) {
</button>
)}

{response && (
<article>
<h3 className="text-lg font-semibold mb-2">AIの回答</h3>
<div className="chat chat-start">
<div className="chat-bubble bg-secondary-content text-black" style={{maxWidth: "100%", wordBreak: "break-word"}}>
<div className="response-container"><StyledMarkdown content={response}/></div>
{isMounted && messages.length > 0 && (
<article className="mt-4">
<h3 className="text-lg font-semibold mb-2">AIとのチャット</h3>
{messages.map((msg, index) => (
<div key={index} className={`chat ${msg.sender === 'user' ? 'chat-end' : 'chat-start'}`}>
<div className={`chat-bubble ${msg.sender === 'user' ? 'bg-primary text-primary-content' : 'bg-secondary-content text-black'}`} style={{maxWidth: "100%", wordBreak: "break-word"}}>
<StyledMarkdown content={msg.text} />
</div>
</div>
</div>
))}
</article>
)}

Expand All @@ -98,4 +123,4 @@ export function ChatForm({ documentContent }: { documentContent: string }) {

</>
);
}
}
2 changes: 1 addition & 1 deletion app/[docs_id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default async function Page({
return (
<div className="p-4">
{splitMdContent.map((section, index) => (
<Section key={index} section={section} />
<Section key={`${docs_id}-${index}`} section={section} docs_id={docs_id} sectionIndex={index} />
))}
</div>
);
Expand Down
10 changes: 8 additions & 2 deletions app/[docs_id]/section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,14 @@ interface ISectionCodeContext {
}
const SectionCodeContext = createContext<ISectionCodeContext | null>(null);
export const useSectionCode = () => useContext(SectionCodeContext);
interface SectionProps {
section: MarkdownSection;
docs_id: string;
sectionIndex: number;
}

// 1つのセクションのタイトルと内容を表示する。内容はMarkdownとしてレンダリングする
export function Section({ section }: { section: MarkdownSection }) {
export function Section({ section, docs_id, sectionIndex }: SectionProps) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [replOutputs, setReplOutputs] = useState<ReplCommand[]>([]);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand Down Expand Up @@ -62,6 +67,7 @@ export function Section({ section }: { section: MarkdownSection }) {
// fileContents: section内にあるファイルエディターの内容
// execResults: section内にあるファイルの実行結果
// console.log(section.title, replOutputs, fileContents, execResults);
const sectionId = `${docs_id}-${sectionIndex}`;

return (
<SectionCodeContext.Provider
Expand All @@ -70,7 +76,7 @@ export function Section({ section }: { section: MarkdownSection }) {
<div>
<Heading level={section.level}>{section.title}</Heading>
<StyledMarkdown content={section.content} />
<ChatForm documentContent={section.content} />
<ChatForm key={sectionId} documentContent={section.content} sectionId={sectionId} />
</div>
</SectionCodeContext.Provider>
);
Expand Down
67 changes: 67 additions & 0 deletions app/context/ChatHistoryContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"use client";

import { createContext, ReactNode, useCallback, useContext, useState, useEffect } from "react";

interface Message {
sender: "user" | "ai";
text: string;
}

interface IChatHistoryContext {
chatHistories: Record<string, Message[]>;
setChatHistory: (sectionId: string, messages: Message[]) => void;
}

const ChatHistoryContext = createContext<IChatHistoryContext | null>(null);

export const useChatHistory = () => {
const context = useContext(ChatHistoryContext);
if (!context) {
throw new Error("useChatHistory must be used within a ChatHistoryProvider");
}
return context;
};

const CHAT_HISTORY_STORAGE_KEY = "my-code-all-chat-histories";

export function ChatHistoryProvider({ children }: { children: ReactNode }) {
const [chatHistories, setChatHistories] = useState<Record<string, Message[]>>({});

useEffect(() => {
try {
const savedHistories = localStorage.getItem(CHAT_HISTORY_STORAGE_KEY);
if (savedHistories) {
setChatHistories(JSON.parse(savedHistories));
}
} catch (error) {
console.error("Failed to load chat histories from localStorage", error);
}
}, []);

useEffect(() => {
if (Object.keys(chatHistories).length > 0) {
localStorage.setItem(CHAT_HISTORY_STORAGE_KEY, JSON.stringify(chatHistories));
} else {
const saved = localStorage.getItem(CHAT_HISTORY_STORAGE_KEY);
if(saved) localStorage.removeItem(CHAT_HISTORY_STORAGE_KEY);
}
}, [chatHistories]);

const setChatHistory = useCallback((sectionId: string, messages: Message[]) => {
setChatHistories((prevHistories) => {
const newHistories = { ...prevHistories };
if (messages.length === 0) {
delete newHistories[sectionId];
} else {
newHistories[sectionId] = messages;
}
return newHistories;
});
}, []);

return (
<ChatHistoryContext.Provider value={{ chatHistories, setChatHistory }}>
{children}
</ChatHistoryContext.Provider>
);
}
9 changes: 6 additions & 3 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Sidebar } from "./sidebar";
import { ReactNode } from "react";
import { PyodideProvider } from "./terminal/python/pyodide";
import { FileProvider } from "./terminal/file";
import { ChatHistoryProvider } from "./context/ChatHistoryContext";

export const metadata: Metadata = {
title: "Create Next App",
Expand All @@ -21,9 +22,11 @@ export default function RootLayout({
<input id="drawer-toggle" type="checkbox" className="drawer-toggle" />
<div className="drawer-content flex flex-col">
<Navbar />
<FileProvider>
<PyodideProvider>{children}</PyodideProvider>
</FileProvider>
<ChatHistoryProvider>
<FileProvider>
<PyodideProvider>{children}</PyodideProvider>
</FileProvider>
</ChatHistoryProvider>
</div>
<div className="drawer-side shadow-md">
<label
Expand Down