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

feat(chat): add brain selection through mention input #969

Merged
merged 10 commits into from
Aug 22, 2023
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChatInput } from "../ChatInput";
import { ChatInput } from "./components";

export const ActionsBar = (): JSX.Element => {
return (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"use client";

import { MentionInput } from "./components";

type ChatBarProps = {
onSubmit: () => void;
setMessage: (text: string) => void;
message: string;
};

export const ChatBar = ({
onSubmit,
setMessage,
message,
}: ChatBarProps): JSX.Element => {
return (
<MentionInput
message={message}
setMessage={setMessage}
onSubmit={onSubmit}
/>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,16 @@ import { MdRemoveCircleOutline } from "react-icons/md";
type MentionItemProps = {
text: string;
onRemove: () => void;
prefix?: string;
};

export const MentionItem = ({
export const BrainMentionItem = ({
text,
prefix = "",
onRemove,
}: MentionItemProps): JSX.Element => {
return (
<div className="relative">
<div className="relative inline-block w-fit-content">
<div className="flex items-center bg-gray-300 mr-2 text-gray-600 rounded-2xl py-1 px-2">
<span className="flex-grow">{`${prefix}${text}`}</span>
<span className="flex-grow">@{text}</span>
<MdRemoveCircleOutline
className="cursor-pointer absolute top-[-10px] right-[5px]"
onClick={onRemove}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import Editor from "@draft-js-plugins/editor";
import { ReactElement } from "react";
import { useTranslation } from "react-i18next";

import "@draft-js-plugins/mention/lib/plugin.css";
import "draft-js/dist/Draft.css";

import { SuggestionRow } from "./components/SuggestionRow";
import { SuggestionsContainer } from "./components/SuggestionsContainer";
import { useMentionInput } from "./hooks/useMentionInput";

type MentionInputProps = {
onSubmit: () => void;
setMessage: (text: string) => void;
message: string;
};
export const MentionInput = ({
onSubmit,
setMessage,
message,
}: MentionInputProps): ReactElement => {
const {
mentionInputRef,
MentionSuggestions,
keyBindingFn,
editorState,
onOpenChange,
onSearchChange,
open,
plugins,
suggestions,
onAddMention,
handleEditorChange,
} = useMentionInput({
message,
onSubmit,
setMessage,
});

const { t } = useTranslation(["chat"]);

return (
<div className="w-full" data-testid="chat-input">
<Editor
editorKey={"editor"}
editorState={editorState}
onChange={handleEditorChange}
plugins={plugins}
ref={mentionInputRef}
placeholder={t("actions_bar_placeholder")}
keyBindingFn={keyBindingFn}
/>
<MentionSuggestions
open={open}
onOpenChange={onOpenChange}
suggestions={suggestions}
onSearchChange={onSearchChange}
popoverContainer={SuggestionsContainer}
onAddMention={onAddMention}
entryComponent={SuggestionRow}
/>
</div>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import Link from "next/link";
import { useTranslation } from "react-i18next";

import Button from "@/lib/components/ui/Button";

export const AddNewBrainButton = (): JSX.Element => {
const { t } = useTranslation(["chat"]);

return (
<Link
href={"/brains-management"}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
>
<Button className="px-5 py-2 text-sm" variant={"tertiary"}>
{t("new_brain")}
</Button>
</Link>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
type BrainSuggestionProps = {
content: string;
id: string;
};
export const BrainSuggestion = ({
content,
id,
}: BrainSuggestionProps): JSX.Element => {
//TODO: use this id for ShareBrain component
console.log({ id });

return (
<div className="relative flex group items-center">
<div
className={
"flex flex-1 items-center gap-2 w-full text-left px-5 py-2 text-sm leading-5 text-gray-900 dark:text-gray-300 group-hover:bg-gray-100 dark:group-hover:bg-gray-700 group-focus:bg-gray-100 dark:group-focus:bg-gray-700 group-focus:outline-none transition-colors"
}
>
<span className="flex-1">{content}</span>
</div>
</div>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { EntryComponentProps } from "@draft-js-plugins/mention/lib/MentionSuggestions/Entry/Entry";

import { BrainSuggestion } from "./BrainSuggestion";

export const SuggestionRow = ({
mention,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
className,
...otherProps
}: EntryComponentProps): JSX.Element => (
<div {...otherProps}>
<BrainSuggestion id={mention.id as string} content={mention.name} />
</div>
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Popover } from "@draft-js-plugins/mention";
import { PopoverProps } from "@draft-js-plugins/mention/lib/MentionSuggestions/Popover";

export const SuggestionsContainer = ({
children,
...popoverProps
}: PopoverProps): JSX.Element => (
<Popover {...popoverProps}>
<div
style={{
maxWidth: "max-content",
}}
className="bg-white dark:bg-black border border-black/10 dark:border-white/25 rounded-md shadow-md overflow-y-auto"
>
{children}
</div>
</Popover>
);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./AddNewBrainButton";
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import createMentionPlugin from "@draft-js-plugins/mention";
import { useMemo } from "react";

import { useBrainContext } from "@/lib/context/BrainProvider/hooks/useBrainContext";

import { BrainMentionItem } from "../../../BrainMentionItem";

interface MentionPluginProps {
removeMention: (entityKeyToRemove: string) => void;
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const useMentionPlugin = (props: MentionPluginProps) => {
const { removeMention } = props;
const { setCurrentBrainId } = useBrainContext();

const { MentionSuggestions, plugins } = useMemo(() => {
const mentionPlugin = createMentionPlugin({
mentionComponent: ({ entityKey, mention: { name } }) => (
<BrainMentionItem
text={name}
onRemove={() => {
setCurrentBrainId(null);
removeMention(entityKey);
}}
/>
),

popperOptions: {
placement: "top-end",
modifiers: [
{
name: "customStyle", // Custom modifier for applying styles
enabled: true,
phase: "beforeWrite",
fn: ({ state }) => {
state.styles.popper = {
...state.styles.popper,
minWidth: "auto",
backgroundColor: "transparent",
padding: "0",
marginBottom: "5",
};
},
},
],
},
});
const { MentionSuggestions: LegacyMentionSuggestions } = mentionPlugin;
const legacyPlugins = [mentionPlugin];

return {
plugins: legacyPlugins,
MentionSuggestions: LegacyMentionSuggestions,
};
}, []);

return { MentionSuggestions, plugins };
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { EditorState } from "draft-js";
import { useEffect, useState } from "react";

import { MentionTriggerType } from "@/app/chat/[chatId]/components/ActionsBar/types";
import { useBrainContext } from "@/lib/context/BrainProvider/hooks/useBrainContext";

import { MentionInputMentionsType, TriggerMap } from "../../../../types";
import { mapMinimalBrainToMentionData } from "../../utils/mapMinimalBrainToMentionData";

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const useMentionState = () => {
const { allBrains } = useBrainContext();
const [editorState, legacySetEditorState] = useState(() =>
EditorState.createEmpty()
);

const [mentionItems, setMentionItems] = useState<MentionInputMentionsType>({
"@": allBrains.map((brain) => ({ ...brain, value: brain.name })),
});

const [suggestions, setSuggestions] = useState(
mapMinimalBrainToMentionData(mentionItems["@"])
);

const setEditorState = (newState: EditorState) => {
const currentSelection = newState.getSelection();
const stateWithContentAndSelection = EditorState.forceSelection(
newState,
currentSelection
);

legacySetEditorState(stateWithContentAndSelection);
};

const getEditorCurrentMentions = (): TriggerMap[] => {
const contentState = editorState.getCurrentContent();
const plainText = contentState.getPlainText();
const mentionTriggers = Object.keys(mentionItems);

const mentionTexts: TriggerMap[] = [];

mentionTriggers.forEach((trigger) => {
if (trigger === "@") {
mentionItems["@"].forEach((item) => {
const mentionText = `${trigger}${item.name}`;
if (plainText.includes(mentionText)) {
mentionTexts.push({
trigger: trigger as MentionTriggerType,
content: item.name,
});
}
});
}
});

return mentionTexts;
};

const getEditorTextWithoutMentions = (
editorCurrentState: EditorState
): string => {
const contentState = editorCurrentState.getCurrentContent();
let plainText = contentState.getPlainText();
Object.keys(mentionItems).forEach((trigger) => {
if (trigger === "@") {
mentionItems[trigger].forEach((item) => {
const regex = new RegExp(`${trigger}${item.name}`, "g");
plainText = plainText.replace(regex, "");
});
}
});

return plainText;
};

useEffect(() => {
setMentionItems({
...mentionItems,
"@": [
...allBrains.map((brain) => ({
...brain,
value: brain.name,
})),
],
});
}, [allBrains]);

return {
editorState,
setEditorState,
mentionItems,
setSuggestions,
setMentionItems,
suggestions,
getEditorCurrentMentions,
getEditorTextWithoutMentions,
};
};
Loading
Loading