All files / src/shared/HFInputs/HFRichInput HFSimpleRichInput.tsx

56.41% Statements 22/39
52.38% Branches 11/21
37.5% Functions 6/16
54.28% Lines 19/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248                                                              21x     21x 21x   21x       21x   21x                 21x             21x                       21x   21x                                                             21x               21x 63x 63x 63x     21x               21x                                                                                                                 45x                                                                                                                 45x              
import { useCallback, useMemo, useState } from "react";
import { EditorState, RichUtils } from "draft-js";
import { ContentState, Editor } from "react-draft-wysiwyg-next";
import "react-draft-wysiwyg-next/dist/react-draft-wysiwyg.css";
import { styled } from "@theme/v2/Provider";
import { Stack } from "@mui/system";
import { TextBIcon, TextItalicIcon, TextUnderlineIcon } from "@phosphor-icons/react";
import IconWrapper from "./IconWrapper";
import { EditorMode, ICON_STATE } from "./richInput.types";
import _ from "lodash";
import FontFamilies from "./FontFamily/FontFamilies";
import { FontSizeMenuSelector } from "./FontSize";
import { ColorSelector } from "./Colors";
import { customStyleMap } from "./FontFamily/consts";
import { toggleCustomInlineStyle } from "draftjs-utils";
import GiveText from "@shared/Text/GiveText";
import { updateRichEditorText } from "./RichTextUtils";
 
function HFSimpleRichInput({
  isDisabled,
  value,
  onChange,
  options,
  maxLength = 50,
}: {
  isDisabled?: boolean;
  onChange?: (e: EditorState) => void;
  value?: ContentState;
  options?: string[];
  maxLength?: number;
}) {
  const emptyState = value
    ? EditorState.createWithContent(value)
    : EditorState.createEmpty();
  const [editorState, setEditorState] = useState(() => emptyState);
  const currentLength = editorState.getCurrentContent().getPlainText("").length;
 
  const editorStateLen = editorState
    .getCurrentContent()
    ?.getPlainText("\u0001").length;
 
  const remaining = editorState ? maxLength - editorStateLen : maxLength;
 
  const handleEditorChange = (state: EditorState) => {
    if (state?.getCurrentContent().getPlainText().length > maxLength) {
      return;
    }
 
    setEditorState(state);
    debouncedOnChange(state);
  };
 
  const debouncedOnChange = useCallback(
    _.debounce((state: EditorState) => {
      onChange && onChange(state);
    }, 300),
    [],
  );
 
  const handleFontSelection = (fontValue: any) => {
    const contentState = editorState.getCurrentContent();
 
    updateRichEditorText(
      editorState,
      (newState: EditorState) =>
        toggleCustomInlineStyle(newState, "fontFamily", fontValue.label),
      handleEditorChange,
      !contentState.hasText(),
    );
  };
 
  const customActions = useMemo(
    () =>
      [
        options?.includes("fontFamily") && [
          <FontFamilies
            key="FONT_FAMILY"
            editorState={editorState}
            onClick={handleFontSelection}
          />,
          options?.includes("fontSize") && (
            <FontSizeMenuSelector
              key="fontSize"
              editorState={editorState}
              onChange={handleEditorChange}
              editorMode={EditorMode.SINGLE_LINE}
            />
          ),
          <HorizontalSeparator key="separator-1" />,
          options?.includes("colors") && (
            <ColorSelector
              editorState={editorState}
              key="color-selector"
              onChange={handleEditorChange}
              editorMode={EditorMode.SINGLE_LINE}
            />
          ),
        ],
      ]
        .filter(Boolean)
        .flat(),
    [editorState, options],
  );
 
  const toggleInlineStyle = (style: string) => {
    updateRichEditorText(
      editorState,
      (newState: EditorState) => RichUtils.toggleInlineStyle(newState, style),
      handleEditorChange,
    );
  };
 
  const getInlineStyleState = (style: string): ICON_STATE => {
    Iif (isDisabled) return "disabled";
    const currentInlineStyle = editorState.getCurrentInlineStyle();
    return currentInlineStyle.has(style) ? "active" : "default";
  };
 
  const handleBeforeInput = (_input: string, _editorState: EditorState) => {
    if (remaining === 0) {
      return "handled";
    } else {
      return "not-handled";
    }
  };
 
  return (
    <>
      <Stack gap="9px">
        <Container>
          {/* @ts-ignore (optional: suppress specific TypeScript error) */}
          <Editor
            editorState={editorState}
            toolbarClassName="toolbarClassName"
            wrapperClassName="wrapperClassName"
            editorClassName="editorClassName"
            onEditorStateChange={handleEditorChange}
            customStyleMap={customStyleMap}
            stripPastedStyles={true}
            // @ts-ignore (optional: suppress specific TypeScript error)
            handleBeforeInput={handleBeforeInput}
            toolbar={{
              options: [],
              link: { options: [] },
              inline: {
                options: [],
              },
              list: { options: [] },
              blockType: { options: [] },
            }}
            toolbarCustomButtons={[
              ...(customActions as any),
              <IconWrapper
                key="bold"
                icon={TextBIcon}
                onClick={() => toggleInlineStyle("BOLD")}
                state={getInlineStyleState("BOLD")}
              />,
              <IconWrapper
                key="italic"
                icon={TextItalicIcon}
                onClick={() => toggleInlineStyle("ITALIC")}
                state={getInlineStyleState("ITALIC")}
              />,
              <IconWrapper
                key="underline"
                icon={TextUnderlineIcon}
                onClick={() => toggleInlineStyle("UNDERLINE")}
                state={getInlineStyleState("UNDERLINE")}
              />,
            ]}
            placeholder="Type business name"
          />
        </Container>
 
        <GiveText color="secondary" fontSize="12px">
          {currentLength}/{maxLength}
        </GiveText>
      </Stack>
    </>
  );
}
 
const Container = styled(Stack)(({ theme }) => ({
  border: `0px solid ${theme.palette.border?.secondary}`,
  borderRadius: "12px",
  "& .editorClassName": {
    maxHeight: "400px",
    height: "auto",
    paddingLeft: "10px",
    border: `1px solid ${theme.palette.border?.secondary}`,
    borderRadius: "12px",
    overflow: "hidden",
  },
  "& .toolbarClassName": {
    borderRadius: "12px",
    backgroundColor: theme.palette.surface?.secondary,
    padding: "8px",
    marginBottom: "8px",
    display: "flex",
    gap: "8px",
    "& .rdw-option-wrapper": {
      border: "none",
      padding: "4px",
      minWidth: "32px",
      maxHeight: "400px",
      height: "auto",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      borderRadius: "4px",
      "&:hover": {
        backgroundColor: theme.palette.action?.hover,
      },
    },
    "& .rdw-option-active": {
      backgroundColor: theme.palette.action?.selected,
    },
  },
  "& .editorClassName a": {
    color: theme.palette.primitive?.blue[100],
    fontSize: "14px",
    fontWeight: 400,
  },
  "& .DraftEditor-root": {
    maxHeight: "400px",
    height: "auto",
    display: "flex",
    alignContent: "center",
    alignItems: "center",
  },
  "& .DraftEditor-editorContainer": {
    width: "100%",
  },
  "& .public-DraftStyleDefault-block": {
    margin: 0,
    padding: "1em 0",
  },
}));
 
const HorizontalSeparator = styled("div")(({ theme }) => ({
  borderRight: `1px solid ${theme.palette.border?.secondary}`,
  height: "18px",
  margin: "auto 0",
}));
 
export default HFSimpleRichInput;