All files / src/utils draft.editor.helpers.ts

13.04% Statements 3/23
0% Branches 0/10
0% Functions 0/3
14.28% Lines 3/21

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                118x               118x                                       118x                        
import {
  EditorState,
  convertToRaw,
  convertFromRaw,
  ContentState,
} from "draft-js";
import { safeParse } from ".";
 
export const editorStateToString = (description: EditorState): string => {
  if (!description) return "";
 
  const editorContent = description.getCurrentContent();
  const stringDescription = JSON.stringify(convertToRaw(editorContent));
  return stringDescription;
};
 
export const stringToEditorState = (description: string): EditorState => {
  if (!description) return EditorState.createEmpty();
 
  const parsed = safeParse(description);
 
  if (parsed) {
    try {
      const editorContent = convertFromRaw(parsed);
      return EditorState.createWithContent(editorContent);
    } catch {
      return EditorState.createWithContent(
        ContentState.createFromText(description),
      );
    }
  }
  return EditorState.createWithContent(
    ContentState.createFromText(description),
  );
};
 
export const convertMinibuilderDescription = (
  description?: EditorState | string | (() => string | EditorState),
): string | EditorState => {
  if (!description) {
    return "";
  } else if (typeof description === "function") {
    const callbackDescription = description();
    return convertMinibuilderDescription(callbackDescription);
  } else {
    return description;
  }
};