editor-assistant.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import {
  2. useCallback, useEffect, useState, useRef, useMemo,
  3. } from 'react';
  4. import { GlobalCodeMirrorEditorKey } from '@growi/editor';
  5. import {
  6. acceptAllChunks, useTextSelectionEffect,
  7. } from '@growi/editor/dist/client/services/unified-merge-view';
  8. import { useCodeMirrorEditorIsolated } from '@growi/editor/dist/client/stores/codemirror-editor';
  9. import { useSecondaryYdocs } from '@growi/editor/dist/client/stores/use-secondary-ydocs';
  10. import { useForm, type UseFormReturn } from 'react-hook-form';
  11. import { useTranslation } from 'react-i18next';
  12. import { type Text as YText } from 'yjs';
  13. import { apiv3Post } from '~/client/util/apiv3-client';
  14. import {
  15. SseMessageSchema,
  16. SseDetectedDiffSchema,
  17. SseFinalizedSchema,
  18. isReplaceDiff,
  19. // isInsertDiff,
  20. // isDeleteDiff,
  21. // isRetainDiff,
  22. type SseMessage,
  23. type SseDetectedDiff,
  24. type SseFinalized,
  25. } from '~/features/openai/interfaces/editor-assistant/sse-schemas';
  26. import { handleIfSuccessfullyParsed } from '~/features/openai/utils/handle-if-successfully-parsed';
  27. import { useIsEnableUnifiedMergeView } from '~/stores-universal/context';
  28. import { EditorMode, useEditorMode } from '~/stores-universal/ui';
  29. import { useCurrentPageId } from '~/stores/page';
  30. import type { AiAssistantHasId } from '../../interfaces/ai-assistant';
  31. import type { MessageLog } from '../../interfaces/message';
  32. import type { IThreadRelationHasId } from '../../interfaces/thread-relation';
  33. import { ThreadType } from '../../interfaces/thread-relation';
  34. import { AiAssistantDropdown } from '../components/AiAssistant/AiAssistantSidebar/AiAssistantDropdown';
  35. // import { type FormData } from '../components/AiAssistant/AiAssistantSidebar/AiAssistantSidebar';
  36. import { MessageCard, type MessageCardRole } from '../components/AiAssistant/AiAssistantSidebar/MessageCard';
  37. import { QuickMenuList } from '../components/AiAssistant/AiAssistantSidebar/QuickMenuList';
  38. import { useAiAssistantSidebar } from '../stores/ai-assistant';
  39. interface CreateThread {
  40. (): Promise<IThreadRelationHasId>;
  41. }
  42. interface PostMessage {
  43. (threadId: string, formData: FormData): Promise<Response>;
  44. }
  45. interface ProcessMessage {
  46. (data: unknown, handler: {
  47. onMessage: (data: SseMessage) => void;
  48. onDetectedDiff: (data: SseDetectedDiff) => void;
  49. onFinalized: (data: SseFinalized) => void;
  50. }): void;
  51. }
  52. interface GenerateInitialView {
  53. (onSubmit: (data: FormData) => Promise<void>): JSX.Element;
  54. }
  55. interface GenerateMessageCard {
  56. (role: MessageCardRole, children: string, messageId: string, messageLogs: MessageLog[], generatingAnswerMessage?: MessageLog): JSX.Element;
  57. }
  58. export interface FormData {
  59. input: string,
  60. markdownType?: 'full' | 'selected' | 'none'
  61. }
  62. type DetectedDiff = Array<{
  63. data: SseDetectedDiff,
  64. applied: boolean,
  65. id: string,
  66. }>
  67. type UseEditorAssistant = () => {
  68. createThread: CreateThread,
  69. postMessage: PostMessage,
  70. processMessage: ProcessMessage,
  71. form: UseFormReturn<FormData>
  72. resetForm: () => void
  73. isTextSelected: boolean,
  74. // Views
  75. generateInitialView: GenerateInitialView,
  76. generateMessageCard: GenerateMessageCard,
  77. headerIcon: JSX.Element,
  78. headerText: JSX.Element,
  79. placeHolder: string,
  80. }
  81. const insertTextAtLine = (yText: YText, lineNumber: number, textToInsert: string): void => {
  82. // Get the entire text content
  83. const content = yText.toString();
  84. // Split by newlines to get all lines
  85. const lines = content.split('\n');
  86. // Calculate the index position for insertion
  87. let insertPosition = 0;
  88. // Sum the length of all lines before the target line (plus newline characters)
  89. for (let i = 0; i < lineNumber && i < lines.length; i++) {
  90. insertPosition += lines[i].length + 1; // +1 for the newline character
  91. }
  92. // Insert the text at the calculated position
  93. yText.insert(insertPosition, textToInsert);
  94. };
  95. const appendTextLastLine = (yText: YText, textToAppend: string) => {
  96. const content = yText.toString();
  97. const insertPosition = content.length;
  98. yText.insert(insertPosition, `\n\n${textToAppend}`);
  99. };
  100. const getLineInfo = (yText: YText, lineNumber: number): { text: string, startIndex: number } | null => {
  101. // Get the entire text content
  102. const content = yText.toString();
  103. // Split by newlines to get all lines
  104. const lines = content.split('\n');
  105. // Check if the requested line exists
  106. if (lineNumber < 0 || lineNumber >= lines.length) {
  107. return null; // Line doesn't exist
  108. }
  109. // Get the text of the specified line
  110. const text = lines[lineNumber];
  111. // Calculate the start index of the line
  112. let startIndex = 0;
  113. for (let i = 0; i < lineNumber; i++) {
  114. startIndex += lines[i].length + 1; // +1 for the newline character
  115. }
  116. // Return comprehensive line information
  117. return {
  118. text,
  119. startIndex,
  120. };
  121. };
  122. export const useEditorAssistant: UseEditorAssistant = () => {
  123. // Refs
  124. // const positionRef = useRef<number>(0);
  125. const lineRef = useRef<number>(0);
  126. // States
  127. const [detectedDiff, setDetectedDiff] = useState<DetectedDiff>();
  128. const [selectedAiAssistant, setSelectedAiAssistant] = useState<AiAssistantHasId>();
  129. const [selectedText, setSelectedText] = useState<string>();
  130. const isTextSelected = useMemo(() => selectedText != null && selectedText.length !== 0, [selectedText]);
  131. // Hooks
  132. const { t } = useTranslation();
  133. const { data: currentPageId } = useCurrentPageId();
  134. const { data: isEnableUnifiedMergeView, mutate: mutateIsEnableUnifiedMergeView } = useIsEnableUnifiedMergeView();
  135. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  136. const yDocs = useSecondaryYdocs(isEnableUnifiedMergeView ?? false, { pageId: currentPageId ?? undefined, useSecondary: isEnableUnifiedMergeView ?? false });
  137. const { data: aiAssistantSidebarData } = useAiAssistantSidebar();
  138. const form = useForm<FormData>({
  139. defaultValues: {
  140. input: '',
  141. },
  142. });
  143. // Functions
  144. const resetForm = useCallback(() => {
  145. form.reset({ input: '' });
  146. }, [form]);
  147. const createThread: CreateThread = useCallback(async() => {
  148. const response = await apiv3Post<IThreadRelationHasId>('/openai/thread', {
  149. type: ThreadType.EDITOR,
  150. aiAssistantId: selectedAiAssistant?._id,
  151. });
  152. return response.data;
  153. }, [selectedAiAssistant?._id]);
  154. const postMessage: PostMessage = useCallback(async(threadId, formData) => {
  155. const getMarkdown = (): string | undefined => {
  156. if (formData.markdownType === 'none') {
  157. return undefined;
  158. }
  159. if (formData.markdownType === 'selected') {
  160. return selectedText;
  161. }
  162. if (formData.markdownType === 'full') {
  163. return codeMirrorEditor?.getDoc();
  164. }
  165. };
  166. const response = await fetch('/_api/v3/openai/edit', {
  167. method: 'POST',
  168. headers: { 'Content-Type': 'application/json' },
  169. body: JSON.stringify({
  170. threadId,
  171. userMessage: formData.input,
  172. markdown: getMarkdown(),
  173. }),
  174. });
  175. return response;
  176. }, [codeMirrorEditor, selectedText]);
  177. const processMessage: ProcessMessage = useCallback((data, handler) => {
  178. handleIfSuccessfullyParsed(data, SseMessageSchema, (data: SseMessage) => {
  179. handler.onMessage(data);
  180. });
  181. handleIfSuccessfullyParsed(data, SseDetectedDiffSchema, (data: SseDetectedDiff) => {
  182. mutateIsEnableUnifiedMergeView(true);
  183. setDetectedDiff((prev) => {
  184. const newData = { data, applied: false, id: crypto.randomUUID() };
  185. if (prev == null) {
  186. return [newData];
  187. }
  188. return [...prev, newData];
  189. });
  190. handler.onDetectedDiff(data);
  191. });
  192. handleIfSuccessfullyParsed(data, SseFinalizedSchema, (data: SseFinalized) => {
  193. handler.onFinalized(data);
  194. });
  195. }, [mutateIsEnableUnifiedMergeView]);
  196. const selectTextHandler = useCallback((selectedText: string, selectedTextFirstLineNumber: number) => {
  197. setSelectedText(selectedText);
  198. lineRef.current = selectedTextFirstLineNumber;
  199. }, []);
  200. // Effects
  201. useTextSelectionEffect(codeMirrorEditor, selectTextHandler);
  202. useEffect(() => {
  203. const pendingDetectedDiff: DetectedDiff | undefined = detectedDiff?.filter(diff => diff.applied === false);
  204. if (yDocs?.secondaryDoc != null && pendingDetectedDiff != null && pendingDetectedDiff.length > 0) {
  205. // For debug
  206. // const testDetectedDiff = [
  207. // {
  208. // data: { diff: { retain: 9 } },
  209. // applied: false,
  210. // id: crypto.randomUUID(),
  211. // },
  212. // {
  213. // data: { diff: { delete: 5 } },
  214. // applied: false,
  215. // id: crypto.randomUUID(),
  216. // },
  217. // {
  218. // data: { diff: { insert: 'growi' } },
  219. // applied: false,
  220. // id: crypto.randomUUID(),
  221. // },
  222. // ];
  223. const yText = yDocs.secondaryDoc.getText('codemirror');
  224. yDocs.secondaryDoc.transact(() => {
  225. pendingDetectedDiff.forEach((detectedDiff) => {
  226. if (isReplaceDiff(detectedDiff.data)) {
  227. if (isTextSelected) {
  228. const lineInfo = getLineInfo(yText, lineRef.current);
  229. if (lineInfo != null && lineInfo.text !== detectedDiff.data.diff.replace) {
  230. yText.delete(lineInfo.startIndex, lineInfo.text.length);
  231. insertTextAtLine(yText, lineRef.current, detectedDiff.data.diff.replace);
  232. }
  233. lineRef.current += 1;
  234. }
  235. else {
  236. appendTextLastLine(yText, detectedDiff.data.diff.replace);
  237. }
  238. }
  239. // if (isInsertDiff(detectedDiff.data)) {
  240. // yText.insert(positionRef.current, detectedDiff.data.diff.insert);
  241. // }
  242. // if (isDeleteDiff(detectedDiff.data)) {
  243. // yText.delete(positionRef.current, detectedDiff.data.diff.delete);
  244. // }
  245. // if (isRetainDiff(detectedDiff.data)) {
  246. // positionRef.current += detectedDiff.data.diff.retain;
  247. // }
  248. });
  249. });
  250. // Mark items as applied after applying to secondaryDoc
  251. setDetectedDiff((prev) => {
  252. if (!prev) return prev;
  253. const pendingDetectedDiffIds = pendingDetectedDiff.map(diff => diff.id);
  254. return prev.map((diff) => {
  255. if (pendingDetectedDiffIds.includes(diff.id)) {
  256. return { ...diff, applied: true };
  257. }
  258. return diff;
  259. });
  260. });
  261. }
  262. }, [codeMirrorEditor, detectedDiff, isTextSelected, selectedText, yDocs?.secondaryDoc]);
  263. // Set detectedDiff to undefined after applying all detectedDiff to secondaryDoc
  264. useEffect(() => {
  265. if (detectedDiff?.filter(detectedDiff => detectedDiff.applied === false).length === 0) {
  266. setSelectedText(undefined);
  267. setDetectedDiff(undefined);
  268. lineRef.current = 0;
  269. // positionRef.current = 0;
  270. }
  271. }, [detectedDiff]);
  272. // Views
  273. const headerIcon = useMemo(() => {
  274. return <span className="material-symbols-outlined growi-ai-chat-icon me-3 fs-4">support_agent</span>;
  275. }, []);
  276. const headerText = useMemo(() => {
  277. return <>{t('Editor Assistant')}</>;
  278. }, [t]);
  279. const placeHolder = useMemo(() => { return 'sidebar_ai_assistant.editor_assistant_placeholder' }, []);
  280. const generateInitialView: GenerateInitialView = useCallback((onSubmit) => {
  281. const selectAiAssistantHandler = (aiAssistant?: AiAssistantHasId) => {
  282. setSelectedAiAssistant(aiAssistant);
  283. };
  284. const clickQuickMenuHandler = async(quickMenu: string) => {
  285. await onSubmit({ input: quickMenu, markdownType: 'full' });
  286. };
  287. return (
  288. <>
  289. <div className="py-2">
  290. <AiAssistantDropdown
  291. selectedAiAssistant={selectedAiAssistant}
  292. onSelect={selectAiAssistantHandler}
  293. />
  294. </div>
  295. <QuickMenuList
  296. onClick={clickQuickMenuHandler}
  297. />
  298. </>
  299. );
  300. }, [selectedAiAssistant]);
  301. const generateMessageCard: GenerateMessageCard = useCallback((role, children, messageId, messageLogs, generatingAnswerMessage) => {
  302. const isActionButtonShown = (() => {
  303. if (!aiAssistantSidebarData?.isEditorAssistant) {
  304. return false;
  305. }
  306. if (generatingAnswerMessage != null) {
  307. return false;
  308. }
  309. const latestAssistantMessageLogId = messageLogs
  310. .filter(message => !message.isUserMessage)
  311. .slice(-1)[0];
  312. if (messageId === latestAssistantMessageLogId?.id) {
  313. return true;
  314. }
  315. return false;
  316. })();
  317. const accept = () => {
  318. if (codeMirrorEditor?.view == null) {
  319. return;
  320. }
  321. acceptAllChunks(codeMirrorEditor.view);
  322. mutateIsEnableUnifiedMergeView(false);
  323. };
  324. const reject = () => {
  325. mutateIsEnableUnifiedMergeView(false);
  326. };
  327. return (
  328. <MessageCard
  329. role={role}
  330. showActionButtons={isActionButtonShown}
  331. onAccept={accept}
  332. onDiscard={reject}
  333. >
  334. {children}
  335. </MessageCard>
  336. );
  337. }, [aiAssistantSidebarData?.isEditorAssistant, codeMirrorEditor?.view, mutateIsEnableUnifiedMergeView]);
  338. return {
  339. createThread,
  340. postMessage,
  341. processMessage,
  342. form,
  343. resetForm,
  344. isTextSelected,
  345. // Views
  346. generateInitialView,
  347. generateMessageCard,
  348. headerIcon,
  349. headerText,
  350. placeHolder,
  351. };
  352. };
  353. // type guard
  354. export const isEditorAssistantFormData = (formData): formData is FormData => {
  355. return 'markdownType' in formData;
  356. };