Text editor for custom workflow templates (#5654)

* add first version of text editor

* add new editor to email body

* fix line height

* remove not needed styles

* allow adding html tags + small refactoring

* fix error when input is empty

* styling of add variable dropdown

* fix bg on focus

* small design fixes

* improve design

* show error message for no input

* text editor only for email body

* remove test button

* code clean up

* code clean up

* code clean up

* fix that added variables weren't saved

* fix import

* first version of editor

* connect reminder body of form with new editor

* add pencile for link-editor

* remove TreeViewPlugin

* clean up css file

* code clean up

* add text indent for list

* improve editor design

* fix style

* slow resizing of editor

* fix that new data was removed when leaving tab

* dont allow italic and bold at same time

* code clean up

* fix type error

* code clean up

* code clean up

* remove text if changed from SMS to email or other way around

* add add variable dropdown

* show error message if email body is empty

* add white-space pre-wrap

* fix import

* prettier

* fix add variable dropdown for mobile

* move dependencies to correct package.json file

* remove html-to-text

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
This commit is contained in:
Carina Wollendorfer
2022-11-25 07:34:55 -07:00
committed by GitHub
co-authored by CarinaWolli
parent 3137a188a0
commit 2de3e7fc59
20 changed files with 1207 additions and 56 deletions
@@ -1375,5 +1375,6 @@
"route_to": "Route to",
"test_preview_description": "Test your routing form without submitting any data",
"test_routing": "Test Routing",
"booking_limit_reached":"Booking Limit for this event type has been reached"
"booking_limit_reached":"Booking Limit for this event type has been reached",
"fill_this_field": "Please fill in this field"
}
@@ -2,8 +2,9 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Dropdown, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, Icon } from "@calcom/ui";
interface IAddVariablesDropdown {
addVariable: (isEmailSubject: boolean, variable: string) => void;
isEmailSubject: boolean;
addVariable: (variable: string, isEmailSubject?: boolean) => void;
isEmailSubject?: boolean;
isTextEditor?: boolean;
}
const variables = [
@@ -23,9 +24,21 @@ export const AddVariablesDropdown = (props: IAddVariablesDropdown) => {
return (
<Dropdown>
<DropdownMenuTrigger className="pt-[6px] focus:bg-gray-50">
<div className="flex items-center ">
{t("add_variable")}
<Icon.FiChevronDown className="ml-1 h-4 w-4" />
<div className="items-center ">
{props.isTextEditor ? (
<>
<div className="hidden sm:flex">
{t("add_variable")}
<Icon.FiChevronDown className="ml-1 h-4 w-4" />
</div>
<div className="block sm:hidden">+</div>
</>
) : (
<div className="flex">
{t("add_variable")}
<Icon.FiChevronDown className="ml-1 h-4 w-4" />
</div>
)}
</div>
</DropdownMenuTrigger>
<DropdownMenuContent className="h-40 overflow-scroll">
@@ -39,7 +52,7 @@ export const AddVariablesDropdown = (props: IAddVariablesDropdown) => {
key={variable}
type="button"
className="w-full px-4 py-2"
onClick={() => props.addVariable(props.isEmailSubject, t(`${variable}_workflow`))}>
onClick={() => props.addVariable(t(`${variable}_workflow`), props.isEmailSubject)}>
<div className="sm:grid sm:grid-cols-2">
<div className="mr-3 text-left md:col-span-1">
{`{${t(`${variable}_workflow`).toUpperCase().replace(/ /g, "_")}}`}
@@ -0,0 +1,69 @@
import { CodeHighlightNode, CodeNode } from "@lexical/code";
import { AutoLinkNode, LinkNode } from "@lexical/link";
import { ListItemNode, ListNode } from "@lexical/list";
import { TRANSFORMERS } from "@lexical/markdown";
import { AutoFocusPlugin } from "@lexical/react/LexicalAutoFocusPlugin";
import { LexicalComposer } from "@lexical/react/LexicalComposer";
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";
import { ListPlugin } from "@lexical/react/LexicalListPlugin";
import { MarkdownShortcutPlugin } from "@lexical/react/LexicalMarkdownShortcutPlugin";
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";
export type TextEditorProps = {
form: UseFormReturn<FormValues>;
stepNumber: number;
};
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,
ListItemNode,
QuoteNode,
CodeNode,
CodeHighlightNode,
TableNode,
TableCellNode,
TableRowNode,
AutoLinkNode,
LinkNode,
],
};
export default function Editor(props: TextEditorProps) {
return (
<div className="editor">
<LexicalComposer initialConfig={editorConfig}>
<div className="editor-container">
<ToolbarPlugin form={props.form} stepNumber={props.stepNumber} />
<div className="editor-inner">
<RichTextPlugin contentEditable={<ContentEditable className="editor-input" />} placeholder="" />
<AutoFocusPlugin />
<ListPlugin />
<LinkPlugin />
<AutoLinkPlugin />
<MarkdownShortcutPlugin transformers={TRANSFORMERS} />
</div>
</div>
</LexicalComposer>
</div>
);
}
@@ -0,0 +1,24 @@
const exampleTheme = {
placeholder: "editor-placeholder",
paragraph: "editor-paragraph",
heading: {
h1: "editor-heading-h1",
h2: "editor-heading-h2",
},
list: {
nested: {
listitem: "editor-nested-listitem",
},
ol: "editor-list-ol",
ul: "editor-list-ul",
listitem: "editor-listitem",
},
image: "editor-image",
link: "editor-link",
text: {
bold: "editor-text-bold",
italic: "editor-text-italic",
},
};
export default exampleTheme;
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-link" viewBox="0 0 16 16">
<path d="M6.354 5.5H4a3 3 0 0 0 0 6h3a3 3 0 0 0 2.83-4H9c-.086 0-.17.01-.25.031A2 2 0 0 1 7 10.5H4a2 2 0 1 1 0-4h1.535c.218-.376.495-.714.82-1z"/>
<path d="M9 5.5a3 3 0 0 0-2.83 4h1.098A2 2 0 0 1 9 6.5h3a2 2 0 1 1 0 4h-1.535a4.02 4.02 0 0 1-.82 1H12a3 3 0 1 0 0-6H9z"/>
</svg>

After

Width:  |  Height:  |  Size: 404 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-list-ol" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5z"/>
<path d="M1.713 11.865v-.474H2c.217 0 .363-.137.363-.317 0-.185-.158-.31-.361-.31-.223 0-.367.152-.373.31h-.59c.016-.467.373-.787.986-.787.588-.002.954.291.957.703a.595.595 0 0 1-.492.594v.033a.615.615 0 0 1 .569.631c.003.533-.502.8-1.051.8-.656 0-1-.37-1.008-.794h.582c.008.178.186.306.422.309.254 0 .424-.145.422-.35-.002-.195-.155-.348-.414-.348h-.3zm-.004-4.699h-.604v-.035c0-.408.295-.844.958-.844.583 0 .96.326.96.756 0 .389-.257.617-.476.848l-.537.572v.03h1.054V9H1.143v-.395l.957-.99c.138-.142.293-.304.293-.508 0-.18-.147-.32-.342-.32a.33.33 0 0 0-.342.338v.041zM2.564 5h-.635V2.924h-.031l-.598.42v-.567l.629-.443h.635V5z"/>
</svg>

After

Width:  |  Height:  |  Size: 984 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-list-ul" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M5 11.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zm-3 1a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm0 4a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm0 4a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>
</svg>

After

Width:  |  Height:  |  Size: 448 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-fill" viewBox="0 0 16 16">
<path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z"/>
</svg>

After

Width:  |  Height:  |  Size: 590 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-text-paragraph" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M2 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5zm0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5zm4-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5z"/>
</svg>

After

Width:  |  Height:  |  Size: 418 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-type-bold" viewBox="0 0 16 16">
<path d="M8.21 13c2.106 0 3.412-1.087 3.412-2.823 0-1.306-.984-2.283-2.324-2.386v-.055a2.176 2.176 0 0 0 1.852-2.14c0-1.51-1.162-2.46-3.014-2.46H3.843V13H8.21zM5.908 4.674h1.696c.963 0 1.517.451 1.517 1.244 0 .834-.629 1.32-1.73 1.32H5.908V4.673zm0 6.788V8.598h1.73c1.217 0 1.88.492 1.88 1.415 0 .943-.643 1.449-1.832 1.449H5.907z"/>
</svg>

After

Width:  |  Height:  |  Size: 471 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-type-h1" viewBox="0 0 16 16">
<path d="M8.637 13V3.669H7.379V7.62H2.758V3.67H1.5V13h1.258V8.728h4.62V13h1.259zm5.329 0V3.669h-1.244L10.5 5.316v1.265l2.16-1.565h.062V13h1.244z"/>
</svg>

After

Width:  |  Height:  |  Size: 283 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-type-h2" viewBox="0 0 16 16">
<path d="M7.638 13V3.669H6.38V7.62H1.759V3.67H.5V13h1.258V8.728h4.62V13h1.259zm3.022-6.733v-.048c0-.889.63-1.668 1.716-1.668.957 0 1.675.608 1.675 1.572 0 .855-.554 1.504-1.067 2.085l-3.513 3.999V13H15.5v-1.094h-4.245v-.075l2.481-2.844c.875-.998 1.586-1.784 1.586-2.953 0-1.463-1.155-2.556-2.919-2.556-1.941 0-2.966 1.326-2.966 2.74v.049h1.223z"/>
</svg>

After

Width:  |  Height:  |  Size: 483 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-type-italic" viewBox="0 0 16 16">
<path d="M7.991 11.674 9.53 4.455c.123-.595.246-.71 1.347-.807l.11-.52H7.211l-.11.52c1.06.096 1.128.212 1.005.807L6.57 11.674c-.123.595-.246.71-1.346.806l-.11.52h3.774l.11-.52c-1.06-.095-1.129-.211-1.006-.806z"/>
</svg>

After

Width:  |  Height:  |  Size: 352 B

@@ -0,0 +1,36 @@
import { AutoLinkPlugin } from "@lexical/react/LexicalAutoLinkPlugin";
const URL_MATCHER =
/((https?:\/\/(www\.)?)|(www\.))[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/;
const EMAIL_MATCHER =
/(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
const MATCHERS = [
(text: any) => {
const match = URL_MATCHER.exec(text);
return (
match && {
index: match.index,
length: match[0].length,
text: match[0],
url: match[0],
}
);
},
(text: any) => {
const match = EMAIL_MATCHER.exec(text);
return (
match && {
index: match.index,
length: match[0].length,
text: match[0],
url: `mailto:${match[0]}`,
}
);
},
];
export default function PlaygroundAutoLinkPlugin() {
return <AutoLinkPlugin matchers={MATCHERS} />;
}
@@ -0,0 +1,526 @@
import { $generateHtmlFromNodes, $generateNodesFromDOM } from "@lexical/html";
import { $isLinkNode, TOGGLE_LINK_COMMAND } from "@lexical/link";
import {
INSERT_ORDERED_LIST_COMMAND,
INSERT_UNORDERED_LIST_COMMAND,
REMOVE_LIST_COMMAND,
$isListNode,
ListNode,
} from "@lexical/list";
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 {
SELECTION_CHANGE_COMMAND,
FORMAT_TEXT_COMMAND,
$getSelection,
$isRangeSelection,
$createParagraphNode,
RangeSelection,
NodeSelection,
GridSelection,
$getRoot,
$insertNodes,
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 { AddVariablesDropdown } from "../../AddVariablesDropdown";
import { TextEditorProps } from "../Editor";
const LowPriority = 1;
const supportedBlockTypes = new Set(["paragraph", "h1", "h2", "ul", "ol"]);
interface BlockType {
[key: string]: string;
}
const blockTypeToBlockName: BlockType = {
h1: "Large Heading",
h2: "Small Heading",
ol: "Numbered List",
paragraph: "Normal",
ul: "Bulleted List",
};
function positionEditorElement(editor: HTMLInputElement, rect: DOMRect | null) {
if (rect === null) {
editor.style.opacity = "0";
editor.style.top = "-1000px";
editor.style.left = "-1000px";
} else {
editor.style.opacity = "1";
editor.style.top = `${rect.top + rect.height + window.pageYOffset + 10}px`;
editor.style.left = `${rect.left + window.pageXOffset - editor.offsetWidth / 2 + rect.width / 2}px`;
}
}
function FloatingLinkEditor({ editor }: { editor: LexicalEditor }) {
const editorRef = useRef<HTMLInputElement>(null);
const mouseDownRef = useRef(false);
const inputRef = useRef<HTMLInputElement | null>(null);
const [linkUrl, setLinkUrl] = useState("");
const [isEditMode, setEditMode] = useState(false);
const [lastSelection, setLastSelection] = useState<RangeSelection | NodeSelection | GridSelection | null>(
null
);
const updateLinkEditor = useCallback(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const node = getSelectedNode(selection);
const parent = node.getParent();
if ($isLinkNode(parent)) {
setLinkUrl(parent.getURL());
} else if ($isLinkNode(node)) {
setLinkUrl(node.getURL());
} else {
setLinkUrl("");
}
}
const editorElem = editorRef.current;
const nativeSelection = window.getSelection();
const activeElement = document.activeElement;
if (editorElem === null) {
return;
}
const rootElement = editor.getRootElement();
if (
selection !== null &&
!nativeSelection?.isCollapsed &&
rootElement !== null &&
rootElement.contains(nativeSelection?.anchorNode || null)
) {
const domRange = nativeSelection?.getRangeAt(0);
let rect: DOMRect | undefined;
if (nativeSelection?.anchorNode === rootElement) {
let inner: Element = rootElement;
while (inner.firstElementChild != null) {
inner = inner.firstElementChild;
}
rect = inner.getBoundingClientRect();
} else {
rect = domRange?.getBoundingClientRect();
}
if (!mouseDownRef.current) {
positionEditorElement(editorElem, rect || null);
}
setLastSelection(selection);
} else if (!activeElement || activeElement.className !== "link-input") {
positionEditorElement(editorElem, null);
setLastSelection(null);
setEditMode(false);
setLinkUrl("");
}
return true;
}, [editor]);
useEffect(() => {
return mergeRegister(
editor.registerUpdateListener(({ editorState }: { editorState: EditorState }) => {
editorState.read(() => {
updateLinkEditor();
});
}),
editor.registerCommand(
SELECTION_CHANGE_COMMAND,
() => {
updateLinkEditor();
return true;
},
LowPriority
)
);
}, [editor, updateLinkEditor]);
useEffect(() => {
editor.getEditorState().read(() => {
updateLinkEditor();
});
}, [editor, updateLinkEditor]);
useEffect(() => {
if (isEditMode && inputRef.current) {
inputRef.current.focus();
}
}, [isEditMode]);
return (
<div ref={editorRef} className="link-editor">
{isEditMode ? (
<input
ref={inputRef}
className="link-input"
value={linkUrl}
onChange={(event) => {
setLinkUrl(event.target.value);
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
if (lastSelection !== null) {
if (linkUrl !== "") {
editor.dispatchCommand(TOGGLE_LINK_COMMAND, linkUrl);
}
setEditMode(false);
}
} else if (event.key === "Escape") {
event.preventDefault();
setEditMode(false);
}
}}
/>
) : (
<>
<div className="link-input">
<a href={linkUrl} target="_blank" rel="noopener noreferrer">
{linkUrl}
</a>
<div
className="link-edit"
role="button"
tabIndex={0}
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
setEditMode(true);
}}
/>
</div>
</>
)}
</div>
);
}
function getSelectedNode(selection: RangeSelection) {
const anchor = selection.anchor;
const focus = selection.focus;
const anchorNode = selection.anchor.getNode();
const focusNode = selection.focus.getNode();
if (anchorNode === focusNode) {
return anchorNode;
}
const isBackward = selection.isBackward();
if (isBackward) {
return $isAtNodeEnd(focus) ? anchorNode : focusNode;
} else {
return $isAtNodeEnd(anchor) ? focusNode : anchorNode;
}
}
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]);
const formatParagraph = () => {
if (blockType !== "paragraph") {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
$wrapNodes(selection, () => $createParagraphNode());
}
});
}
setShowBlockOptionsDropDown(false);
};
const formatLargeHeading = () => {
if (blockType !== "h1") {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
$wrapNodes(selection, () => $createHeadingNode("h1"));
}
});
}
setShowBlockOptionsDropDown(false);
};
const formatSmallHeading = () => {
if (blockType !== "h2") {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
$wrapNodes(selection, () => $createHeadingNode("h2"));
}
});
}
setShowBlockOptionsDropDown(false);
};
const formatBulletList = () => {
if (blockType !== "ul") {
editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
} else {
editor.dispatchCommand(REMOVE_LIST_COMMAND, undefined);
}
setShowBlockOptionsDropDown(false);
};
const formatNumberedList = () => {
if (blockType !== "ol") {
editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
} 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 updateToolbar = useCallback(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const anchorNode = selection.anchor.getNode();
const element = anchorNode.getKey() === "root" ? anchorNode : anchorNode.getTopLevelElementOrThrow();
const elementKey = element.getKey();
const elementDOM = editor.getElementByKey(elementKey);
if (elementDOM !== null) {
if ($isListNode(element)) {
const parentList = $getNearestNodeOfType(anchorNode, ListNode);
const type = parentList ? parentList.getTag() : element.getTag();
setBlockType(type);
} else {
const type = $isHeadingNode(element) ? element.getTag() : element.getType();
setBlockType(type);
}
}
setIsBold(selection.hasFormat("bold"));
setIsItalic(selection.hasFormat("italic"));
const node = getSelectedNode(selection);
const parent = node.getParent();
if ($isLinkNode(parent) || $isLinkNode(node)) {
setIsLink(true);
} else {
setIsLink(false);
}
}
}, [editor]);
const addVariable = (variable: string) => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
editor.update(() => {
const formatedVariable = `{${variable.toUpperCase().replace(/ /g, "_")}}`;
selection?.insertRawText(formatedVariable);
});
}
});
};
useEffect(() => {
editor.update(() => {
const parser = new DOMParser();
const dom = parser.parseFromString(
props.form.getValues(`steps.${props.stepNumber - 1}.reminderBody`) || "",
"text/html"
);
const nodes = $generateNodesFromDOM(editor, dom);
$getRoot().select();
$insertNodes(nodes);
editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
const textInHtml = $generateHtmlFromNodes(editor);
props.form.setValue(`steps.${props.stepNumber - 1}.reminderBody`, textInHtml);
props.form.clearErrors();
});
});
});
}, []);
useEffect(() => {
return mergeRegister(
editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
updateToolbar();
});
}),
editor.registerCommand(
SELECTION_CHANGE_COMMAND,
(_payload, newEditor) => {
updateToolbar();
return false;
},
LowPriority
)
);
}, [editor, updateToolbar]);
const insertLink = useCallback(() => {
if (!isLink) {
editor.dispatchCommand(TOGGLE_LINK_COMMAND, "https://");
} else {
editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
}
}, [editor, isLink]);
return (
<div className="toolbar flex" ref={toolbarRef}>
<>
{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
)}
</>
)}
<>
<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) {
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)}{" "}
</>
<div className="ml-auto">
<AddVariablesDropdown addVariable={addVariable} isEmailSubject={false} isTextEditor={true} />
</div>
</>
</div>
);
}
@@ -0,0 +1,402 @@
.editor a {
color: #0000FF;
text-decoration: underline;
font-size: 14px;
}
.editor li {
padding-left: 1.28571429em;
text-indent: -1.28571429em;
}
.editor ul {
list-style: disc inside
}
.editor ol {
list-style: decimal inside
}
.editor-container {
border-radius: 6px;
position: relative;
line-height: 20px;
font-weight: 400;
text-align: left;
border-color: #D1D5DB;
border-width: 1px;
padding: 1px
}
.editor-inner {
background: #fff;
position: relative;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
height: 200px;
overflow: scroll;
resize: vertical;
}
.editor-input {
min-height: 150px;
font-size: 14px;
position: relative;
tab-size: 1;
outline: 0;
padding: 15px 10px;
outline: none
}
.editor-text-bold {
font-weight: bold;
}
.editor-text-italic {
font-style: italic;
}
.editor-link {
color: rgb(33, 111, 219);
text-decoration: none;
}
.editor-tokenFunction {
color: #dd4a68;
}
.editor-paragraph {
margin: 0;
margin-bottom: 8px;
position: relative;
}
.editor-paragraph:last-child {
margin-bottom: 0;
}
.editor-heading-h1 {
font-size: 25px;
font-weight: 400;
margin-bottom: 20px;
font-weight: bold;
}
.editor-heading-h2 {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
}
.editor-list-ul {
margin-bottom: 12px;
}
.editor-list-ol {
margin-bottom: 12px;
}
.editor-listitem {
margin: 0px 32px;
}
.editor-nested-listitem {
list-style-type: none;
}
pre::-webkit-scrollbar {
background: transparent;
width: 10px;
}
pre::-webkit-scrollbar-thumb {
background: #999;
}
.toolbar {
display: flex;
margin-bottom: 1px;
background: #fff;
padding: 2px;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
vertical-align: middle;
}
.toolbar button.toolbar-item {
border: 0;
display: flex;
background: none;
border-radius: 10px;
padding: 8px;
cursor: pointer;
vertical-align: middle;
height: 36px;
}
.toolbar button.toolbar-item.spaced {
margin-right: 2px;
}
.toolbar button.toolbar-item i.format {
background-size: contain;
display: inline-block;
height: 18px;
width: 18px;
margin-top: 2px;
vertical-align: -0.25em;
display: flex;
opacity: 0.6;
}
.icon.paragraph {
background-image: url(images/icons/text-paragraph.svg);
}
.toolbar button.toolbar-item.active {
background-color: rgba(223, 232, 250, 0.3);
}
.toolbar button.toolbar-item.active i {
opacity: 1;
}
.toolbar .toolbar-item:hover:not([disabled]) {
background-color: #eee;
}
.toolbar select.toolbar-item {
border: 0;
display: flex;
background: none;
border-radius: 10px;
padding: 8px;
vertical-align: middle;
-webkit-appearance: none;
-moz-appearance: none;
width: 70px;
font-size: 14px;
color: #777;
text-overflow: ellipsis;
}
.toolbar .toolbar-item .text {
line-height: 20px;
width: 200px;
vertical-align: middle;
font-size: 14px;
color: #777;
text-overflow: ellipsis;
width: 70px;
overflow: hidden;
height: 20px;
text-align: left;
}
.toolbar .toolbar-item .icon {
display: flex;
width: 20px;
height: 20px;
user-select: none;
margin-right: 8px;
line-height: 16px;
background-size: contain;
}
#block-controls button:hover {
background-color: #efefef;
}
#block-controls button:focus-visible {
border-color: blue;
}
.dropdown {
z-index: 5;
display: block;
position: absolute;
box-shadow: 0 12px 28px 0 rgba(0, 0, 0, 0.2), 0 2px 4px 0 rgba(0, 0, 0, 0.1),
inset 0 0 0 1px rgba(255, 255, 255, 0.5);
border-radius: 8px;
min-width: 100px;
min-height: 40px;
background-color: #fff;
}
.dropdown .item {
margin: 0 8px 0 8px;
padding: 8px;
color: #050505;
cursor: pointer;
line-height: 16px;
font-size: 15px;
display: flex;
align-content: center;
flex-direction: row;
flex-shrink: 0;
justify-content: space-between;
background-color: #fff;
border-radius: 8px;
border: 0;
min-width: 268px;
}
.dropdown .item .active {
display: flex;
width: 20px;
height: 20px;
background-size: contain;
}
.dropdown .item:first-child {
margin-top: 8px;
}
.dropdown .item:last-child {
margin-bottom: 8px;
}
.dropdown .item:hover {
background-color: #eee;
}
.dropdown .item .text {
display: flex;
line-height: 20px;
flex-grow: 1;
width: 200px;
}
.dropdown .item .icon {
display: flex;
width: 20px;
height: 20px;
user-select: none;
margin-right: 12px;
line-height: 16px;
background-size: contain;
}
.link-editor {
position: absolute;
z-index: 100;
top: -10000px;
left: -10000px;
margin-top: -6px;
max-width: 300px;
width: 100%;
opacity: 0;
background-color: #fff;
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.3);
border-radius: 8px;
transition: opacity 0.5s;
}
.link-editor .link-input {
display: block;
width: calc(100% - 24px);
box-sizing: border-box;
margin: 8px 12px;
padding: 8px 12px;
border-radius: 15px;
background-color: #eee;
font-size: 15px;
color: rgb(5, 5, 5);
border: 0;
outline: 0;
position: relative;
font-family: inherit;
}
.link-editor div.link-edit {
background-image: url(images/icons/pencil-fill.svg);
background-size: 16px;
background-position: center;
background-repeat: no-repeat;
width: 35px;
vertical-align: -0.25em;
position: absolute;
right: 0;
top: 0;
bottom: 0;
cursor: pointer;
}
.link-editor .link-input a {
color: rgb(33, 111, 219);
text-decoration: none;
display: block;
white-space: nowrap;
overflow: hidden;
margin-right: 30px;
text-overflow: ellipsis;
}
.link-editor .link-input a:hover {
text-decoration: underline;
}
.link-editor .button {
width: 20px;
height: 20px;
display: inline-block;
padding: 6px;
border-radius: 8px;
cursor: pointer;
margin: 0 2px;
}
.link-editor .button.hovered {
width: 20px;
height: 20px;
display: inline-block;
background-color: #eee;
}
.link-editor .button i,
.actions i {
background-size: contain;
display: inline-block;
height: 20px;
width: 20px;
vertical-align: -0.25em;
}
.icon.paragraph {
background-image: url(images/icons/text-paragraph.svg);
}
.icon.large-heading,
.icon.h1 {
background-image: url(images/icons/type-h1.svg);
}
.icon.small-heading,
.icon.h2 {
background-image: url(images/icons/type-h2.svg);
}
.icon.bullet-list,
.icon.ul {
background-image: url(images/icons/list-ul.svg);
}
.icon.numbered-list,
.icon.ol {
background-image: url(images/icons/list-ol.svg);
}
i.bold {
background-image: url(images/icons/type-bold.svg);
}
i.italic {
background-image: url(images/icons/type-italic.svg);
}
i.link {
background-image: url(images/icons/link.svg);
}
@@ -41,6 +41,7 @@ import {
} 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 = {
@@ -107,7 +108,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
const refReminderBody = useRef<HTMLTextAreaElement | null>(null);
const addVariable = (isEmailSubject: boolean, variable: string) => {
const addVariable = (variable: string, isEmailSubject?: boolean) => {
if (step) {
if (isEmailSubject) {
const currentEmailSubject = refEmailSubject?.current?.value || "";
@@ -291,23 +292,32 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
className="text-sm"
onChange={(val) => {
if (val) {
if (val.value === WorkflowActions.SMS_NUMBER) {
setIsPhoneNumberNeeded(true);
const oldValue = form.getValues(`steps.${step.stepNumber - 1}.action`);
const wasSMSAction =
oldValue === WorkflowActions.SMS_ATTENDEE ||
oldValue === WorkflowActions.SMS_NUMBER;
const isSMSAction =
val.value === WorkflowActions.SMS_ATTENDEE ||
val.value === WorkflowActions.SMS_NUMBER;
if (isSMSAction) {
setIsSenderIdNeeded(true);
setIsEmailAddressNeeded(false);
} else if (val.value === WorkflowActions.EMAIL_ADDRESS) {
setIsEmailAddressNeeded(true);
setIsPhoneNumberNeeded(false);
setIsSenderIdNeeded(false);
} else if (val.value === WorkflowActions.SMS_ATTENDEE) {
setIsSenderIdNeeded(true);
setIsEmailAddressNeeded(false);
setIsPhoneNumberNeeded(false);
setIsPhoneNumberNeeded(val.value === WorkflowActions.SMS_NUMBER);
if (!wasSMSAction) {
form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, "");
}
} else {
setIsEmailAddressNeeded(false);
setIsPhoneNumberNeeded(false);
setIsSenderIdNeeded(false);
setIsEmailAddressNeeded(val.value === WorkflowActions.EMAIL_ADDRESS);
if (wasSMSAction) {
form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, "");
}
}
form.unregister(`steps.${step.stepNumber - 1}.sendTo`);
form.clearErrors(`steps.${step.stepNumber - 1}.sendTo`);
if (
@@ -424,8 +434,8 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
{isCustomReminderBodyNeeded && (
<div className="mt-2 rounded-md bg-gray-50 p-4 pt-2 md:p-6 md:pt-4">
{isEmailSubjectNeeded && (
<div className="mb-5">
<div className="mb-2 flex items-center">
<div className="mb-6">
<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} />
@@ -436,7 +446,8 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
emailSubjectFormRef?.(e);
refEmailSubject.current = e;
}}
className="my-0"
rows={1}
className="my-0 focus:ring-transparent"
required
{...restEmailSubjectForm}
/>
@@ -448,26 +459,41 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
)}
</div>
)}
<div className="mb-2 flex items-center">
<Label className="mb-0 flex-none">
{isEmailSubjectNeeded ? t("email_body") : t("text_message")}
</Label>
<div className="flex-grow text-right">
<AddVariablesDropdown addVariable={addVariable} isEmailSubject={false} />
</div>
</div>
<TextArea
ref={(e) => {
reminderBodyFormRef?.(e);
refReminderBody.current = e;
}}
className="my-0 h-24"
required
{...restReminderBodyForm}
/>
{step.action !== WorkflowActions.SMS_ATTENDEE &&
step.action !== WorkflowActions.SMS_NUMBER ? (
<>
<div className="mb-2 flex items-center pb-[1.5px]">
<Label className="mb-0 flex-none ">
{isEmailSubjectNeeded ? t("email_body") : t("text_message")}
</Label>
</div>
<Editor form={form} stepNumber={step.stepNumber} />
</>
) : (
<>
<div className="flex items-center">
<Label className="mb-0 flex-none">
{isEmailSubjectNeeded ? t("email_body") : t("text_message")}
</Label>
<div className="flex-grow text-right">
<AddVariablesDropdown addVariable={addVariable} isEmailSubject={false} />
</div>
</div>
<TextArea
ref={(e) => {
reminderBodyFormRef?.(e);
refReminderBody.current = e;
}}
className="my-0 h-24"
required
{...restReminderBodyForm}
/>
</>
)}
{form.formState.errors.steps &&
form.formState?.errors?.steps[step.stepNumber - 1]?.reminderBody && (
<p className="mt-1 text-xs text-red-500">
<p className="mt-1 text-sm text-red-500">
{form.formState?.errors?.steps[step.stepNumber - 1]?.reminderBody?.message || ""}
</p>
)}
@@ -61,6 +61,7 @@ const formSchema = z.object({
sendTo: z
.string()
.refine((val) => isValidPhoneNumber(val) || val.includes("@"))
.optional()
.nullable(),
sender: z
.string()
@@ -95,6 +96,7 @@ function WorkflowPage() {
data: workflow,
isError,
error,
isLoading,
} = trpc.viewer.workflows.get.useQuery(
{ id: +workflowId },
{
@@ -103,7 +105,7 @@ function WorkflowPage() {
);
useEffect(() => {
if (workflow) {
if (workflow && !isLoading) {
setSelectedEventTypes(
workflow.activeOn.map((active) => ({
value: String(active.eventType.id),
@@ -143,7 +145,7 @@ function WorkflowPage() {
form.setValue("activeOn", activeOn || []);
setIsAllDataLoaded(true);
}
}, [workflow]);
}, [isLoading]);
const updateMutation = trpc.viewer.workflows.update.useMutation({
onSuccess: async ({ workflow }) => {
@@ -172,30 +174,49 @@ function WorkflowPage() {
form={form}
handleSubmit={async (values) => {
let activeOnEventTypeIds: number[] = [];
let isEmpty = false;
values.steps.forEach((step) => {
const isSMSAction =
step.action === WorkflowActions.SMS_ATTENDEE || step.action === WorkflowActions.SMS_NUMBER;
const strippedHtml = step.reminderBody?.replace(/<[^>]+>/g, "") || "";
const isBodyEmpty =
step.template === WorkflowTemplates.CUSTOM && !isSMSAction && strippedHtml.length <= 1;
if (isBodyEmpty) {
form.setError(`steps.${step.stepNumber - 1}.reminderBody`, {
type: "custom",
message: t("fill_this_field"),
});
}
if (step.reminderBody) {
step.reminderBody = translateVariablesToEnglish(step.reminderBody, { locale: i18n.language, t });
}
if (step.emailSubject) {
step.emailSubject = translateVariablesToEnglish(step.emailSubject, { locale: i18n.language, t });
}
isEmpty = !isEmpty ? isBodyEmpty : isEmpty;
});
if (values.activeOn) {
activeOnEventTypeIds = values.activeOn.map((option) => {
return parseInt(option.value, 10);
if (!isEmpty) {
if (values.activeOn) {
activeOnEventTypeIds = values.activeOn.map((option) => {
return parseInt(option.value, 10);
});
}
updateMutation.mutate({
id: parseInt(router.query.workflow as string, 10),
name: values.name,
activeOn: activeOnEventTypeIds,
steps: values.steps,
trigger: values.trigger,
time: values.time || null,
timeUnit: values.timeUnit || null,
});
}
updateMutation.mutate({
id: parseInt(router.query.workflow as string, 10),
name: values.name,
activeOn: activeOnEventTypeIds,
steps: values.steps,
trigger: values.trigger,
time: values.time || null,
timeUnit: values.timeUnit || null,
});
}}>
<Shell
backPath="/workflows"
+5 -1
View File
@@ -4,5 +4,9 @@
"description": "Cal.com's main collocation of features",
"authors": "Cal.com, Inc.",
"version": "1.0.0",
"main": "index.ts"
"main": "index.ts",
"dependencies": {
"@lexical/react": "^0.5.0",
"lexical": "^0.5.0"
}
}
+1 -1
View File
@@ -166,7 +166,7 @@ export const PasswordField = forwardRef<HTMLInputElement, InputFieldProps>(funct
addOnSuffix={
<Tooltip content={textLabel}>
<button
className="absolute right-3 bottom-0 h-9 text-gray-900"
className="absolute bottom-0 right-3 h-9 text-gray-900"
type="button"
onClick={() => toggleIsPasswordVisible()}>
{isPasswordVisible ? (