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

55.44% Statements 56/101
60.27% Branches 44/73
59.25% Functions 16/27
55.31% Lines 52/94

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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520                                                                                  45x                                                   545x 545x     545x             545x 545x 545x 545x   64x 14x 5x         545x                                                   545x   534x                                                         545x   534x                             545x       545x   545x   6x         545x 11x 11x       11x 11x   545x   545x         545x                   545x 2180x 2180x 2180x     545x 545x 545x         545x     545x                                                                                               545x                           545x 3x 2x     2x 2x     2x     545x 64x               545x                                       545x                                                                                                                                                                                                                                         45x 1135x 545x                                                                                                                                             1666x              
// https://github.com/jpuri/react-draft-wysiwyg/blob/master/src/controls/TextAlign/index.js
// https://github.com/jpuri/react-draft-wysiwyg/issues/1460#issuecomment-2848529052
 
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { EditorState, Modifier, RichUtils } from "draft-js";
import {
  alignmentInnerDivSx,
  buildBlockStyleFn,
  documentHeadingSx,
} from "./blockStyle";
import { TableInsertControl, buildTableBlockRenderFunc } from "./TableBlock";
import { insertPastedContent, parsePastedHtml } from "./pastedContent";
import {
  ContentState,
  Editor,
  SyntheticKeyboardEvent,
} from "react-draft-wysiwyg-next";
import "react-draft-wysiwyg-next/dist/react-draft-wysiwyg.css";
import { styled, useAppTheme } from "@theme/v2/Provider";
import GiveText from "@shared/Text/GiveText";
import { Stack } from "@mui/system";
import {
  ListDashesIcon,
  TextBIcon,
  TextItalicIcon,
  TextStrikethroughIcon,
  TextUnderlineIcon,
} from "@phosphor-icons/react";
import LinkModal from "./LinkModal";
import IconWrapper from "./IconWrapper";
import { EditorMode, ICON_STATE, RichInputVariant } from "./richInput.types";
import { debounce } from "lodash";
import { Alignment } from "./Alignment";
import { HeadingsMenuSelector } from "./Headings";
import { FontSizeMenuSelector } from "./FontSize";
import { ColorSelector } from "./Colors";
import { OrderedList } from "./OrderedList";
import { ImageLink } from "./Image";
import "./TextEditor.css";
import { updateLastListItem } from "./FontSize/utils";
 
const MAX_TEXT_LENGTH = 5000;
 
function HFRichInput({
  isDisabled,
  value,
  onChange,
  options,
  defaultValue,
  maxLength = MAX_TEXT_LENGTH,
  label = "Content (Optional)",
  showCharCount = true,
  variant = "form",
}: {
  isDisabled?: boolean;
  onChange?: (e: EditorState) => void;
  value?: ContentState;
  options?: string[];
  defaultValue?: ContentState;
  /** Character cap. Defaults to 5000 (suits short inputs); pass a larger value for documents. */
  maxLength?: number;
  /** Heading shown above the editor. Pass `null` to hide it. */
  label?: string | null;
  /** Whether to show the `n/maxLength` counter. */
  showCharCount?: boolean;
  variant?: RichInputVariant;
}) {
  const { palette } = useAppTheme();
  const emptyState = value
    ? EditorState.createWithContent(value)
    : EditorState.createEmpty();
  const [editorState, setEditorState] = useState(() => emptyState);
 
  // Table edits (cell commits, add/remove row/column, delete, insert) must go
  // through handleEditorChange — react-draft-wysiwyg's internal onChange
  // silently drops updates while the selection sits on an atomic block, which
  // is exactly where it lands around a table, freezing the editor. The render
  // func is built once; the handlers read live values through refs.
  const editorStateRef = useRef(editorState);
  editorStateRef.current = editorState;
  const handleEditorChangeRef = useRef<(state: EditorState) => void>();
  const tableBlockRenderFunc = useMemo(
    () =>
      buildTableBlockRenderFunc({
        getEditorState: () => editorStateRef.current,
        onChange: (state) => handleEditorChangeRef.current?.(state),
      }),
    [],
  );
 
  const toggleCustomInlineStyle = (
    editorState: EditorState,
    styleType: string,
    styleValue: string,
  ) => {
    let nextEditorState = editorState;
    const currentStyles = editorState.getCurrentInlineStyle();
 
    // Remove only styles of the same type (e.g., fontSize) while keeping others (e.g., color)
    currentStyles.forEach((style) => {
      if (style) {
        if (style.startsWith(`${styleType}-`)) {
          nextEditorState = RichUtils.toggleInlineStyle(nextEditorState, style);
        }
      }
    });
 
    // Apply the new inline style while keeping the existing ones
    nextEditorState = RichUtils.toggleInlineStyle(
      nextEditorState,
      `${styleType}-${styleValue}`,
    );
 
    return nextEditorState;
  };
 
  const prependedCustomActions = useMemo(
    () =>
      [
        options?.includes("headings") && (
          <HeadingsMenuSelector
            key="headings"
            editorState={editorState}
            includeParagraphSmall={options?.includes("paragraph-small")}
          />
        ),
        options?.includes("fontSize") && (
          <FontSizeMenuSelector
            toggleCustomInlineStyle={toggleCustomInlineStyle}
            key="fontSize"
            editorState={editorState}
            editorMode={EditorMode.MULTI_LINE}
          />
        ),
        <HorizontalSeparator key="separator-1" />,
        options?.includes("alignments") && [
          <Alignment editorState={editorState} value="left" key="left" />,
          <Alignment editorState={editorState} value="center" key="center" />,
          <Alignment editorState={editorState} value="right" key="right" />,
          <HorizontalSeparator key="separator-2" />,
        ],
      ]
        .filter(Boolean)
        .flat(),
    [options],
  );
 
  const apendedCustomActions = useMemo(
    () =>
      [
        options?.includes("colors") && (
          <ColorSelector
            toggleCustomInlineStyle={toggleCustomInlineStyle}
            editorState={editorState}
            key="color-selector"
            editorMode={EditorMode.MULTI_LINE}
          />
        ),
      ]
        .filter(Boolean)
        .flat(),
    [options],
  );
 
  const editorStateLen = editorState
    .getCurrentContent()
    ?.getPlainText("\u0001").length;
 
  const remaining = editorState ? maxLength - editorStateLen : maxLength;
 
  const debouncedOnChange = useCallback(
    debounce((state: EditorState) => {
      onChange && onChange(state);
    }, 300),
    [],
  );
 
  const handleEditorChange = (state: EditorState) => {
    const contentState = state.getCurrentContent();
    Iif (contentState.getPlainText().length > maxLength) {
      return;
    }
 
    setEditorState(state);
    debouncedOnChange(state);
  };
  handleEditorChangeRef.current = handleEditorChange;
 
  const toggleInlineStyle = (style: string) => {
    const newState = RichUtils.toggleInlineStyle(editorState, style);
    handleEditorChange(newState);
  };
 
  const toggleList = () => {
    updateLastListItem(editorState);
 
    const newState = RichUtils.toggleBlockType(
      editorState,
      "unordered-list-item",
    );
    handleEditorChange(newState);
  };
 
  const getInlineStyleState = (style: string): ICON_STATE => {
    Iif (isDisabled) return "disabled";
    const currentInlineStyle = editorState.getCurrentInlineStyle();
    return currentInlineStyle.has(style) ? "active" : "default";
  };
 
  const getListStyleState = (): ICON_STATE => {
    Iif (isDisabled) return "disabled";
    const currentBlockType = editorState
      .getCurrentContent()
      .getBlockForKey(editorState.getSelection().getStartKey())
      .getType();
 
    return currentBlockType === "unordered-list-item" ? "active" : "default";
  };
 
  const handleAddLink = (
    url: string,
    text: string,
    openInNewWindow = false,
  ) => {
    const targetOption = openInNewWindow ? "_blank" : "_self";
    const contentState = editorState.getCurrentContent();
    const selection = editorState.getSelection();
 
    if (selection.isCollapsed()) {
      //text is not selected
      const contentWithLink = Modifier.replaceText(
        contentState,
        selection,
        text || url,
        editorState.getCurrentInlineStyle(),
        contentState
          .createEntity("LINK", "MUTABLE", { url, targetOption })
          .getLastCreatedEntityKey(),
      );
      const newEditorState = EditorState.push(
        editorState,
        contentWithLink,
        "apply-entity",
      );
      handleEditorChange(newEditorState);
    } else {
      const contentStateWithEntity = contentState.createEntity(
        "LINK",
        "MUTABLE",
        { url, targetOption },
      );
      const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
      const newContentState = Modifier.applyEntity(
        contentState,
        selection,
        entityKey,
      );
 
      const newEditorState = EditorState.push(
        editorState,
        newContentState,
        "apply-entity",
      );
      handleEditorChange(newEditorState);
    }
  };
 
  const handleBeforeInput = (_input: string, _editorState: EditorState) => {
    if (remaining === 0) {
      return "handled";
    } else {
      return "not-handled";
    }
  };
 
  // Only the "rich-paste" editor (legal documents) intercepts pastes, keeping
  // the formatting it can model — heading levels, bold/italic/underline/
  // strikethrough, alignment, lists, links and tables (pastedContent.ts).
  // Everything else returns false and falls through to the default plain-text
  // paste (stripPastedStyles). The change goes through the host pipeline, NOT
  // the rdw onChange the library hands this callback — see the TableHost note.
  const handlePastedText = (_text: string, html: string): boolean => {
    if (!options?.includes("rich-paste") || !html) return false;
    const content = parsePastedHtml(html, {
      tables: options?.includes("table"),
    });
    Iif (!content) return false;
    handleEditorChangeRef.current?.(
      insertPastedContent(editorStateRef.current, content),
    );
    return true;
  };
 
  useEffect(() => {
    Eif (!defaultValue) return;
    const currentText = value?.getPlainText() ?? "";
    const defaultText = defaultValue.getPlainText();
    if (!currentText && defaultText) {
      setEditorState(EditorState.createWithContent(defaultValue));
    }
  }, [defaultValue]);
 
  const handleReturn = (
    e: SyntheticKeyboardEvent,
    editorState: EditorState,
  ) => {
    const currentBlockKey = editorState.getSelection().getStartKey();
    const currentBlock = editorState
      .getCurrentContent()
      .getBlockForKey(currentBlockKey);
 
    if (
      ["ordered-list-item", "unordered-list-item"].includes(
        currentBlock.getType(),
      )
    ) {
      updateLastListItem(editorState);
    }
 
    return false;
  };
 
  return (
    <>
      <Stack gap="9px">
        {label ? (
          <GiveText fontWeight={400} fontSize="14px" color="primary">
            {label}
          </GiveText>
        ) : null}
        <Container variant={variant}>
          {/* handleBeforeInput exists in draft-js but not passed on react-draft
          Editor Props */}
          {/* @ts-ignore (optional: suppress specific TypeScript error) */}
          <Editor
            handleReturn={handleReturn}
            editorState={editorState}
            // @ts-ignore blockStyleFn is a draft-js Editor prop not declared on react-draft-wysiwyg-next's EditorProps
            blockStyleFn={buildBlockStyleFn({
              paragraphSmall: options?.includes("paragraph-small"),
            })}
            // TABLE-entity atomic blocks (legal documents). IMAGE atomics
            // still fall through to the library's own renderer. TableBlock.tsx
            customBlockRenderFunc={tableBlockRenderFunc}
            toolbarClassName="toolbarClassName"
            wrapperClassName="wrapperClassName"
            editorClassName="editorClassName"
            onEditorStateChange={handleEditorChange}
            handlePastedText={handlePastedText}
            stripPastedStyles={true}
            // @ts-ignore (optional: suppress specific TypeScript error)
            handleBeforeInput={handleBeforeInput}
            toolbar={{
              options: [],
              link: { options: [] },
              inline: {
                options: [],
              },
              list: { options: [] },
              blockType: { options: [] },
              image: { options: [], alignmentEnabled: false },
            }}
            toolbarCustomButtons={[
              ...(prependedCustomActions 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")}
              />,
              <IconWrapper
                key="strikethrough"
                icon={TextStrikethroughIcon}
                state={getInlineStyleState("STRIKETHROUGH")}
                onClick={() => toggleInlineStyle("STRIKETHROUGH")}
              />,
              <HorizontalSeparator key="separator-3" />,
              ...apendedCustomActions,
              options?.includes("ordered-items") && (
                <OrderedList
                  key="ordered-items"
                  editorState={editorState}
                  handleEditorChange={handleEditorChange}
                />
              ),
              options?.includes("table") && (
                <TableInsertControl
                  key="table"
                  hostEditorState={editorState}
                  onInsert={handleEditorChange}
                />
              ),
              <IconWrapper
                state={getListStyleState()}
                key="list"
                icon={ListDashesIcon}
                onClick={toggleList}
              />,
              <LinkModal
                editorState={editorState}
                key="link"
                onSubmit={handleAddLink}
              />,
 
              options?.includes("image") && (
                <ImageLink editorState={editorState} key="image" />
              ),
              // Drop gated-out (falsy) entries — react-draft-wysiwyg-next
              // cloneElement()s every custom button and throws on `false`.
            ].filter(Boolean)}
          />
        </Container>
        {showCharCount ? (
          <GiveText fontSize="12px" sx={{ color: palette.text.secondary }}>
            {editorStateLen}/{maxLength}
          </GiveText>
        ) : null}
      </Stack>
    </>
  );
}
 
// The document variant OMITS the form-input box constraints (border, fixed
// height, padding) and the toolbar's bottom margin instead of overriding them:
// consumer sx targeting the same classes sits at equal specificity, so any
// counter-declaration here would win or lose purely on emotion insertion
// order (child styles insert after the parent's sx on a fresh mount).
const Container = styled(Stack, {
  shouldForwardProp: (prop) => prop !== "variant",
})<{ variant: RichInputVariant }>(({ theme, variant }) => ({
  "& .editorClassName": {
    ...(variant === "form" && {
      border: `1px solid ${theme.palette.border?.secondary}`,
      borderRadius: "12px",
      minHeight: "172px",
      maxHeight: "172px",
      padding: "12px",
    }),
    "& p, & ul, & ol, & h1, & h2, & h3, & h4, & h5, & h6": {
      margin: 0,
      padding: 0,
    },
    "& p, & h1, & h2, & h3, & h4, & h5, & h6": {
      lineHeight: 1.3,
      fontWeight: 400,
    },
    // Documents keep a real heading scale — the flat weight above is meant for
    // the short form inputs, and would render a pasted agreement's headings at
    // body weight. Declared after it so it wins at equal specificity.
    ...(variant === "document" && documentHeadingSx),
    "& img": {
      borderRadius: "8px",
    },
    "& .rdw-paragraph-small, & .rdw-paragraph-small *": {
      fontSize: "12px",
    },
    // Draft.css (embedded in the lib stylesheet) puts `text-align: left`
    // directly on the inner block div — see blockStyle.ts.
    ...alignmentInnerDivSx,
    "& div": {
      margin: "0",
      lineHeight: 1.3,
      marginBottom: 16,
    },
    "& li": {
      listStyleType: "none",
      marginLeft: "0",
      "&::before": {
        display: "none",
      },
    },
  },
  "& .toolbarClassName": {
    borderRadius: "12px",
    backgroundColor: theme.palette.surface?.secondary,
    padding: "4px 8px",
    ...(variant === "form" && { marginBottom: 10 }),
    "& .rdw-option-wrapper": {
      backgroundColor: "transparent",
    },
    "& .rdw-option-wrapper:hover": {
      boxShadow: "unset",
    },
  },
  "& .DraftEditor-root": {
    overflow: "hidden",
  },
  "& .editorClassName a": {
    color: theme.palette.primitive?.blue[100],
    fontSize: "14px",
    fontWeight: 400,
  },
  "& .rdw-link-decorator-wrapper": {
    position: "relative",
    "& .rdw-link-decorator-icon": {
      display: "none",
    },
  },
}));
 
const HorizontalSeparator = styled("div")(({ theme }) => ({
  borderRight: `1px solid ${theme.palette.border?.secondary}`,
  height: "18px",
  margin: "auto 0",
}));
 
export default HFRichInput;