Skip to content

Commit

Permalink
save
Browse files Browse the repository at this point in the history
  • Loading branch information
AntoLC committed Sep 20, 2024
1 parent 480c574 commit 01d279c
Show file tree
Hide file tree
Showing 5 changed files with 231 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useMutation } from '@tanstack/react-query';

import { APIError, errorCauses, fetchAPI } from '@/api';

export type AIActions =
| 'prompt'
| 'rephrase'
| 'summarize'
| 'translate'
| 'correct'
| 'translate_fr'
| 'translate_en'
| 'translate_de';

export type AIParams = {
text: string;
action: AIActions;
};

export type AIResponse = {
answer: string;
};

export const AI = async ({ ...params }: AIParams): Promise<AIResponse> => {
const response = await fetchAPI(`ai/`, {
method: 'POST',
body: JSON.stringify({
...params,
}),
});

if (!response.ok) {
throw new APIError('Failed to request ai', await errorCauses(response));
}

return response.json() as Promise<AIResponse>;
};

export function useAI() {
return useMutation<AIResponse, APIError, AIParams>({
mutationFn: AI,
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import {
useBlockNoteEditor,
useComponentsContext,
useSelectedBlocks,
} from '@blocknote/react';
import { ReactNode, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { Box, Text } from '@/components';

import { AIActions, useAI } from '../api/useAI';

export function AIGroupButton() {
const editor = useBlockNoteEditor();
const Components = useComponentsContext();
const selectedBlocks = useSelectedBlocks(editor);
const { t } = useTranslation();

const show = useMemo(() => {
return !!selectedBlocks.find((block) => block.content !== undefined);
}, [selectedBlocks]);

if (!show || !editor.isEditable || !Components) {
return null;
}

return (
<Components.Generic.Menu.Root>
<Components.Generic.Menu.Trigger>
<Components.FormattingToolbar.Button
className="bn-button bn-menu-item"
data-test="ai-actions"
label="AI"
mainTooltip={t('AI Actions')}
>
AI
</Components.FormattingToolbar.Button>
</Components.Generic.Menu.Trigger>
<Components.Generic.Menu.Dropdown
className="bn-menu-dropdown bn-drag-handle-menu"
sub={true}
>
<AIMenuItem
action="prompt"
icon={
<Text $isMaterialIcon $size="s">
text_fields
</Text>
}
>
{t('Use as prompt')}
</AIMenuItem>
<AIMenuItem
action="rephrase"
icon={
<Text $isMaterialIcon $size="s">
refresh
</Text>
}
>
{t('Rephrase')}
</AIMenuItem>
<AIMenuItem
action="summarize"
icon={
<Text $isMaterialIcon $size="s">
summarize
</Text>
}
>
{t('Summarize')}
</AIMenuItem>
<AIMenuItem
action="correct"
icon={
<Text $isMaterialIcon $size="s">
check
</Text>
}
>
{t('Correct')}
</AIMenuItem>
<Components.Generic.Menu.Root position="right" sub={true}>
<Components.Generic.Menu.Trigger sub={false}>
<Components.Generic.Menu.Item
className="bn-menu-item"
subTrigger={true}
>
<Box $direction="row" $gap="0.6rem">
<Text $isMaterialIcon $size="s">
translate
</Text>
Language
</Box>
</Components.Generic.Menu.Item>
</Components.Generic.Menu.Trigger>
<Components.Generic.Menu.Dropdown
sub={false}
className="bn-menu-dropdown bn-drag-handle-menu"
>
<AIMenuItem action="translate_en">{t('English')}</AIMenuItem>
<AIMenuItem action="translate_fr">{t('French')}</AIMenuItem>
<AIMenuItem action="translate_de">{t('German')}</AIMenuItem>
</Components.Generic.Menu.Dropdown>
</Components.Generic.Menu.Root>
</Components.Generic.Menu.Dropdown>
</Components.Generic.Menu.Root>
);
}

interface AIMenuItemProps {
action: AIActions;
children: ReactNode;
icon?: ReactNode;
}

const AIMenuItem = ({ action, children, icon }: AIMenuItemProps) => {
const editor = useBlockNoteEditor();
const Components = useComponentsContext();
const { mutateAsync: requestAI, isPending } = useAI();

const handleAIAction = useCallback(async () => {
const selectedBlocks = editor.getSelection()?.blocks;

if (!selectedBlocks || selectedBlocks.length === 0) {
return;
}

const markdown = await editor.blocksToMarkdownLossy(selectedBlocks);
const responseAI = await requestAI({
text: markdown,
action,
});

if (!responseAI.answer) {
return;
}

const blockMarkdown = await editor.tryParseMarkdownToBlocks(
responseAI.answer,
);
editor.replaceBlocks(selectedBlocks, blockMarkdown);
}, [editor, requestAI, action]);

if (!Components) {
return null;
}

return (
<Components.Generic.Menu.Item
closeMenuOnClick={false}
icon={icon}
onClick={() => void handleAIAction()}
rightSection={isPending ? <Box className="loader" /> : undefined}
>
{children}
</Components.Generic.Menu.Item>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,18 @@ import {
import { forEach, isArray } from 'lodash';
import React, { useMemo } from 'react';

import { AIGroupButton } from './AIButton';

export const BlockNoteToolbar = () => {
return (
<FormattingToolbarController
formattingToolbar={() => (
<FormattingToolbar>
<BlockTypeSelect key="blockTypeSelect" />

{/* Extra button to do some AI powered actions */}
<AIGroupButton key="AIButton" />

{/* Extra button to convert from markdown to json */}
<MarkdownButton key="customButton" />

Expand Down
11 changes: 10 additions & 1 deletion src/frontend/apps/impress/src/i18n/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,16 @@
"accessibility-dinum-services": "<strong>DINUM</strong> s'engage à rendre accessibles ses services numériques, conformément à l'article 47 de la loi n° 2005-102 du 11 février 2005.",
"accessibility-form-defenseurdesdroits": "Écrire un message au<1>Défenseur des droits</1>",
"accessibility-not-audit": "<strong>docs.numerique.gouv.fr</strong> n'est pas en conformité avec le RGAA 4.1. Le site n'a <strong>pas encore été audité.</strong>",
"you have reported to the website manager a lack of accessibility that prevents you from accessing content or one of the services of the portal and you have not received a satisfactory response.": "vous avez signalé au responsable du site internet un défaut d'accessibilité qui vous empêche d'accéder à un contenu ou à un des services du portail et vous n'avez pas obtenu de réponse satisfaisante."
"you have reported to the website manager a lack of accessibility that prevents you from accessing content or one of the services of the portal and you have not received a satisfactory response.": "vous avez signalé au responsable du site internet un défaut d'accessibilité qui vous empêche d'accéder à un contenu ou à un des services du portail et vous n'avez pas obtenu de réponse satisfaisante.",
"AI Actions": "Actions IA",
"Use as prompt": "Utiliser comme prompt",
"Rephrase": "Reformuler",
"Summarize": "Résumer",
"Correct": "Corriger",
"Translate": "Traduire",
"English": "Anglais",
"French": "Français",
"German": "Allemand"
}
}
}
14 changes: 14 additions & 0 deletions src/frontend/apps/impress/src/pages/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,17 @@ main ::-webkit-scrollbar-thumb:hover,
cursor: pointer;
outline: inherit;
}

.loader {
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 71%;
width: 20px;
height: 20px;
animation: spin 1s linear infinite;
}

@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}

0 comments on commit 01d279c

Please sign in to comment.