Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

18.9 KB
Raw Blame
'use client';

import { isDesktop } from '@lobechat/const';
import type { IEditor } from '@lobehub/editor';
import {
  ReactAlertPlugin,
  ReactChartPlugin,
  ReactFootnotePlugin,
  ReactImagePlugin,
  ReactLinkPlugin,
  ReactLiteXmlPlugin,
  ReactMathPlugin,
  ReactMentionPlugin,
  ReactSlashOption,
  ReactSlashPlugin,
  ReactTablePlugin,
  ReactToolbarPlugin,
  ReactVideoPlugin,
} from '@lobehub/editor';
import { Editor, useEditorState } from '@lobehub/editor/react';
import { createStaticStyles, cx } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import type { CSSProperties, RefObject } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';

import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';
import { writeTopicCommentMentionMarkdown } from '@/features/Portal/TopicComments/editorUtils';

import { type EditorCanvasProps } from './EditorCanvas';
import InlineToolbar from './InlineToolbar';
import LinearFilePlugin from './LinearFilePlugin';
import { registerAttachmentClickOpen } from './registerAttachmentClickOpen';
import { registerBlockDecoratorCaretGuard } from './registerBlockDecoratorCaretGuard';
import { registerBlockDecoratorClickToWrite } from './registerBlockDecoratorClickToWrite';
import { registerImageFilePastePreference } from './registerImageFilePastePreference';
import { needsImageRehost, rehostImage } from './rehostImage';
import OrderedListNumberMenu from './richList/OrderedListNumberMenu';
import { LIST_HEADING_ATTRIBUTE, ReactRichListPlugin } from './richList/RichListPlugin';
import { useFileUpload, useImageUpload } from './useImageUpload';

interface FileFilter {
  extensions: string[];
  name: string;
}

const IMAGE_FILTERS: FileFilter[] = [
  { extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'avif'], name: 'Images' },
];

const VIDEO_FILTERS: FileFilter[] = [
  { extensions: ['mp4', 'webm', 'mov', 'm4v', 'ogv'], name: 'Videos' },
];

// Force the Lexical FileNode's outer `<span>` to render as its own block-
// level row inside the paragraph. The inner card visuals (icon + name + size
// + download button) live in `LinearFilePlugin`.
const fileNodeStyles = createStaticStyles(({ css }) => ({
  fileWrapper: css`
    display: block !important;
    width: 100% !important;
    margin-block: 8px !important;
  `,
}));

// A bullet item's marker at a given nesting depth. Lexical nests a list inside a
// `.editor_listItemNested` item; items holding only a nested list, and check
// list items, draw no bullet. `ul` outranks @lobehub/editor's own `-` marker rule.
const bullet = (depth: number) =>
  `${'.editor_listItemNested '.repeat(depth)}ul.editor_listUnordered > .editor_listItem:not(:has(ul), [role='checkbox'])::before`;

// Notion-style list markers in the theme color: a solid disc, then a hollow
// circle, then a square, repeating with depth; ordered list numbers match.
// A text color applied to the item still colors its marker.
const listMarkerStyles = createStaticStyles(({ css, cssVar }) => {
  // Resolved on the item itself, where Lexical sets `--listitem-marker-color`.
  const markerColor = `var(--listitem-marker-color, ${cssVar.colorPrimary})`;
  const markerSize = '0.375em';

  return {
    content: css`
      ol.editor_listOrdered > .editor_listItem::marker {
        color: ${markerColor};
      }

      ${bullet(0)}, ${bullet(3)} {
        content: '';

        display: inline-block;

        box-sizing: border-box;
        width: ${markerSize};
        height: ${markerSize};
        margin-inline: -0.9em calc(0.9em - ${markerSize});
        border-radius: 50%;

        vertical-align: middle;

        opacity: 1;
        background: ${markerColor};
      }

      ${bullet(1)}, ${bullet(4)} {
        border: 0.09em solid ${markerColor};
        background: transparent;
      }

      ${bullet(2)}, ${bullet(5)} {
        border: none;
        border-radius: 0.06em;
        background: ${markerColor};
      }

      /* A list item styled as a heading takes the heading's type scale
         (@lobehub/editor's header styles); its marker scales with it. */
      .editor_listItem[${LIST_HEADING_ATTRIBUTE}] {
        margin-block-start: max(
          calc(var(--lobe-markdown-header-multiple) * var(--lobe-markdown-margin-multiple) * 0.4em),
          var(--lobe-markdown-font-size)
        );
        /* Indent by the body font, so heading items line up with plain ones. */
        margin-inline-start: var(--lobe-markdown-font-size);
        font-weight: bold;
        line-height: 1.25;
      }

      .editor_listItem[${LIST_HEADING_ATTRIBUTE}='h1'] {
        font-size: calc(
          var(--lobe-markdown-font-size) * (1 + 1.5 * var(--lobe-markdown-header-multiple))
        );
      }

      .editor_listItem[${LIST_HEADING_ATTRIBUTE}='h2'] {
        font-size: calc(
          var(--lobe-markdown-font-size) * (1 + var(--lobe-markdown-header-multiple))
        );
      }

      .editor_listItem[${LIST_HEADING_ATTRIBUTE}='h3'] {
        font-size: calc(
          var(--lobe-markdown-font-size) * (1 + 0.5 * var(--lobe-markdown-header-multiple))
        );
      }

      .editor_listItem[${LIST_HEADING_ATTRIBUTE}='h4'] {
        font-size: calc(
          var(--lobe-markdown-font-size) * (1 + 0.25 * var(--lobe-markdown-header-multiple))
        );
      }
    `,
  };
});

/**
 * Base plugins for the editor (without image and toolbar, which need dynamic config)
 */
const STATIC_PLUGINS = [
  ReactLiteXmlPlugin,
  ...createChatInputRichPlugins({ linkPlugin: ReactLinkPlugin, mathPlugin: false }),
  // The kernel reads a plugin's config once at init, and `mentionOption` can
  // arrive later (workspace pages resolve their member source asynchronously),
  // so pin the member chip's markdown form here rather than relying on
  // `mentionOption.markdownWriter` being present at mount. Same writer as the
  // comment editors, so a chip serialises identically in every canvas.
  Editor.withProps(ReactMentionPlugin, { markdownWriter: writeTopicCommentMentionMarkdown }),
  ReactTablePlugin,
  ReactAlertPlugin,
  ReactFootnotePlugin,
  ReactChartPlugin,
  // After ReactListPlugin (in the rich plugins above), whose markdown it extends.
  ReactRichListPlugin,
];

const EDITOR_INIT_DATA_SOURCE_TYPES = ['json', 'markdown'] as const;
const EDITOR_INIT_RETRY_LIMIT = 30;
const EDITOR_INIT_RETRY_INTERVAL = 16;

interface InspectableEditor extends IEditor {
  dataTypeMap?: Map<string, unknown> | Record<string, unknown>;
}

const getEditorDataSourceTypes = (editor: InspectableEditor): string[] => {
  const dataTypeMap = editor.dataTypeMap;

  if (!dataTypeMap) return [];

  if (dataTypeMap instanceof Map) {
    return [...dataTypeMap.keys()].sort();
  }

  return Object.keys(dataTypeMap).sort();
};

const isEditorInitReady = (editor: IEditor) => {
  const inspectableEditor = editor as InspectableEditor;
  const dataSourceTypes = getEditorDataSourceTypes(inspectableEditor);

  return {
    dataSourceTypes,
    hasLexicalEditor: !!editor.getLexicalEditor?.(),
    isReady:
      !!editor.getLexicalEditor?.() &&
      EDITOR_INIT_DATA_SOURCE_TYPES.every((type) => dataSourceTypes.includes(type)),
  };
};

export interface InternalEditorProps extends EditorCanvasProps {
  /**
   * Optional lock ref to suppress content-change callback during programmatic document hydration.
   */
  contentChangeLockRef?: RefObject<boolean>;

  /**
   * Editor instance (required)
   */
  editor: IEditor;
}

/**
 * Internal EditorCanvas component that requires editor instance
 */
const InternalEditor = memo<InternalEditorProps>(
  ({
    allowContentBleed,
    blockImageCaretGuard = false,
    className,
    contentChangeLockRef,
    contentStyle,
    disabled,
    editable = true,
    editor,
    enableInlineMath = true,
    extraPlugins,
    floatingToolbar = true,
    getPopupContainer,
    mentionOption,
    onContentChange,
    onInit,
    onPressEnter,
    placeholder,
    plugins: customPlugins,
    readonlySelectionItems,
    slashItems,
    style,
    toolbarExtraItems,
  }) => {
    const { t } = useTranslation('file');
    const editorState = useEditorState(editor);
    const handleImageUpload = useImageUpload();
    const handleFileUpload = useFileUpload();

    const pickDesktopFile = useCallback(async (filters: FileFilter[]): Promise<File | null> => {
      if (!isDesktop) return null;
      const { ensureElectronIpc } = await import('@/utils/electron/ipc');
      const ipc = ensureElectronIpc();
      const result = await (ipc as any).localSystem.handlePickFile({ filters });
      if (result.canceled || !result.file) return null;
      const { data, mimeType, name } = result.file;
      return new File([data], name, { type: mimeType });
    }, []);
    const handlePickImage = useCallback(() => pickDesktopFile(IMAGE_FILTERS), [pickDesktopFile]);
    const handlePickVideo = useCallback(() => pickDesktopFile(VIDEO_FILTERS), [pickDesktopFile]);

    const finalPlaceholder = placeholder || t('pageEditor.editorPlaceholder');
    const wrapperStyle = useMemo<CSSProperties>(
      () => ({
        cursor: disabled ? 'not-allowed' : undefined,
        maxWidth: '100%',
        minWidth: 0,
        opacity: disabled ? 0.65 : undefined,
        overflow: allowContentBleed ? 'visible' : 'hidden',
        pointerEvents: disabled ? 'none' : undefined,
        width: '100%',
      }),
      [allowContentBleed, disabled],
    );

    // The `/` and `@` menus. `<Editor>` only mounts its slash plugin once a
    // menu has items, but the kernel instantiates a plugin only if it
    // registered before the editor initialised — so `@` members that load
    // after mount (the usual case for a comment box) would never open a menu.
    // Own the plugin here instead: it registers at mount whenever either menu
    // is configured, and later items reach it as an options update.
    const slashPlugin = useMemo(() => {
      if (!slashItems && !mentionOption) return;

      // The member chip's markdown writer is pinned on the mention plugin in
      // STATIC_PLUGINS; the menu only takes the search and select options.
      const { markdownWriter: _markdownWriter, ...mentionMenu } = mentionOption ?? {};

      return Editor.withProps(ReactSlashPlugin, {
        children: [
          slashItems && <ReactSlashOption items={slashItems} key="/" maxLength={8} trigger="/" />,
          mentionOption && (
            <ReactSlashOption
              key="@"
              maxLength={8}
              trigger="@"
              {...mentionMenu}
              items={mentionMenu.items ?? []}
            />
          ),
        ],
        getPopupContainer,
      });
    }, [getPopupContainer, mentionOption, slashItems]);

    // Build plugins array
    const plugins = useMemo(() => {
      // If custom plugins provided, use them directly
      if (customPlugins) return customPlugins;

      const imagePlugin = Editor.withProps(ReactImagePlugin, {
        defaultBlockImage: true,
        handleRehost: rehostImage,
        handleUpload: handleImageUpload,
        needRehost: (url: string) =>
          !!editor.getLexicalEditor?.()?.isEditable() && needsImageRehost(url),
        onPickFile: isDesktop ? handlePickImage : undefined,
      });

      const videoPlugin = Editor.withProps(ReactVideoPlugin, {
        handleUpload: handleFileUpload,
        onPickFile: isDesktop ? handlePickVideo : undefined,
      });

      const filePlugin = Editor.withProps(LinearFilePlugin, {
        handleUpload: handleFileUpload,
        theme: { file: fileNodeStyles.fileWrapper as unknown as string },
      });

      const mathPlugin = Editor.withProps(ReactMathPlugin, { enableInlineMath });

      // Build base plugins with optional extra plugins prepended. The slash
      // plugin leads so its element keeps a stable position (plugins are
      // keyed by index) when `extraPlugins` grows, e.g. once collab attaches.
      const basePlugins = [
        ...(slashPlugin ? [slashPlugin] : []),
        ...(extraPlugins ?? []),
        ...STATIC_PLUGINS,
        mathPlugin,
        imagePlugin,
        videoPlugin,
        filePlugin,
      ];

      if (!floatingToolbar || disabled) return basePlugins;

      // The formatting toolbar only when the editor is actually editable — a
      // locked / read-only page must not surface it on text selection (its
      // buttons would dispatch commands that never save).
      if (editable) {
        return [
          ...basePlugins,
          Editor.withProps(ReactToolbarPlugin, {
            children: (
              <InlineToolbar
                floating
                editor={editor}
                editorState={editorState}
                extraItems={toolbarExtraItems}
              />
            ),
          }),
        ];
      }

      // A read-only body can still be selected; selection-scoped actions that
      // never edit (comment on it, ask about it) stay reachable through a
      // toolbar that carries nothing else.
      if (readonlySelectionItems?.length) {
        return [
          ...basePlugins,
          Editor.withProps(ReactToolbarPlugin, {
            children: (
              <InlineToolbar
                floating
                selectionOnly
                editor={editor}
                editorState={editorState}
                extraItems={readonlySelectionItems}
              />
            ),
          }),
        ];
      }

      return basePlugins;
    }, [
      customPlugins,
      disabled,
      editable,
      editor,
      editorState,
      enableInlineMath,
      extraPlugins,
      floatingToolbar,
      handleFileUpload,
      handleImageUpload,
      handlePickImage,
      handlePickVideo,
      readonlySelectionItems,
      slashPlugin,
      toolbarExtraItems,
    ]);

    useEffect(() => {
      // for easier debug, mount editor instance to window
      if (editor) window.__editor = editor;

      return () => {
        window.__editor = undefined;
      };
    }, [editor]);

    // Open file attachments in a new tab on click (PDFs preview natively).
    // Workaround for @lobehub/editor's ReactFile decorator not exposing a
    // download / preview affordance.
    useEffect(() => {
      if (!editor) return;
      const unregister = registerAttachmentClickOpen(editor);
      return () => unregister?.();
    }, [editor]);

    // Copy Image from apps like Discord puts an image-only HTML flavor next to
    // the bitmap; upload the bitmap instead of rehosting the remote URL.
    useEffect(() => {
      if (!editor) return;
      const unregister = registerImageFilePastePreference(editor);
      return () => unregister?.();
    }, [editor]);

    // Opt-in (comment / task editors): keep the caret out of the root node around
    // block images by pushing an empty paragraph next to the image instead of
    // showing Lexical's horizontal root-level caret.
    useEffect(() => {
      if (!editor || !blockImageCaretGuard) return;
      const unregisterGuard = registerBlockDecoratorCaretGuard(editor);
      // A click in a block image's row, or typing with the image selected,
      // continues writing on the line after it.
      const unregisterClick = registerBlockDecoratorClickToWrite(editor);
      return () => {
        unregisterGuard?.();
        unregisterClick?.();
      };
    }, [blockImageCaretGuard, editor]);

    const onInitRef = useRef(onInit);
    const initializedEditorRef = useRef<IEditor | null>(null);

    useEffect(() => {
      onInitRef.current = onInit;
    }, [onInit]);

    useEffect(() => {
      if (!onInit) return;

      let retryCount = 0;
      let timer: ReturnType<typeof setTimeout> | undefined;
      let disposed = false;

      const notifyWhenReady = () => {
        if (disposed) return;

        const snapshot = isEditorInitReady(editor);

        if (snapshot.isReady) {
          if (initializedEditorRef.current !== editor) {
            initializedEditorRef.current = editor;
            onInitRef.current?.(editor);
          }

          return;
        }

        if (retryCount >= EDITOR_INIT_RETRY_LIMIT) {
          console.warn('[InternalEditor] onInit delayed because editor is not ready:', snapshot);
          return;
        }

        retryCount += 1;
        timer = setTimeout(notifyWhenReady, EDITOR_INIT_RETRY_INTERVAL);
      };

      notifyWhenReady();

      return () => {
        disposed = true;
        if (timer) clearTimeout(timer);
      };
    }, [editor, onInit]);

    // Use refs for stable references across re-renders
    const previousDocumentSnapshotRef = useRef<unknown>(undefined);
    const onContentChangeRef = useRef(onContentChange);
    onContentChangeRef.current = onContentChange;

    // Listen to Lexical updates directly to trigger content change
    // This bypasses @lobehub/editor's onTextChange which has issues with previousContent reset
    useEffect(() => {
      if (!editor) return;

      const lexicalEditor = editor.getLexicalEditor?.();
      if (!lexicalEditor) return;

      // Initialize snapshot before registering listener
      previousDocumentSnapshotRef.current = editor.getDocument('json');

      const unregister = lexicalEditor.registerUpdateListener(({ dirtyElements, dirtyLeaves }) => {
        // Skip selection-only / caret-movement updates — no content was mutated.
        if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return;

        const currentDocumentSnapshot = editor.getDocument('json');

        if (!isEqual(currentDocumentSnapshot, previousDocumentSnapshotRef.current)) {
          previousDocumentSnapshotRef.current = currentDocumentSnapshot;

          // During document hydration (e.g. route switch), we only advance snapshot
          // and skip external change callback to avoid false dirty checks.
          if (contentChangeLockRef?.current) return;
          if (disabled) return;

          onContentChangeRef.current?.();
        }
      });

      return () => {
        unregister();
      };
    }, [contentChangeLockRef, disabled, editor]); // Only depend on stable refs and editor

    return (
      <>
        <div
          className={cx(listMarkerStyles.content, className)}
          style={wrapperStyle}
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
          }}
        >
          <Editor
            content={''}
            editable={editable && !disabled}
            editor={editor}
            getPopupContainer={getPopupContainer}
            // Custom plugins replace the built-in set, slash plugin included,
            // so those callers keep `<Editor>`'s own menus.
            mentionOption={customPlugins ? mentionOption : undefined}
            placeholder={finalPlaceholder}
            plugins={plugins}
            slashOption={customPlugins && slashItems ? { items: slashItems } : undefined}
            type={'text'}
            style={{
              paddingBottom: 32,
              ...style,
              ...contentStyle,
            }}
            {...(onPressEnter ? { onPressEnter } : {})}
          />
        </div>
        {editable && !disabled && <OrderedListNumberMenu editor={editor} />}
      </>
    );
  },
);

InternalEditor.displayName = 'InternalEditor';

export default InternalEditor;