Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

11.8 KB
Raw Blame
import { useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useEditor, EditorContent, type Editor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
import { TableKit } from '@tiptap/extension-table';
import TaskItem from '@tiptap/extension-task-item';
import Placeholder from '@tiptap/extension-placeholder';
import Link from '@tiptap/extension-link';
import { common, createLowlight } from 'lowlight';
import { Markdown } from 'tiptap-markdown';
import { pasteMarkdown } from './pasteMarkdown';
import { ResizableImage } from './tiptap-image';
import { Mention } from '@/lib/tiptap-mention';
import { useSession } from '@/lib/auth-client';
import { useIssueRefs } from '@/context/issueRefs';
import { IssueRef } from './issueRefDecorations';
import { refreshDecorations } from './refreshDecorations';
import { SlashCommand } from '@/lib/tiptap-slash-command';
import { MarkdownTable } from './tiptap-table';
import { TightTaskList } from './tiptap-task-list';
import { Video } from './tiptap-video';
import { attachmentHtml, type Embeddable } from './attachmentEmbed';
import { openLinkOnModifierClick } from './modifierClickLink';
import { createLinkKeyboardHandlers } from './linkKeyboardHandlers';
import EditorImagePicker from './EditorImagePicker';
import EditorSelectionMenu from './EditorSelectionMenu';
import EditorTableMenu from './EditorTableMenu';
import EditorLinkPreview from './EditorLinkPreview';
import { useMentionCandidates, useMentionNames } from '@/hooks/useMentionCandidates';
import type { MentionSource } from '@/lib/api/endpoints/mentions';
import { useTranslations } from 'next-intl';

// Shared by every editor instance. A block with no language is detected by
// highlightAuto, so there is no language picker.
const lowlight = createLowlight(common);

export const editorStarterKitOptions = {
  codeBlock: false,
  link: false,
} as const;

// A minimal WYSIWYG editor over markdown text — no persistent toolbar, just a
// bubble menu on selection and a "/" command list (Linear/Notion-style). Content
// in and out is plain markdown (via tiptap-markdown), matching how descriptions
// are stored everywhere else in the pipeline.
export default function MarkdownEditor({
  defaultValue,
  onChange,
  onBlur,
  onReady,
  placeholder,
  className,
  editable = true,
  uploadFile,
  imageAttachments,
  readingLinks = true,
  mentions,
}: {
  defaultValue: string;
  onChange?: (markdown: string) => void;
  onBlur?: (markdown: string) => void;
  // Exposes the editor instance so a parent can read the live markdown (via
  // editor.storage.markdown.getMarkdown()) or insert content at the cursor.
  onReady?: (editor: Editor | null) => void;
  placeholder?: string;
  className?: string;
  // When false the content is read-only (no bubble menu, no editing) — used to
  // render comment bodies as markdown.
  editable?: boolean;
  // When set, files dropped onto the editor are uploaded and inserted at the
  // drop position (image/video inline, other files as a link).
  uploadFile?: (file: File) => Promise<Embeddable>;
  // Offered in a picker, to embed an upload again. Omitted where there is nothing
  // stored to read them from yet (a create dialog), which drops the picker.
  imageAttachments?: Embeddable[];
  readingLinks?: boolean;
  // Where the text is written, which decides who the "@" menu offers. Without it the
  // menu offers nobody: a mention in the text would reach no one.
  mentions?: MentionSource;
}) {
  const t = useTranslations('common.editor');
  const editorRef = useRef<Editor | null>(null);
  const linkKeyboardHandlers = useMemo(() => createLinkKeyboardHandlers(true), []);
  // Held in a ref because the extensions are built once: the "@" menu reads the
  // roster through it, so a list that arrives later is still offered.
  const router = useRouter();
  const { data: session } = useSession();
  const issueRefs = useIssueRefs();
  const mentionCandidates = useMentionCandidates(mentions ?? null);
  const mentionCandidatesRef = useRef(mentionCandidates);
  mentionCandidatesRef.current = mentionCandidates;
  const mentionNames = useMentionNames();
  const mentionNamesRef = useRef(mentionNames);
  mentionNamesRef.current = mentionNames;
  const issueRefsRef = useRef(issueRefs);
  issueRefsRef.current = issueRefs;
  const openIssueRefRef = useRef(router.push);
  openIssueRefRef.current = (href: string) => router.push(href);
  const selfHandle = session?.user.username ?? '';
  const selfHandleRef = useRef(selfHandle);
  selfHandleRef.current = selfHandle;
  const editableRef = useRef(editable);
  editableRef.current = editable;
  // False while the field can be typed into but has no focus: the chip shows, and
  // swaps for the plain identifier only once editing actually starts.
  const focusedRef = useRef(false);
  const [focused, setFocused] = useState(false);
  // Whether the document has changed since this editor was mounted. The markdown
  // round trip is not an identity: the link extension's autolink parses a bare URL
  // into a link node, which serialises back in angle brackets. A blur reporting every
  // time would hand its caller markdown that differs from the stored text after a
  // focus that changed nothing. Set by onUpdate; a caller keyed on the value it stores
  // (IssueDetailContent, IssueCustomFieldBody) remounts on a save and starts a fresh
  // one, so a save that fails still reports on the next blur.
  const changedRef = useRef(false);
  const [imagePickerOpen, setImagePickerOpen] = useState(false);

  // Upload each file and insert it (image/video inline, other files as a link)
  // starting at `pos`, advancing past each insertion. Shared by drop and paste.
  const insertFiles = (files: FileList, pos: number) => {
    void (async () => {
      for (const file of Array.from(files)) {
        const a = await uploadFile?.(file).catch(() => null);
        const ed = editorRef.current;
        if (!a || !ed) continue;
        ed.chain().insertContentAt(pos, attachmentHtml(a)).focus().run();
        pos = ed.state.selection.to;
      }
    })();
  };

  const editor = useEditor({
    immediatelyRender: false,
    editable,
    extensions: [
      // Replaces StarterKit's plain code block, keeping the node name codeBlock.
      StarterKit.configure(editorStarterKitOptions),
      CodeBlockLowlight.configure({ lowlight }),
      Placeholder.configure({ placeholder }),
      Link.configure({
        openOnClick: false,
        autolink: true,
        HTMLAttributes: { class: 'cursor-pointer', tabindex: '0' },
      }),
      // Renders ![](url) markdown inline.
      ResizableImage,
      // Renders an @username in the text as a mention chip, and offers who a mention
      // written here reaches while one is typed.
      Mention.configure({
        items: () => mentionCandidatesRef.current,
        self: () => selfHandleRef.current,
        name: (handle) => mentionNamesRef.current.get(handle),
      }),
      // Paints KEY-123 as a link without writing the link into the markdown.
      IssueRef.configure({
        refs: () => issueRefsRef.current.refs,
        open: (href) => openIssueRefRef.current(href),
        rich: () => issueRefsRef.current.resolve && (!editableRef.current || !focusedRef.current),
      }),
      // Renders video attachments as an inline <video> player.
      Video,
      // TableKit carries the row and cell nodes around MarkdownTable's table node.
      // Column widths are not resizable: markdown carries no width, so a resized
      // column would be lost the next time the description is read back.
      TableKit.configure({ table: false }),
      MarkdownTable.configure({ resizable: false }),
      TightTaskList,
      TaskItem.configure({ nested: true }),
      SlashCommand.configure({
        codeBlockLabel: t('codeBlock'),
        taskListLabel: t('todoList'),
        tableLabel: t('table'),
        image: imageAttachments
          ? { label: t('image'), onPick: () => setImagePickerOpen(true) }
          : undefined,
      }),
      // html:true so the custom <video> tag survives the markdown round-trip.
      // tiptap only instantiates nodes declared in its schema (there is no
      // script/iframe node), so this does not allow arbitrary HTML to execute.
      // breaks:true renders a single newline as a line break (matching the
      // pipeline's post-doc format, where "Source:"/"Website:" field lines are
      // separated by single \n — the same breaks:true semantics Plane/Linear use).
      Markdown.configure({ html: true, linkify: true, breaks: true }),
    ],
    content: defaultValue,
    editorProps: {
      attributes: {
        // flex-1 so the typing area covers a container taller than the text.
        class: 'md-content flex-1 focus:outline-none',
      },
      handleClick(view, _pos, event) {
        return openLinkOnModifierClick(event, view.dom);
      },
      handleDOMEvents: linkKeyboardHandlers,
      // Files dropped from the OS are uploaded, then inserted at the drop
      // position. Internal moves and attachment-card drags (which carry
      // text/html, not files) fall through to tiptap's default handling.
      handleDrop(view, event, _slice, moved) {
        if (moved || !uploadFile) return false;
        const files = event.dataTransfer?.files;
        if (!files || files.length === 0) return false;
        event.preventDefault();
        const coords = view.posAtCoords({ left: event.clientX, top: event.clientY });
        insertFiles(files, coords?.pos ?? view.state.selection.to);
        return true;
      },
      // A pasted screenshot or copied file arrives as clipboard files: upload
      // each and insert at the cursor, same as a drop.
      handlePaste(view, event) {
        const files = event.clipboardData?.files;
        if (uploadFile && files && files.length > 0) {
          event.preventDefault();
          insertFiles(files, view.state.selection.to);
          return true;
        }
        const editor = editorRef.current;
        if (!editor) return false;
        return pasteMarkdown(editor, event.clipboardData);
      },
    },
    onUpdate: ({ editor }) => {
      changedRef.current = true;
      onChange?.(editor.storage.markdown.getMarkdown());
    },
    onFocus: () => {
      focusedRef.current = true;
      setFocused(true);
    },
    onBlur: ({ editor }) => {
      focusedRef.current = false;
      setFocused(false);
      if (changedRef.current) onBlur?.(editor.storage.markdown.getMarkdown());
    },
  });

  useEffect(() => {
    editorRef.current = editor;
    onReady?.(editor);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [editor]);

  const issueRefList = issueRefs.refs.join(',');
  useEffect(() => {
    // After the commit. The refresh mounts the chip, and doing it here calls flushSync.
    const frame = requestAnimationFrame(() => refreshDecorations(editor));
    return () => cancelAnimationFrame(frame);
  }, [editor, issueRefList, issueRefs.resolve, selfHandle, editable, focused]);

  if (!editor) return null;

  return (
    <div className={className}>
      {editable && <EditorSelectionMenu editor={editor} taskList />}
      {editable && <EditorTableMenu editor={editor} />}
      {/* Grows with the text rather than being pinned to the container's height,
          so a container that scrolls measures the overflow and shows a bar. */}
      <EditorContent editor={editor} className="flex min-h-full flex-col" />
      <EditorLinkPreview editor={editor} source={defaultValue} compact={readingLinks} />
      {imageAttachments && (
        <EditorImagePicker
          open={imagePickerOpen}
          images={imageAttachments}
          onClose={() => setImagePickerOpen(false)}
          onPick={(a) => {
            setImagePickerOpen(false);
            editor.chain().focus().insertContent(attachmentHtml(a)).run();
          }}
        />
      )}
    </div>
  );
}