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.

11.7 KB
Raw Blame
import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT, isDesktop } from '@lobechat/const';
import { confirmModal, toast } from '@lobehub/ui';
import debug from 'debug';
import { debounce } from 'es-toolkit/compat';
import { type StateCreator } from 'zustand';

import { type EditLockHealth } from '@/features/EditLock';
import { focusEditorStartLine } from '@/features/EditorCanvas/focusEditorStartLine';
import { useDocumentStore } from '@/store/document';
import { getElectronStoreState } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
import { useFileStore } from '@/store/file';

import { type PendingCommentAnchor, type RightPanelMode, type State } from './initialState';
import { initialState } from './initialState';

const log = debug('page:editor');

export interface Action {
  flushMetaSave: () => void;
  handleCopyLink: (t: (key: string) => string) => void;
  handleDelete: (t: (key: string) => string, onDeleteCallback?: () => void) => Promise<void>;
  /**
   * Enter in the title: save it and continue on the body's first line. `bodyText`
   * is the part of the title after the caret, which becomes that first line.
   */
  handleTitleSubmit: (bodyText?: string) => Promise<void>;
  initMeta: (title?: string, emoji?: string) => void;
  performMetaSave: () => Promise<void>;
  setCommentsPanelOpen: (open: boolean) => void;
  /**
   * The store outlives a document switch (the resource manager swaps `pageId`
   * on a mounted PageEditor), so a panel left open on the previous document
   * would otherwise show the next one's gutter with nothing selected.
   */
  setDocumentId: (documentId: string | undefined) => void;
  setEmoji: (emoji: string | undefined) => void;
  /**
   * Mirror the lock health from {@link useEditLock} into the store so banners and
   * draft persistence can observe deviations without re-deriving the state.
   */
  setLockHealth: (health: EditLockHealth) => void;
  setLockOwnerId: (ownerId: string | undefined) => void;
  /** True while the lock state is still being resolved (editor read-only meanwhile). */
  setLockPending: (pending: boolean) => void;
  /**
   * Record who holds the edit lock. `holderId` (+ `holderOwnerId`) is the single
   * source of truth; "locked by other" is derived against the current user/session
   * via {@link usePageLockedByOther}, never stored separately.
   */
  setLockState: (
    holderId: string | null,
    expiresAt?: Date | string | null,
    holderOwnerId?: string | null,
  ) => void;
  /** Hand a captured body selection to the comment composer, or clear it (`undefined`). */
  setPendingCommentAnchor: (pending: PendingCommentAnchor | undefined) => void;
  setRightPanelMode: (mode: RightPanelMode) => void;
  setTitle: (title: string) => void;
  /**
   * Adopt title/emoji pushed from the outside (document list refresh, sidebar
   * rename, realtime sync) — but only while the local meta is clean and idle.
   * While the user is typing, or a save is in flight, the local value wins;
   * otherwise a list refresh echoing the *previous* save would clobber the
   * characters typed since the last save.
   */
  syncMeta: (title?: string, emoji?: string) => void;
  triggerDebouncedMetaSave: () => void;
}

export type Store = State & Action;

export const store: (initState?: Partial<State>) => StateCreator<Store> =
  (initState) => (set, get) => {
    // Debounced save function for meta (title/emoji)
    let debouncedMetaSave: ReturnType<typeof debounce> | null = null;

    const getOrCreateDebouncedMetaSave = () => {
      if (!debouncedMetaSave) {
        debouncedMetaSave = debounce(
          async () => {
            try {
              await get().performMetaSave();
            } catch (error) {
              console.error('[PageEditor] Failed to auto-save meta:', error);
            }
          },
          EDITOR_DEBOUNCE_TIME,
          { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
        );
      }
      return debouncedMetaSave;
    };

    return {
      ...initialState,
      ...initState,

      flushMetaSave: () => {
        debouncedMetaSave?.flush();
      },

      handleCopyLink: (t) => {
        const { documentId } = get();
        if (documentId) {
          const appOrigin = isDesktop
            ? electronSyncSelectors.remoteServerUrl(getElectronStoreState())
            : window.location.origin;
          const url = `${appOrigin}${window.location.pathname}`;
          navigator.clipboard.writeText(url);
          toast.success(t('pageEditor.linkCopied'));
        }
      },

      handleDelete: async (t, onDeleteCallback) => {
        const { documentId } = get();
        if (!documentId) return;

        return new Promise((resolve, reject) => {
          confirmModal({
            cancelText: t('cancel'),
            content: t('pageEditor.deleteConfirm.content'),
            okButtonProps: { danger: true },
            okText: t('delete'),
            onOk: async () => {
              try {
                const { removeDocument } = useFileStore.getState();
                await removeDocument(documentId);
                toast.success(t('pageEditor.deleteSuccess'));
                onDeleteCallback?.();
                resolve();
              } catch (error) {
                log('Failed to delete page:', error);
                toast.error(t('pageEditor.deleteError'));
                reject(error);
              }
            },
            title: t('pageEditor.deleteConfirm.title'),
          });
        });
      },

      handleTitleSubmit: async (bodyText) => {
        const { editor, flushMetaSave } = get();

        // Flush the pending title save, then continue on a fresh first line of
        // the body (AFFiNE's doc title does the same). A bare `editor.focus()`
        // would restore the body's last caret — often the end of a long page.
        flushMetaSave();
        focusEditorStartLine(editor, bodyText);
      },

      initMeta: (title, emoji) => {
        set({
          emoji,
          isMetaDirty: false,
          lastSavedEmoji: emoji,
          lastSavedTitle: title,
          metaSaveStatus: 'idle',
          title,
        });
      },

      performMetaSave: async () => {
        const {
          documentId,
          title,
          emoji,
          lastSavedTitle,
          lastSavedEmoji,
          isMetaDirty,
          metaReadOnly,
          onTitleChange,
          onEmojiChange,
        } = get();

        // Backstop: never persist meta for a read-only doc, even if something
        // marked it dirty out-of-band. A title save also rewrites the filename
        // (DocumentService.updateDocument), which would desync a managed skill.
        if (!documentId || !isMetaDirty || metaReadOnly) return;

        set({ metaSaveStatus: 'saving' });

        try {
          // Trigger save via DocumentStore with metadata
          await useDocumentStore.getState().performSave(
            documentId,
            {
              emoji,
              title,
            },
            { metadataOnly: true, saveSource: 'autosave' },
          );

          // Notify parent after successful save. The callbacks were captured
          // with the request, so they still address the document that was saved.
          if (title !== lastSavedTitle) {
            onTitleChange?.(title || '');
          }
          if (emoji !== lastSavedEmoji) {
            onEmojiChange?.(emoji);
          }

          // The store outlives a document switch (see `setDocumentId`). If the
          // editor moved on to another document while this request was in
          // flight, the meta below belongs to that document: comparing it with
          // the saved values would mark it dirty, record the previous
          // document's title as its last-saved one and queue a save of it.
          const { title: currentTitle, emoji: currentEmoji, documentId: currentDocumentId } = get();
          if (currentDocumentId !== documentId) return;

          // The user may have kept typing while the request was in flight, so
          // re-derive dirtiness from the *current* meta instead of clearing it
          // blindly — otherwise those trailing edits would never be persisted.
          const stillDirty = currentTitle !== title || currentEmoji !== emoji;

          set({
            isMetaDirty: stillDirty,
            lastSavedEmoji: emoji,
            lastSavedTitle: title,
            metaSaveStatus: 'saved',
          });

          if (stillDirty) {
            get().triggerDebouncedMetaSave();
          }
        } catch (error) {
          console.error('[PageEditor] Failed to save meta:', error);
          if (get().documentId === documentId) set({ metaSaveStatus: 'idle' });
        }
      },

      setCommentsPanelOpen: (commentsPanelOpen) => {
        if (get().commentsPanelOpen !== commentsPanelOpen) set({ commentsPanelOpen });
      },

      setDocumentId: (documentId) => {
        if (get().documentId === documentId) return;
        // A restored anchored draft or a fresh pick reopens it for the new
        // document; nothing here to show it for should not carry over.
        set({ commentsPanelOpen: false, documentId });
      },

      setEmoji: (emoji: string | undefined) => {
        const { lastSavedEmoji, metaReadOnly, triggerDebouncedMetaSave } = get();

        if (metaReadOnly) return;

        const isDirty = emoji !== lastSavedEmoji;
        set({ emoji, isMetaDirty: isDirty });

        if (isDirty) {
          triggerDebouncedMetaSave();
        }
      },

      setLockHealth: (health) => {
        if (get().lockHealth !== health) set({ lockHealth: health });
      },

      setLockPending: (pending) => {
        if (get().isLockPending !== pending) set({ isLockPending: pending });
      },

      setLockOwnerId: (ownerId) => {
        if (get().lockOwnerId !== ownerId) set({ lockOwnerId: ownerId });
      },

      setLockState: (holderId, expiresAt = null, holderOwnerId = null) => {
        if (
          get().lockHolderId === holderId &&
          get().lockExpiresAt === expiresAt &&
          get().lockHolderOwnerId === holderOwnerId
        )
          return;
        set({ lockExpiresAt: expiresAt, lockHolderId: holderId, lockHolderOwnerId: holderOwnerId });
      },

      setPendingCommentAnchor: (pendingCommentAnchor) => {
        set((state) => ({
          pendingCommentAnchor,
          // `?? 0` guards a store instance hydrated before this counter existed
          // (a hot reload keeps the old state), which would otherwise tick to NaN.
          pendingCommentAnchorVersion: pendingCommentAnchor
            ? (state.pendingCommentAnchorVersion ?? 0) + 1
            : (state.pendingCommentAnchorVersion ?? 0),
        }));
      },

      setRightPanelMode: (rightPanelMode) => {
        set({ rightPanelMode });
      },

      setTitle: (title: string) => {
        const { lastSavedTitle, metaReadOnly, triggerDebouncedMetaSave } = get();

        // Ignore title writes from every source — manual UI, AI / page-agent
        // editTitle, title extraction — when the doc's meta is read-only. The
        // visible name is owned elsewhere (e.g. a skill bundle title).
        if (metaReadOnly) return;

        const isDirty = title !== lastSavedTitle;
        set({ isMetaDirty: isDirty, title });

        if (isDirty) {
          triggerDebouncedMetaSave();
        }
      },

      syncMeta: (title, emoji) => {
        const { isMetaDirty, metaSaveStatus, lastSavedTitle, lastSavedEmoji } = get();

        if (isMetaDirty || metaSaveStatus === 'saving') return;
        if (title === lastSavedTitle && emoji === lastSavedEmoji) return;

        set({
          emoji,
          isMetaDirty: false,
          lastSavedEmoji: emoji,
          lastSavedTitle: title,
          title,
        });
      },

      triggerDebouncedMetaSave: () => {
        const save = getOrCreateDebouncedMetaSave();
        save();
      },
    };
  };