TagSpaces is an offline, open source, document manager with tagging support
Add context menu for the chat (#2216)
Stanimird1f2e0c1381b
diff --git a/src/renderer/components/chat/ChatMenu.tsx b/src/renderer/components/chat/ChatMenu.tsxnew file mode 100644index 000000000..9f4fa31fc--- /dev/null+++ b/src/renderer/components/chat/ChatMenu.tsx@@ -0,0 +1,124 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import React from 'react';+import { ListItemIcon, Menu, MenuItem } from '@mui/material';+import SelectAllIcon from '@mui/icons-material/SelectAll';+import { useTranslation } from 'react-i18next';+import { Divider } from '@mui/material/';+import CopyIcon from '@mui/icons-material/FileCopy';+import HtmlIcon from '@mui/icons-material/Html';+import RttIcon from '@mui/icons-material/Rtt';+import { DeleteIcon } from '-/components/CommonIcons';++interface ChatMenuProps {+ anchorEl: null | HTMLElement;+ handleClose: () => void;+ handleSelectAll: () => void;+ handleCopy: () => void;+ clearHistory: () => void;+ saveAsHtml: () => void;+ saveAsMarkdown: () => void;+}++function ChatMenu(props: ChatMenuProps) {+ const { t } = useTranslation();+ const {+ anchorEl,+ handleClose,+ handleSelectAll,+ handleCopy,+ clearHistory,+ saveAsHtml,+ saveAsMarkdown,+ } = props;++ return (+ <Menu+ anchorEl={anchorEl}+ id="account-menu"+ open={Boolean(anchorEl)}+ onClose={handleClose}+ onClick={handleClose}+ /*slotProps={{+ paper: {+ elevation: 0,+ sx: {+ overflow: 'visible',+ filter: 'drop-shadow(0px 2px 8px rgba(0,0,0,0.32))',+ mt: 1.5,+ '& .MuiAvatar-root': {+ width: 32,+ height: 32,+ ml: -0.5,+ mr: 1,+ },+ '&::before': {+ content: '""',+ display: 'block',+ position: 'absolute',+ top: 0,+ right: 14,+ width: 10,+ height: 10,+ bgcolor: 'background.paper',+ transform: 'translateY(-50%) rotate(45deg)',+ zIndex: 0,+ },+ },+ },+ }}*/+ transformOrigin={{ horizontal: 'right', vertical: 'top' }}+ anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}+ >+ <MenuItem onClick={handleSelectAll}>+ <ListItemIcon>+ <SelectAllIcon fontSize="small" />+ </ListItemIcon>+ {t('core:selectAll')}+ </MenuItem>+ <MenuItem onClick={handleCopy}>+ <ListItemIcon>+ <CopyIcon fontSize="small" />+ </ListItemIcon>+ {t('core:copy')}+ </MenuItem>+ <MenuItem onClick={clearHistory}>+ <ListItemIcon>+ <DeleteIcon fontSize="small" />+ </ListItemIcon>+ {t('core:clearHistory')}+ </MenuItem>+ <Divider />+ <MenuItem onClick={saveAsHtml}>+ <ListItemIcon>+ <HtmlIcon fontSize="small" />+ </ListItemIcon>+ {t('core:saveAsHtml')}+ </MenuItem>+ <MenuItem onClick={saveAsMarkdown}>+ <ListItemIcon>+ <RttIcon fontSize="small" />+ </ListItemIcon>+ {t('core:saveAsMd')}+ </MenuItem>+ </Menu>+ );+}++export default ChatMenu;diff --git a/src/renderer/components/chat/ChatView.tsx b/src/renderer/components/chat/ChatView.tsxindex 85703fa17..986aa15e7 100644--- a/src/renderer/components/chat/ChatView.tsx+++ b/src/renderer/components/chat/ChatView.tsx@@ -20,14 +20,19 @@ import AppConfig from '-/AppConfig';import { CloseIcon } from '-/components/CommonIcons';import DragItemTypes from '-/components/DragItemTypes';import Tooltip from '-/components/Tooltip';+import TsIconButton from '-/components/TsIconButton';import TsSelect from '-/components/TsSelect';import TsTextField from '-/components/TsTextField';import ChatDndTargetFile from '-/components/chat/ChatDndTargetFile';+import ChatMenu from '-/components/chat/ChatMenu';import { AIProvider, ChatItem, ChatMode } from '-/components/chat/ChatTypes';import SelectChatModel from '-/components/chat/SelectChatModel';import { OllamaIcon } from '-/components/dialogs/components/Ollama';import { useChatContext } from '-/hooks/useChatContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';import { getDefaultAIProvider } from '-/reducers/settings';+import { saveAsTextFile } from '-/services/utils-io';+import MoreVertIcon from '@mui/icons-material/MoreVert';import SendIcon from '@mui/icons-material/Send';import { Box, Grid2, MenuItem } from '@mui/material';import CircularProgress from '@mui/material/CircularProgress';@@ -36,10 +41,17 @@ import FormHelperText from '@mui/material/FormHelperText';import IconButton from '@mui/material/IconButton';import InputAdornment from '@mui/material/InputAdornment';import { useTheme } from '@mui/material/styles';+import { formatDateTime4Tag } from '@tagspaces/tagspaces-common/misc';import { extractFileExtension } from '@tagspaces/tagspaces-common/paths';import { MilkdownEditor, MilkdownRef } from '@tagspaces/tagspaces-md';import { format } from 'date-fns';-import { ChangeEvent, useEffect, useMemo, useReducer, useRef } from 'react';+import React, {+ ChangeEvent,+ useEffect,+ useMemo,+ useReducer,+ useRef,+} from 'react';import { NativeTypes } from 'react-dnd-html5-backend';import { useTranslation } from 'react-i18next';import { useSelector } from 'react-redux';@@ -58,16 +70,19 @@ function ChatView() {setModel,currentModel,getHistoryFilePath,+ deleteHistory,} = useChatContext();+ const { showNotification } = useNotificationContext();const aiDefaultProvider: AIProvider = useSelector(getDefaultAIProvider);const isTyping = useRef<boolean>(false);const isLoading = useRef<boolean>(false);const currentMode = useRef<ChatMode>(undefined);const editorRef = useRef<MilkdownRef>(null);+ const milkdownDivRef = useRef<HTMLDivElement>(null);const chatMsg = useRef<string>(undefined);//const txtInputRef = useRef<HTMLInputElement>(null);const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);-+ const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);/*const getAddedText = (oldText, newText) => {if (newText.startsWith(oldText)) {return newText.slice(oldText.length);@@ -95,7 +110,7 @@ function ChatView() {useEffect(() => {if (AppConfig.isElectron) {window.electronIO.ipcRenderer.on('ChatMessage', (message, replace) => {- console.log('ChatMessage:' + message);+ //console.log('ChatMessage:' + message);if (!replace) {// ignore download progressif (isLoading.current) {@@ -126,12 +141,21 @@ function ChatView() {};const handleChangeModel = (newModelName: string) => {- changeCurrentModel(newModelName).then((success) => {- if (success) {- setModel(newModelName);- //forceUpdate();- }- });+ changeCurrentModel(newModelName)+ .then((success) => {+ if (success) {+ setModel(newModelName);+ //forceUpdate();+ }+ })+ .catch((err) => {+ showNotification(+ t('core:installCustomModel') + err.message + ': ' + newModelName,+ 'error',+ false,+ );+ console.log(err);+ });};function formatChatItems(chatItems: ChatItem[]): string {@@ -196,6 +220,73 @@ function ChatView() {);};+ const handleMoreClick = (event: React.MouseEvent<HTMLElement>) => {+ setAnchorEl(event.currentTarget);+ };+ const handleClose = () => {+ setAnchorEl(null);+ };++ const handleSelectAll = () => {+ setAnchorEl(null);+ const range = document.createRange(); // Create a new range+ const selection = window.getSelection(); // Get the current selection+ if (milkdownDivRef.current) {+ range.selectNodeContents(milkdownDivRef.current); // Select the text inside the div+ selection.removeAllRanges(); // Clear any existing selections+ selection.addRange(range); // Add the new range to the selection+ }+ };++ const handleCopy = () => {+ setAnchorEl(null);+ if (milkdownDivRef.current) {+ const textToCopy = milkdownDivRef.current.innerText; // Get the text content of the div+ navigator.clipboard+ .writeText(textToCopy)+ .then(() => {+ showNotification(t('core:copyToClipboard'));+ })+ .catch((err) => {+ console.error('Failed to copy text:', err);+ showNotification(t('core:generatedHTMLFailed'));+ });+ }+ };++ const clearHistory = () => {+ setAnchorEl(null);+ deleteHistory();+ };++ const saveAsHtml = () => {+ setAnchorEl(null);+ if (milkdownDivRef.current) {+ const html = milkdownDivRef.current.innerHTML;+ const blob = new Blob([html], {+ type: 'text/html',+ });+ const dateTimeTag = formatDateTime4Tag(new Date(), true);+ const filename = 'tagspaces-chat [export ' + dateTimeTag + '].html';++ saveAsTextFile(blob, filename);+ }+ };++ const saveAsMarkdown = () => {+ setAnchorEl(null);+ if (editorRef.current) {+ const md = editorRef.current.getMarkdown();+ const blob = new Blob([md], {+ type: 'text/markdown',+ });+ const dateTimeTag = formatDateTime4Tag(new Date(), true);+ const filename = 'tagspaces-chat [export ' + dateTimeTag + '].md';++ saveAsTextFile(blob, filename);+ }+ };+const { FILE } = NativeTypes;return (@@ -210,8 +301,13 @@ function ChatView() {overflow: 'hidden',}}>- <Grid2 container spacing={1} direction="row">- <Grid2 size={12}>+ <Grid2+ container+ spacing={0}+ direction="row"+ style={{ flexFlow: 'nowrap' }}+ >+ <Grid2 size={11.5}><SelectChatModelid="chatModelId"handleChangeModel={handleChangeModel}@@ -219,14 +315,39 @@ function ChatView() {label={t('core:selectedAIModel')}/></Grid2>+ <Grid2>+ <TsIconButton+ style={{ marginTop: 20 }}+ tooltip={t('core:chatMore')}+ onClick={handleMoreClick}+ data-tid="chatMoreTID"+ aria-label={t('core:chatMore')}+ aria-controls={Boolean(anchorEl) ? 'account-menu' : undefined}+ aria-haspopup="true"+ aria-expanded={Boolean(anchorEl) ? 'true' : undefined}+ >+ <MoreVertIcon />+ </TsIconButton>+ <ChatMenu+ anchorEl={anchorEl}+ handleClose={handleClose}+ handleSelectAll={handleSelectAll}+ handleCopy={handleCopy}+ clearHistory={clearHistory}+ saveAsHtml={saveAsHtml}+ saveAsMarkdown={saveAsMarkdown}+ />+ </Grid2></Grid2><Grid2 size="grow" sx={{ padding: 0, overflowY: 'auto' }}>- <MilkdownEditor- ref={editorRef}- content={formatChatItems(chatHistoryItems)}- readOnly={true}- lightMode={true}- />+ <div ref={milkdownDivRef}>+ <MilkdownEditor+ ref={editorRef}+ content={formatChatItems(chatHistoryItems)}+ readOnly={true}+ lightMode={true}+ />+ </div></Grid2><Grid2 container spacing={1} direction="column"><Grid2>diff --git a/src/renderer/components/chat/SelectChatModel.tsx b/src/renderer/components/chat/SelectChatModel.tsxindex 1dd75283a..41e317480 100644--- a/src/renderer/components/chat/SelectChatModel.tsx+++ b/src/renderer/components/chat/SelectChatModel.tsx@@ -16,14 +16,16 @@**/-import { RemoveIcon } from '-/components/CommonIcons';+import { AIIcon, RemoveIcon } from '-/components/CommonIcons';import TsSelect from '-/components/TsSelect';import { Model } from '-/components/chat/ChatTypes';+import ConfirmDialog from '-/components/dialogs/ConfirmDialog';import { useChatContext } from '-/hooks/useChatContext';-import { MenuItem } from '@mui/material';+import DownloadIcon from '@mui/icons-material/Download';+import { ListItemIcon, MenuItem } from '@mui/material';import IconButton from '@mui/material/IconButton';import InputAdornment from '@mui/material/InputAdornment';-import { ChangeEvent } from 'react';+import { ChangeEvent, useState } from 'react';import { useTranslation } from 'react-i18next';interface Props {@@ -38,6 +40,8 @@ function SelectChatModel(props: Props) {const { t } = useTranslation();const { id, label, chosenModel, handleChangeModel, disabled } = props;const { models, removeModel } = useChatContext();+ const [isCustomModelPromptDialogOpened, setCustomModelPromptDialogOpened] =+ useState(false);const ollamaAvailableModels: Model[] = [{@@ -97,7 +101,11 @@ function SelectChatModel(props: Props) {];const changeModel = (event: ChangeEvent<HTMLInputElement>) => {- handleChangeModel(event.target.value);+ if (event.target.value === 'customModel') {+ setCustomModelPromptDialogOpened(true);+ } else {+ handleChangeModel(event.target.value);+ }};const handleRemoveModel = () => {@@ -105,63 +113,105 @@ function SelectChatModel(props: Props) {};return (- <TsSelect- disabled={disabled}- value={chosenModel ? chosenModel : 'init'}- onChange={changeModel}- label={label ? label : ''}- id={id ? id : 'selectChatModelId'}- slotProps={{- input: {- endAdornment: chosenModel && (- <InputAdornment position="end" sx={{ ml: -12 }}>- <IconButton- aria-label={t('core:deleteModel')}- onClick={handleRemoveModel}- data-tid="deleteModelTID"- size="small"- >- <RemoveIcon />- </IconButton>- </InputAdornment>- ),- },- }}- >- <MenuItem value="init" disabled>- {t('core:chooseModel')}- </MenuItem>- <MenuItem value="" disabled>- {t('core:installedAIModel')}- </MenuItem>- {models && models.length > 0 ? (- models.map((model) => (+ <>+ <TsSelect+ disabled={disabled}+ value={chosenModel ? chosenModel : 'init'}+ onChange={changeModel}+ label={label ? label : ''}+ id={id ? id : 'selectChatModelId'}+ slotProps={{+ input: {+ endAdornment: chosenModel && (+ <InputAdornment position="end" sx={{ ml: -12 }}>+ <IconButton+ aria-label={t('core:deleteModel')}+ onClick={handleRemoveModel}+ data-tid="deleteModelTID"+ size="small"+ >+ <RemoveIcon />+ </IconButton>+ </InputAdornment>+ ),+ },+ }}+ >+ <MenuItem value="init" disabled>+ {t('core:chooseModel')}+ </MenuItem>+ <MenuItem value="" disabled>+ {t('core:installedAIModel')}+ </MenuItem>+ {models && models.length > 0 ? (+ models.map((model) => (+ <MenuItem+ key={model.name}+ value={model.name}+ title={model.modified_at}+ >+ {' '}+ <ListItemIcon>+ <AIIcon fontSize="small" />+ </ListItemIcon>+ {model.name} {(model.size / (1024 * 1024 * 1024)).toFixed(2)} GB+ </MenuItem>+ ))+ ) : (+ <MenuItem value="" disabled>+ {t('core:noAIModelsInstaller')}+ </MenuItem>+ )}+ <MenuItem value="" disabled>+ {t('core:exampleInstallableModels')}+ </MenuItem>+ {ollamaAvailableModels.map((model) => (<MenuItemkey={model.name}value={model.name}- title={model.modified_at}+ title={model.details.format}>- {model.name} {(model.size / (1024 * 1024 * 1024)).toFixed(2)} GB+ <ListItemIcon>+ <DownloadIcon fontSize="small" />+ </ListItemIcon>+ {model.name}</MenuItem>- ))- ) : (+ ))}<MenuItem value="" disabled>- {t('core:noAIModelsInstaller')}+ {t('core:moreActions')}</MenuItem>- )}- <MenuItem value="" disabled>- {t('core:exampleInstallableModels')}- </MenuItem>- {ollamaAvailableModels.map((model) => (- <MenuItem- key={model.name}- value={model.name}- title={model.details.format}- >- {model.name}+ <MenuItem value="customModel">+ <ListItemIcon>+ <DownloadIcon fontSize="small" />+ </ListItemIcon>+ {t('core:installCustomModel')}</MenuItem>- ))}- </TsSelect>+ </TsSelect>+ <ConfirmDialog+ prompt={t('core:model')}+ open={isCustomModelPromptDialogOpened}+ onClose={() => {+ setCustomModelPromptDialogOpened(false);+ }}+ title={t('core:downloadChatModel')}+ helpText={+ 'E.g.: llama3.2:1b, further models available on ollama.com/search'+ }+ // content={t('core:chooseModel')}+ confirmCallback={(result) => {+ if (result && typeof result === 'string') {+ handleChangeModel(result);+ } else {+ setCustomModelPromptDialogOpened(false);+ }+ }}+ cancelDialogTID="cancelInstallCustomModel"+ confirmDialogTID="confirmInstallCustomModel"+ confirmDialogContentTID="confirmCustomModelContent"+ customConfirmText={t('core:startDownload')}+ customCancelText={t('core:cancel')}+ />+ </>);}diff --git a/src/renderer/components/dialogs/ConfirmDialog.tsx b/src/renderer/components/dialogs/ConfirmDialog.tsxindex fc36614a2..1293624a1 100644--- a/src/renderer/components/dialogs/ConfirmDialog.tsx+++ b/src/renderer/components/dialogs/ConfirmDialog.tsx@@ -16,40 +16,54 @@**/-import React from 'react';+import DraggablePaper from '-/components/DraggablePaper';import TsButton from '-/components/TsButton';+import TsTextField from '-/components/TsTextField';+import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import TsDialogActions from '-/components/dialogs/components/TsDialogActions';+import BulletIcon from '@mui/icons-material/Remove';+import Dialog from '@mui/material/Dialog';import DialogContent from '@mui/material/DialogContent';-import DialogTitle from '@mui/material/DialogTitle';import DialogContentText from '@mui/material/DialogContentText';-import DraggablePaper from '-/components/DraggablePaper';+import DialogTitle from '@mui/material/DialogTitle';import List from '@mui/material/List';import ListItem from '@mui/material/ListItem';-import BulletIcon from '@mui/icons-material/Remove';import ListItemIcon from '@mui/material/ListItemIcon';import ListItemText from '@mui/material/ListItemText';-import Dialog from '@mui/material/Dialog';-import DialogCloseButton from '-/components/dialogs/DialogCloseButton';+import { useState } from 'react';import { useTranslation } from 'react-i18next';interface Props {open: boolean;title: string;- content: string;+ content?: string;+ customConfirmText?: string;+ customCancelText?: string;cancelDialogTID?: string;confirmDialogTID?: string;confirmDialogContentTID?: string;+ prompt?: string;+ helpText?: string;list: Array<string>;- confirmCallback: (result: boolean) => void;+ confirmCallback: (result: boolean | string) => void;onClose: () => void;}function ConfirmDialog(props: Props) {- const { open, onClose, confirmCallback } = props;+ const {+ open,+ onClose,+ confirmCallback,+ prompt,+ helpText,+ customCancelText,+ customConfirmText,+ } = props;const { t } = useTranslation();+ const [promptValue, setPromptValue] = useState<string>('');function onConfirm(result) {- confirmCallback(result);+ confirmCallback(result && prompt ? promptValue : result);onClose();}@@ -73,6 +87,15 @@ function ConfirmDialog(props: Props) {component="span">{props.content}+ {prompt && (+ <TsTextField+ fullWidth+ label={helpText}+ value={promptValue}+ onChange={(e) => setPromptValue(e.target.value)}+ placeholder={prompt}+ />+ )}{props.list && (<List dense>{props.list.map((listItem) => (@@ -92,13 +115,13 @@ function ConfirmDialog(props: Props) {onClick={() => onConfirm(false)}data-tid={props.cancelDialogTID}>- {t('core:no')}+ {customCancelText ? customCancelText : t('core:no')}</TsButton><TsButtondata-tid={props.confirmDialogTID}onClick={() => onConfirm(true)}>- {t('core:yes')}+ {customConfirmText ? customConfirmText : t('core:yes')}</TsButton></TsDialogActions></Dialog>diff --git a/src/renderer/hooks/ChatProvider.tsx b/src/renderer/hooks/ChatProvider.tsxindex 529a72c34..752a84462 100644--- a/src/renderer/hooks/ChatProvider.tsx+++ b/src/renderer/hooks/ChatProvider.tsx@@ -89,6 +89,7 @@ type ChatData = {) => Promise<any>;generate: (fileContent: 'text' | 'image', mode: ChatMode) => Promise<string>;initHistory: () => void;+ deleteHistory: () => Promise<boolean>;};export const ChatContext = createContext<ChatData>({@@ -113,6 +114,7 @@ export const ChatContext = createContext<ChatData>({newChatMessage: undefined,generate: undefined,initHistory: undefined,+ deleteHistory: undefined,});export type ChatContextProviderProps = {@@ -239,6 +241,20 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {return undefined;}+ function deleteHistory(): Promise<boolean> {+ const historyFilePath = getHistoryFilePath();+ if (currentLocation) {+ return currentLocation+ .deleteFilePromise(historyFilePath, false)+ .then(() => {+ chatHistoryItems.current = [];+ forceUpdate();+ return true;+ });+ }+ return Promise.resolve(false);+ }+function loadHistory(): Promise<ChatItem[]> {const historyFilePath = getHistoryFilePath();if (currentLocation) {@@ -726,6 +742,7 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {findModel,generate,initHistory,+ deleteHistory,};}, [defaultAiProvider,diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.jsonindex ab50b2ac9..09a31a65d 100644--- a/src/renderer/locales/en/core.json+++ b/src/renderer/locales/en/core.json@@ -808,6 +808,8 @@"confirmtsLastOpenedFilesHistoryDeletion": "Are you sure you want to clear the list of your recently opened files?","searchHasTheWords": "Has the words","saveAsHtml": "Save as HTML",+ "saveAsMd": "Save as Markdown",+ "installCustomModel": "Install Custom Model...","linkValidityDuration": "Download links are valid until {{linkValidityDistance}}","shareFiles": "Share Files","shareFile": "Share File",@@ -898,10 +900,12 @@"chooseModel": "Choose AI Model","selectedAIModel": "Selected AI Model","installedAIModel": "Installed AI Model",+ "moreActions": "More Actions","exampleInstallableModels": "Example Installable AI Models","noAIModelsInstaller": "No AI Models Installed","engineName": "AI Engine Name","maxCollectedTag": "Max Collected Tag","aiChatTab": "AI Chat",+ "startDownload": "Start download","-": "-"}