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

18.03% Statements 11/61
8.57% Branches 3/35
38.46% Functions 5/13
15.51% Lines 9/58

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                                675x                         45x           468x   468x                                                                                                                                                                                                                                                                 468x 43x       468x 301x         468x                    
import {
  getSelectionCustomInlineStyle,
  toggleCustomInlineStyle as tg,
} from "draftjs-utils";
import { useMemo, useRef } from "react";
import { fontSizes } from "./const";
import { WrapperActionComponent } from "../components/Wrapper";
import { EditorState } from "react-draft-wysiwyg-next";
import { Modifier, SelectionState, EditorState as ES } from "draft-js";
import { updateRichEditorText } from "../RichTextUtils";
import { EditorMode } from "../richInput.types";
import {
  isAllSelected,
  updateAllSelectedInlineFontSize,
} from "./utils";
 
const FONT_SIZE_STYLES = fontSizes.map((x) => `fontsize-${x.value}`);
 
interface Props {
  onChange?: (value: any) => void;
  editorState: EditorState;
  toggleCustomInlineStyle?: (
    editorState: EditorState,
    styleType: any,
    styleValue: any,
  ) => any;
  editorMode: EditorMode;
}
 
export const FontSizeMenuSelector = ({
  onChange,
  editorState,
  toggleCustomInlineStyle,
  editorMode,
}: Props) => {
  const customFontSize = useRef("16");
 
  const clickHandler = {
    [EditorMode.SINGLE_LINE]: (option: any) => {
      const updateFn = (newState: EditorState) => {
        return toggleCustomInlineStyle
          ? toggleCustomInlineStyle(newState, "fontsize", option.value)
          : tg(newState, "fontSize", option.value);
      };
 
      updateRichEditorText(
        editorState,
        (newState: EditorState) => updateFn(newState),
        onChange,
      );
    },
    [EditorMode.MULTI_LINE]: (option: any) => {
      let newEditorState = editorState;
      let contentState = newEditorState.getCurrentContent();
      const fontSizeValue = option.value;
 
      const editor = document.querySelector(".DraftEditor-root");
      const listItems = editor?.querySelectorAll("li");
 
      // Get the start and end block keys
      const selection = newEditorState.getSelection();
      const anchorKey = selection.getAnchorKey();
      const focusKey = selection.getFocusKey();
      const isCollapsed = newEditorState.getSelection().isCollapsed();
 
      if (isAllSelected(newEditorState)) {
        listItems?.forEach((li) => {
          li.setAttribute("style", `font-size:${fontSizeValue}px`);
        });
        const newEditorState = updateAllSelectedInlineFontSize(
          editorState,
          fontSizeValue,
          FONT_SIZE_STYLES,
        );
        onChange?.(newEditorState);
 
        return;
      }
 
      let blockKey = anchorKey;
 
      while (blockKey) {
        const block = contentState.getBlockForKey(blockKey);
        const blockText = block.getText();
 
        const startOffset = selection.getStartOffset();
        const endOffset = selection.getEndOffset();
        const isFullySelected =
          blockText.length > 0 &&
          startOffset === 0 &&
          endOffset === blockText.length;
 
        if (isFullySelected) {
          contentState = newEditorState.getCurrentContent();
 
          //If one row is divided in more spans with diferent style, if all the row is selected, the enw styles has to be applied to the entire row
          //without removing previosu styles, doesn't work
          FONT_SIZE_STYLES.forEach((style) => {
            contentState = Modifier.removeInlineStyle(
              contentState,
              selection,
              style,
            );
          });
 
          // Create a selection covering the entire block
          const blockSelection = SelectionState.createEmpty(blockKey).merge({
            anchorOffset: 0,
            focusOffset: block.getLength(),
          });
 
          contentState = Modifier.setBlockData(
            contentState,
            blockSelection,
            block.getData().set("fontSize", fontSizeValue),
          );
 
          // Push the updated ContentState back into the EditorState
          newEditorState = ES.push(
            newEditorState,
            contentState,
            "change-block-data",
          );
 
          listItems?.forEach((li) => {
            const liBlockKey = li.getAttribute("data-offset-key");
 
            if (liBlockKey && liBlockKey.split("-")[0] === blockKey) {
              li.setAttribute("style", `font-size:${fontSizeValue}px`);
            }
          });
        } else {
          if (isCollapsed && blockText.length === 0) {
            listItems?.forEach((li) => {
              const liBlockKey = li.getAttribute("data-offset-key");
 
              if (liBlockKey && liBlockKey.split("-")[0] === blockKey) {
                li.setAttribute("style", `font-size:${fontSizeValue}px`);
              }
            });
          }
          // For partial selection, update inline style only
          newEditorState = toggleCustomInlineStyle
            ? toggleCustomInlineStyle(newEditorState, "fontsize", fontSizeValue)
            : tg(newEditorState, "fontSize", fontSizeValue);
 
          if (newEditorState && typeof onChange === "function") {
            onChange(newEditorState);
          }
        }
 
        if (blockKey === focusKey) break;
        blockKey = contentState.getKeyAfter(blockKey);
      }
 
      //if any of the cases above are not trigered, update the font size
      //there are cases when there isnt anything from above tigered(start new list or press enter key)
      newEditorState = toggleCustomInlineStyle
        ? toggleCustomInlineStyle(newEditorState, "fontsize", option.value)
        : tg(newEditorState, "fontSize", option.value);
 
      onChange?.(newEditorState);
    },
  };
 
  const inlineState =
    useMemo(
      () => getSelectionCustomInlineStyle(editorState, ["FONTSIZE"]).FONTSIZE,
      [editorState],
    )?.split("-")[1] ?? customFontSize.current;
 
  const fontSizeActiveIndex = useMemo(
    () => fontSizes.findIndex((x) => inlineState === x.value),
    [inlineState],
  );
 
  //6'th index is 16 px
  return (
    <WrapperActionComponent
      value={fontSizes[fontSizeActiveIndex]?.label ?? fontSizes[6]?.label}
      options={fontSizes}
      menuWidth={66}
      activeIndex={fontSizeActiveIndex}
      handleClick={clickHandler[editorMode]}
    />
  );
};