Make WYSIWYG editor reusable (#6293)

* make text editor reusable

* use dropdown component for block type

* remove ring when clicking on block type

* allow excluding items in toolbar

* refactor code

* make AddVariableDropdown reusable

* fixed missed translations

* fixes variable translation issue

* change missed translation variables

* make AddVariablesDropdown reusable

* reorder block types in dropdown

* remove not needed prop

* code clean up

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2023-01-09 14:15:11 +00:00
1 parent 112d504148
commit a0135cdc59
46 files changed
+415 -420

No files matched your search

@@ -72,13 +72,13 @@ const WorkflowListItem = (props: ItemProps) => {
workflow.steps.forEach((step) => {
switch (step.action) {
case WorkflowActions.EMAIL_HOST:
sendTo.add(t("organizer_name_workflow"));
sendTo.add(t("organizer_name_variable"));
break;
case WorkflowActions.EMAIL_ATTENDEE:
sendTo.add(t("attendee_name_workflow"));
sendTo.add(t("attendee_name_variable"));
break;
case WorkflowActions.SMS_ATTENDEE:
sendTo.add(t("attendee_name_workflow"));
sendTo.add(t("attendee_name_variable"));
break;
case WorkflowActions.SMS_NUMBER:
sendTo.add(step.sendTo || "");
@@ -34,13 +34,13 @@ import {
showToast,
TextArea,
TextField,
Editor,
AddVariablesDropdown,
} from "@calcom/ui";
import { AddVariablesDropdown } from "../components/AddVariablesDropdown";
import { getWorkflowTemplateOptions, getWorkflowTriggerOptions } from "../lib/getOptions";
import { translateVariablesToEnglish } from "../lib/variableTranslations";
import type { FormValues } from "../pages/workflow";
import Editor from "./TextEditor/Editor";
import { TimeTimeUnitInput } from "./TimeTimeUnitInput";
type WorkflowStepProps = {
@@ -50,6 +50,18 @@ type WorkflowStepProps = {
setReload?: Dispatch<SetStateAction<boolean>>;
};
const dynamicTextVariables = [
"event_name",
"event_date",
"event_time",
"location",
"organizer_name",
"attendee_name",
"attendee_email",
"additional_notes",
"meeting_url",
];
export default function WorkflowStepContainer(props: WorkflowStepProps) {
const { t, i18n } = useLocale();
const utils = trpc.useContext();
@@ -117,23 +129,25 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
: false
);
const addVariable = (variable: string, isEmailSubject?: boolean) => {
const addVariableBody = (variable: string) => {
if (step) {
if (isEmailSubject) {
const currentEmailSubject = refEmailSubject?.current?.value || "";
const cursorPosition = refEmailSubject?.current?.selectionStart || currentEmailSubject.length;
const subjectWithAddedVariable = `${currentEmailSubject.substring(0, cursorPosition)}{${variable
.toUpperCase()
.replace(/ /g, "_")}}${currentEmailSubject.substring(cursorPosition)}`;
form.setValue(`steps.${step.stepNumber - 1}.emailSubject`, subjectWithAddedVariable);
} else {
const currentMessageBody = refReminderBody?.current?.value || "";
const cursorPosition = refReminderBody?.current?.selectionStart || currentMessageBody.length;
const messageWithAddedVariable = `${currentMessageBody.substring(0, cursorPosition)}{${variable
.toUpperCase()
.replace(/ /g, "_")}}${currentMessageBody.substring(cursorPosition)}`;
form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, messageWithAddedVariable);
}
const currentMessageBody = refReminderBody?.current?.value || "";
const cursorPosition = refReminderBody?.current?.selectionStart || currentMessageBody.length;
const messageWithAddedVariable = `${currentMessageBody.substring(0, cursorPosition)}{${variable
.toUpperCase()
.replace(/ /g, "_")}}${currentMessageBody.substring(cursorPosition)}`;
form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, messageWithAddedVariable);
}
};
const addVariableEmailSubject = (variable: string) => {
if (step) {
const currentEmailSubject = refEmailSubject?.current?.value || "";
const cursorPosition = refEmailSubject?.current?.selectionStart || currentEmailSubject.length;
const subjectWithAddedVariable = `${currentEmailSubject.substring(0, cursorPosition)}{${variable
.toUpperCase()
.replace(/ /g, "_")}}${currentEmailSubject.substring(cursorPosition)}`;
form.setValue(`steps.${step.stepNumber - 1}.emailSubject`, subjectWithAddedVariable);
}
};
@@ -541,7 +555,10 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
<div className="flex items-center">
<Label className="mb-0 flex-none">{t("subject")}</Label>
<div className="flex-grow text-right">
<AddVariablesDropdown addVariable={addVariable} isEmailSubject={true} />
<AddVariablesDropdown
addVariable={addVariableEmailSubject}
variables={dynamicTextVariables}
/>
</div>
</div>
<TextArea
@@ -571,7 +588,16 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
{isEmailSubjectNeeded ? t("email_body") : t("text_message")}
</Label>
</div>
<Editor form={form} stepNumber={step.stepNumber} />
<Editor
getText={() => {
return props.form.getValues(`steps.${step.stepNumber - 1}.reminderBody`) || "";
}}
setText={(text: string) => {
props.form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, text);
props.form.clearErrors();
}}
variables={dynamicTextVariables}
/>
</>
) : (
<>
@@ -580,7 +606,10 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
{isEmailSubjectNeeded ? t("email_body") : t("text_message")}
</Label>
<div className="flex-grow text-right">
<AddVariablesDropdown addVariable={addVariable} isEmailSubject={false} />
<AddVariablesDropdown
addVariable={addVariableBody}
variables={dynamicTextVariables}
/>
</div>
</div>
<TextArea
@@ -1,15 +1,15 @@
import { TFunction } from "next-i18next";
const originalVariables = [
"event_name_workflow",
"organizer_name_workflow",
"attendee_name_workflow",
"event_date_workflow",
"event_time_workflow",
"location_workflow",
"additional_notes_workflow",
"attendee_email_workflow",
"meeting_url_workflow",
"event_name_variable",
"organizer_name_variable",
"attendee_name_variable",
"event_date_variable",
"event_time_variable",
"location_variable",
"additional_notes_variable",
"attendee_email_variable",
"meeting_url_variable",
];
export function getTranslatedText(text: string, language: { locale: string; t: TFunction }) {
@@ -21,14 +21,14 @@ export function getTranslatedText(text: string, language: { locale: string; t: T
});
variables?.forEach((variable) => {
const regex = new RegExp(variable, "g"); // .replaceAll is not available here for some reason
const translatedVariable = originalVariables.includes(variable.toLowerCase().concat("_workflow"))
? language.t(variable.toLowerCase().concat("_workflow")).replace(/ /g, "_").toLocaleUpperCase()
: originalVariables.includes(variable.toLowerCase().concat("_name_workflow")) //for the old variables names (ORGANIZER_NAME, ATTENDEE_NAME)
? language.t(variable.toLowerCase().concat("_name_workflow")).replace(/ /g, "_").toLocaleUpperCase()
const regex = new RegExp(`{${variable}}`, "g"); // .replaceAll is not available here for some reason
const translatedVariable = originalVariables.includes(variable.toLowerCase().concat("_variable"))
? language.t(variable.toLowerCase().concat("_variable")).replace(/ /g, "_").toLocaleUpperCase()
: originalVariables.includes(variable.toLowerCase().concat("_name_variable")) //for the old variables names (ORGANIZER_NAME, ATTENDEE_NAME)
? language.t(variable.toLowerCase().concat("_name_variable")).replace(/ /g, "_").toLocaleUpperCase()
: variable;
translatedText = translatedText.replace(regex, translatedVariable);
translatedText = translatedText.replace(regex, `{${translatedVariable}}`);
});
}
@@ -11,28 +11,32 @@ import { MarkdownShortcutPlugin } from "@lexical/react/LexicalMarkdownShortcutPl
import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
import { HeadingNode, QuoteNode } from "@lexical/rich-text";
import { TableCellNode, TableNode, TableRowNode } from "@lexical/table";
import { UseFormReturn } from "react-hook-form";
import { FormValues } from "../../pages/workflow";
import ExampleTheme from "./ExampleTheme";
import AutoLinkPlugin from "./plugins/AutoLinkPlugin";
import ToolbarPlugin from "./plugins/ToolbarPlugin";
import "./stylesEditor.css";
/*
Detault toolbar items:
- blockType
- bold
- italic
- link
*/
export type TextEditorProps = {
form: UseFormReturn<FormValues>;
stepNumber: number;
getText: () => string;
setText: (text: string) => void;
excludedToolbarItems?: string[];
variables?: string[];
};
const editorConfig = {
// The editor theme
theme: ExampleTheme,
// Handling of errors during update
onError(error: any) {
throw error;
},
namespace: "",
// Any custom nodes go here
nodes: [
HeadingNode,
ListNode,
@@ -48,12 +52,17 @@ const editorConfig = {
],
};
export default function Editor(props: TextEditorProps) {
export const Editor = (props: TextEditorProps) => {
return (
<div className="editor">
<LexicalComposer initialConfig={editorConfig}>
<div className="editor-container">
<ToolbarPlugin form={props.form} stepNumber={props.stepNumber} />
<ToolbarPlugin
getText={props.getText}
setText={props.setText}
excludedToolbarItems={props.excludedToolbarItems}
variables={props.variables}
/>
<div className="editor-inner">
<RichTextPlugin contentEditable={<ContentEditable className="editor-input" />} placeholder="" />
<AutoFocusPlugin />
@@ -66,4 +75,4 @@ export default function Editor(props: TextEditorProps) {
</LexicalComposer>
</div>
);
}
};
+2
View File
@@ -0,0 +1,2 @@
export { Editor } from "./Editor";
export { AddVariablesDropdown } from "./plugins/AddVariablesDropdown";
@@ -2,23 +2,11 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Dropdown, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, Icon } from "@calcom/ui";
interface IAddVariablesDropdown {
addVariable: (variable: string, isEmailSubject?: boolean) => void;
isEmailSubject?: boolean;
addVariable: (variable: string) => void;
isTextEditor?: boolean;
variables: string[];
}
const variables = [
"event_name",
"event_date",
"event_time",
"location",
"organizer_name",
"attendee_name",
"attendee_email",
"additional_notes",
"meeting_url",
];
export const AddVariablesDropdown = (props: IAddVariablesDropdown) => {
const { t } = useLocale();
@@ -47,16 +35,16 @@ export const AddVariablesDropdown = (props: IAddVariablesDropdown) => {
<div className="mb-2 px-4 text-left text-xs text-gray-500">
{t("add_dynamic_variables").toLocaleUpperCase()}
</div>
{variables.map((variable) => (
{props.variables.map((variable) => (
<DropdownMenuItem key={variable} className="hover:ring-0">
<button
key={variable}
type="button"
className="w-full px-4 py-2"
onClick={() => props.addVariable(t(`${variable}_workflow`), props.isEmailSubject)}>
onClick={() => props.addVariable(t(`${variable}_variable`))}>
<div className="sm:grid sm:grid-cols-2">
<div className="mr-3 text-left md:col-span-1">
{`{${t(`${variable}_workflow`).toUpperCase().replace(/ /g, "_")}}`}
{`{${t(`${variable}_variable`).toUpperCase().replace(/ /g, "_")}}`}
</div>
<div className="hidden text-left text-gray-600 sm:col-span-1 sm:flex">
{t(`${variable}_info`)}
@@ -11,6 +11,7 @@ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext
import { $createHeadingNode, $isHeadingNode } from "@lexical/rich-text";
import { $wrapNodes, $isAtNodeEnd } from "@lexical/selection";
import { $getNearestNodeOfType, mergeRegister } from "@lexical/utils";
import classNames from "classnames";
import {
SELECTION_CHANGE_COMMAND,
FORMAT_TEXT_COMMAND,
@@ -25,14 +26,20 @@ import {
LexicalEditor,
EditorState,
} from "lexical";
import { RefObject, Dispatch, SetStateAction } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Icon } from "@calcom/ui";
import {
Icon,
Dropdown,
DropdownMenuTrigger,
DropdownMenuItem,
DropdownMenuContent,
Button,
} from "@calcom/ui";
import { AddVariablesDropdown } from "../../AddVariablesDropdown";
import { TextEditorProps } from "../Editor";
import { AddVariablesDropdown } from "./AddVariablesDropdown";
const LowPriority = 1;
@@ -43,11 +50,11 @@ interface BlockType {
}
const blockTypeToBlockName: BlockType = {
paragraph: "Normal",
ol: "Numbered List",
ul: "Bulleted List",
h1: "Large Heading",
h2: "Small Heading",
ol: "Numbered List",
paragraph: "Normal",
ul: "Bulleted List",
};
function positionEditorElement(editor: HTMLInputElement, rect: DOMRect | null) {
@@ -220,51 +227,13 @@ function getSelectedNode(selection: RangeSelection) {
}
}
type BlockOptionsDropdownProps = {
editor: LexicalEditor;
blockType: string;
toolbarRef: RefObject<HTMLDivElement>;
setShowBlockOptionsDropDown: Dispatch<SetStateAction<boolean>>;
};
function BlockOptionsDropdownList({
editor,
blockType,
toolbarRef,
setShowBlockOptionsDropDown,
}: BlockOptionsDropdownProps) {
const dropDownRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const toolbar = toolbarRef.current;
const dropDown = dropDownRef.current;
if (toolbar !== null && dropDown) {
const { top, left } = toolbar.getBoundingClientRect();
dropDown.style.top = `${top + 40}px`;
dropDown.style.left = `${left}px`;
}
}, [dropDownRef, toolbarRef]);
useEffect(() => {
const dropDown = dropDownRef.current;
const toolbar = toolbarRef.current;
if (dropDown && toolbar !== null) {
const handle = (event: any) => {
const target = event.target;
if (!dropDown.contains(target) && !toolbar.contains(target)) {
setShowBlockOptionsDropDown(false);
}
};
document.addEventListener("click", handle);
return () => {
document.removeEventListener("click", handle);
};
}
}, [dropDownRef, setShowBlockOptionsDropDown, toolbarRef]);
export default function ToolbarPlugin(props: TextEditorProps) {
const [editor] = useLexicalComposerContext();
const toolbarRef = useRef(null);
const [blockType, setBlockType] = useState("paragraph");
const [isLink, setIsLink] = useState(false);
const [isBold, setIsBold] = useState(false);
const [isItalic, setIsItalic] = useState(false);
const formatParagraph = () => {
if (blockType !== "paragraph") {
@@ -276,7 +245,6 @@ function BlockOptionsDropdownList({
}
});
}
setShowBlockOptionsDropDown(false);
};
const formatLargeHeading = () => {
@@ -289,7 +257,6 @@ function BlockOptionsDropdownList({
}
});
}
setShowBlockOptionsDropDown(false);
};
const formatSmallHeading = () => {
@@ -302,7 +269,6 @@ function BlockOptionsDropdownList({
}
});
}
setShowBlockOptionsDropDown(false);
};
const formatBulletList = () => {
@@ -311,7 +277,6 @@ function BlockOptionsDropdownList({
} else {
editor.dispatchCommand(REMOVE_LIST_COMMAND, undefined);
}
setShowBlockOptionsDropDown(false);
};
const formatNumberedList = () => {
@@ -320,48 +285,27 @@ function BlockOptionsDropdownList({
} else {
editor.dispatchCommand(REMOVE_LIST_COMMAND, undefined);
}
setShowBlockOptionsDropDown(false);
};
return (
<div className="dropdown" ref={dropDownRef}>
<button type="button" className="item" onClick={formatParagraph}>
<span className="icon paragraph" />
<span className="text">Normal</span>
{blockType === "paragraph" && <span className="active" />}
</button>
<button type="button" className="item" onClick={formatBulletList}>
<span className="icon bullet-list" />
<span className="text">Bullet List</span>
{blockType === "ul" && <span className="active" />}
</button>
<button type="button" className="item" onClick={formatNumberedList}>
<span className="icon numbered-list" />
<span className="text">Numbered List</span>
{blockType === "ol" && <span className="active" />}
</button>
<button type="button" className="item" onClick={formatLargeHeading}>
<span className="icon large-heading" />
<span className="text">Large Heading</span>
{blockType === "h1" && <span className="active" />}
</button>
<button type="button" className="item" onClick={formatSmallHeading}>
<span className="icon small-heading" />
<span className="text">Small Heading</span>
{blockType === "h2" && <span className="active" />}
</button>
</div>
);
}
export default function ToolbarPlugin(props: TextEditorProps) {
const [editor] = useLexicalComposerContext();
const toolbarRef = useRef(null);
const [blockType, setBlockType] = useState("paragraph");
const [showBlockOptionsDropDown, setShowBlockOptionsDropDown] = useState(false);
const [isLink, setIsLink] = useState(false);
const [isBold, setIsBold] = useState(false);
const [isItalic, setIsItalic] = useState(false);
const format = (newBlockType: string) => {
switch (newBlockType) {
case "paragraph":
formatParagraph();
break;
case "ul":
formatBulletList();
break;
case "ol":
formatNumberedList();
break;
case "h1":
formatLargeHeading();
break;
case "h2":
formatSmallHeading();
break;
}
};
const updateToolbar = useCallback(() => {
const selection = $getSelection();
@@ -408,10 +352,7 @@ export default function ToolbarPlugin(props: TextEditorProps) {
useEffect(() => {
editor.update(() => {
const parser = new DOMParser();
const dom = parser.parseFromString(
props.form.getValues(`steps.${props.stepNumber - 1}.reminderBody`) || "",
"text/html"
);
const dom = parser.parseFromString(props.getText(), "text/html");
const nodes = $generateNodesFromDOM(editor, dom);
@@ -421,8 +362,7 @@ export default function ToolbarPlugin(props: TextEditorProps) {
editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
const textInHtml = $generateHtmlFromNodes(editor);
props.form.setValue(`steps.${props.stepNumber - 1}.reminderBody`, textInHtml);
props.form.clearErrors();
props.setText(textInHtml);
});
});
});
@@ -457,69 +397,94 @@ export default function ToolbarPlugin(props: TextEditorProps) {
return (
<div className="toolbar flex" ref={toolbarRef}>
<>
{supportedBlockTypes.has(blockType) && (
{!props.excludedToolbarItems?.includes("blockType") && supportedBlockTypes.has(blockType) && (
<>
<button
type="button"
className="toolbar-item block-controls"
onClick={() => setShowBlockOptionsDropDown(!showBlockOptionsDropDown)}
aria-label="Formatting Options">
<span className={"icon block-type " + blockType} />
<span className="text hidden sm:flex">
{blockTypeToBlockName[blockType as keyof BlockType]}
</span>
<Icon.FiChevronDown className="h-4 w-4" />
</button>
{showBlockOptionsDropDown &&
createPortal(
<BlockOptionsDropdownList
editor={editor}
blockType={blockType}
toolbarRef={toolbarRef}
setShowBlockOptionsDropDown={setShowBlockOptionsDropDown}
/>,
document.body
)}
<Dropdown>
<DropdownMenuTrigger className="toolbar-item w-36 text-gray-500">
<>
<span className={"icon block-type " + blockType} />
<span className="text hidden text-gray-700 sm:flex">
{blockTypeToBlockName[blockType as keyof BlockType]}
</span>
<Icon.FiChevronDown className="ml-2 h-4 w-4 text-gray-700" />
</>
</DropdownMenuTrigger>
<DropdownMenuContent>
{Object.keys(blockTypeToBlockName).map((key) => {
return (
<DropdownMenuItem key={key} className="outline-none hover:ring-0 focus:ring-0">
<Button
color="minimal"
type="button"
onClick={() => format(key)}
className={classNames(
"toolbar-item w-full focus:ring-0",
blockType === key ? "w-full bg-gray-100" : ""
)}>
<>
<span className={"icon block-type " + key} />
<span>{blockTypeToBlockName[key]}</span>
</>
</Button>
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</Dropdown>
</>
)}
<>
<button
type="button"
onClick={() => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "bold");
if (isItalic) {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");
}
}}
className={"toolbar-item spaced " + (isBold ? "active" : "")}
aria-label="Format Bold">
<i className="format bold" />
</button>
<button
type="button"
onClick={() => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");
if (isBold) {
{!props.excludedToolbarItems?.includes("bold") && (
<button
type="button"
onClick={() => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "bold");
}
}}
className={"toolbar-item spaced " + (isItalic ? "active" : "")}
aria-label="Format Italics">
<i className="format italic" />
</button>
<button
type="button"
onClick={insertLink}
className={"toolbar-item spaced " + (isLink ? "active" : "")}
aria-label="Insert Link">
<i className="format link" />
</button>
{isLink && createPortal(<FloatingLinkEditor editor={editor} />, document.body)}{" "}
if (isItalic) {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");
}
}}
className={"toolbar-item spaced " + (isBold ? "active" : "")}
aria-label="Format Bold">
<i className="format bold" />
</button>
)}
{!props.excludedToolbarItems?.includes("italic") && (
<button
type="button"
onClick={() => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");
if (isBold) {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "bold");
}
}}
className={"toolbar-item spaced " + (isItalic ? "active" : "")}
aria-label="Format Italics">
<i className="format italic" />
</button>
)}
{!props.excludedToolbarItems?.includes("link") && (
<>
<button
type="button"
onClick={insertLink}
className={"toolbar-item spaced " + (isLink ? "active" : "")}
aria-label="Insert Link">
<i className="format link" />
</button>
{isLink && createPortal(<FloatingLinkEditor editor={editor} />, document.body)}{" "}
</>
)}
</>
<div className="ml-auto">
<AddVariablesDropdown addVariable={addVariable} isEmailSubject={false} isTextEditor={true} />
</div>
{props.variables && (
<div className="ml-auto">
<AddVariablesDropdown
addVariable={addVariable}
isTextEditor={true}
variables={props.variables || []}
/>
</div>
)}
</>
</div>
);
@@ -129,7 +129,6 @@ pre::-webkit-scrollbar-thumb {
.toolbar button.toolbar-item {
border: 0;
display: flex;
background: none;
border-radius: 10px;
padding: 8px;
cursor: pointer;
+1
View File
@@ -56,6 +56,7 @@ export { List, ListItem, ListItemText, ListItemTitle, ListLinkItem } from "./lis
export type { ListItemProps, ListProps } from "./list";
export { HeadSeo } from "./head-seo";
export { Skeleton, SkeletonAvatar, SkeletonButton, SkeletonContainer, SkeletonText } from "./skeleton";
export { Editor, AddVariablesDropdown } from "./editor";
export {
Dialog,
DialogClose,
+2
View File
@@ -57,6 +57,8 @@ export {
AppStoreCategories,
Slider,
useShouldShowArrows,
Editor,
AddVariablesDropdown,
Dialog,
DialogClose,
DialogContent,