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

29.41% Statements 5/17
0% Branches 0/5
16.66% Functions 1/6
29.41% Lines 5/17

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                            45x 447x                                           447x   447x                   447x                                                            
import { ImageIcon } from "@phosphor-icons/react";
import { EditorState } from "react-draft-wysiwyg-next";
import { WrapperActionComponent } from "./components/Wrapper";
import IconWrapper from "./IconWrapper";
import { useState } from "react";
import { AtomicBlockUtils } from "draft-js";
import ImageModalNew from "@sections/PayBuilder/Forms/About/ImageModalNew";
import { MediaItem } from "@sections/PayBuilder/provider/provider.type";
 
interface Props {
  onChange?: (vals: any) => void;
  editorState: EditorState;
}
 
export const ImageLink = ({ onChange, editorState }: Props) => {
  const onAddImage = (src: string) => {
    const entityData = {
      src,
      height: "auto",
      width: "100%",
      style: "border-radius: 10px;",
    };
    const entityKey = editorState
      .getCurrentContent()
      .createEntity("IMAGE", "MUTABLE", entityData)
      .getLastCreatedEntityKey();
 
    const newEditorState = AtomicBlockUtils.insertAtomicBlock(
      editorState,
      entityKey,
      " ",
    );
    if (typeof onChange === "function") {
      onChange(newEditorState);
    }
  };
 
  const [isImageModalOpen, setIsImageModalOpen] = useState(false);
 
  const handleSelect = (item?: MediaItem, shouldClose = true) => {
    if (item?.URL) {
      onAddImage(item.URL + "/original");
    }
    //onChange seems async. If the modal is closed before letting the ediotr to update itself, the image doesn't get rendered
    setTimeout(() => {
      setIsImageModalOpen(false);
    }, 0);
  };
 
  return (
    <>
      <WrapperActionComponent
        value=""
        menuWidth={392}
        activeIndex={-1}
        overrideOnClick={false}
        anchor={
          <IconWrapper
            onClick={() => {
              setIsImageModalOpen(true);
              //onclick gets overided
              return;
            }}
            icon={ImageIcon}
          />
        }
      />
      <ImageModalNew
        handleSelect={handleSelect}
        open={isImageModalOpen}
        onClose={() => {
          setIsImageModalOpen(false);
        }}
        selectedImage={{} as MediaItem}
        noEditing
      />
    </>
  );
};