Skip to content

Commit

Permalink
feat(editor): output prefixed HTML
Browse files Browse the repository at this point in the history
  • Loading branch information
konstantinmuenster committed Dec 11, 2023
1 parent 2703a7a commit a03908b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 28 deletions.
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import {
EditorContent,
Extension,
JSONContent,
Mark,
Node,
useEditor,
} from "@tiptap/react";
import { EditorContent, Extension, Mark, Node, useEditor } from "@tiptap/react";
import { Blockquote } from "@tiptap/extension-blockquote";
import { Bold } from "@tiptap/extension-bold";
import { BulletList } from "@tiptap/extension-bullet-list";
Expand Down Expand Up @@ -59,29 +52,23 @@ const extensions: (Extension | Node | Mark)[] = [
Youtube,
];

export interface RichTextContent {
html?: string;
text?: string;
json?: JSONContent;
}
const OUTPUT_PREFIX = "<!--strapi-plugin-rich-text-output-->";
const removeOutputPrefix = (value: string) => value.replace(OUTPUT_PREFIX, "");
export const isRichText = (value: string) => value.startsWith(OUTPUT_PREFIX);

interface EditorProps {
initialContent: RichTextContent | string;
onChange: (value: RichTextContent) => void;
initialContent: string;
onChange: (value: string) => void;
placeholder: string | null;
disabled: boolean;
}

export default function Editor({ initialContent, onChange }: EditorProps) {
const editor = useEditor({
extensions,
content: initialContent,
content: removeOutputPrefix(initialContent),
onUpdate: ({ editor }) => {
onChange({
html: editor.getHTML(),
text: editor.getText(),
json: editor.getJSON(),
});
onChange(OUTPUT_PREFIX + editor.getHTML());
},
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Field, FieldLabel } from "@strapi/design-system/Field";
import { Typography } from "@strapi/design-system/Typography";
import { useIntl } from "react-intl";

import Editor, { RichTextContent } from "./Editor";
import Editor, { isRichText } from "./Editor";
import { createHTMLFromMarkdown } from "../../lib/markdown";

interface RichTextProps {
Expand Down Expand Up @@ -56,20 +56,20 @@ export default function RichText({
const { formatMessage } = useIntl();

const content = useMemo(() => {
try {
return (JSON.parse(value || "") as RichTextContent).json || "";
} catch {
return value ? createHTMLFromMarkdown(value) : "";
if (value) {
return isRichText(value) ? value : createHTMLFromMarkdown(value);
} else {
return "";
}
}, []);

const handleChange = useCallback(
(value: RichTextContent) => {
(value: string) => {
onChange({
target: {
name: name,
type: attribute.type,
value: JSON.stringify(value),
value: value,
},
});
},
Expand Down

0 comments on commit a03908b

Please sign in to comment.