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.

5.8 KB
Raw Blame
'use client';

import { createContext, type ReactNode, type RefObject, use, useEffect } from 'react';

import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { usePermission } from '@/hooks/usePermission';

import { isDocumentCommentsUnavailable } from '../isDocumentUnavailableError';
import { usePageEditorStore } from '../store';
import { DocumentCommentAnchorsProvider } from './anchor/context';
import DocumentCommentHighlightStyle from './anchor/HighlightStyle';
import { readAnchoredDraftAnchor, restoreFailedAnchoredDraft } from './Composer';
import type { DocumentCommentsState } from './useDocumentCommentsState';
import { useDocumentCommentsState } from './useDocumentCommentsState';

const DocumentCommentsContext = createContext<DocumentCommentsState | null>(null);

interface DocumentCommentsProviderProps {
  children: ReactNode;
  documentId: string;
  /**
   * Whether the editor renders its own right panel. Without one there is no
   * comments panel, and anchored threads list below the body instead.
   */
  panelAvailable: boolean;
  /** The body's scroll container; the panel's cards follow its scroll. */
  paneRef: RefObject<HTMLElement | null>;
}

const DocumentCommentsStateProvider = ({
  children,
  documentId,
  paneRef,
  panelAvailable,
}: DocumentCommentsProviderProps) => {
  const workspaceId = useActiveWorkspaceId();
  const { allowed: canCreate } = usePermission('create_content');
  const commentsPanelOpen = usePageEditorStore((s) => s.commentsPanelOpen);
  const setCommentsPanelOpen = usePageEditorStore((s) => s.setCommentsPanelOpen);
  const gutterEnabled = panelAvailable && commentsPanelOpen;
  const state = useDocumentCommentsState({ documentId, gutterEnabled, paneRef, panelAvailable });

  // The gutter composer only mounts once a pending anchor exists in the
  // store, but the store doesn't survive a reload while the draft (in
  // localStorage) does. Republish it here, in a provider that is always
  // mounted for the document, so a reload mid-draft doesn't strand it.
  // Gated on the current permission: `Composer` renders nothing without it,
  // so restoring the anchor for a since-revoked member would only leave a
  // permanently empty, undismissable pending card β€” the draft stays in
  // storage, recoverable once the permission comes back.
  //
  // The same moment β€” the shared slot being free β€” is when a failed gutter
  // submission stashed while a newer draft owned that slot gets handed back
  // (see `Composer`'s `preserveFailedAnchoredDraft`): re-checked whenever
  // the slot frees, i.e. after the newer draft is sent or cancelled, not
  // only on mount. Only in a panel-capable layout, where no composer is
  // mounted while the slot is free; the inline box below the body adopts
  // the stash itself, since it already holds the slot's state.
  const hasPendingForDocument = usePageEditorStore(
    (s) => s.pendingCommentAnchor?.documentId === documentId,
  );
  const setPendingCommentAnchor = usePageEditorStore((s) => s.setPendingCommentAnchor);
  useEffect(() => {
    if (!canCreate || hasPendingForDocument) return;
    const anchor =
      readAnchoredDraftAnchor(workspaceId, documentId) ??
      (panelAvailable
        ? restoreFailedAnchoredDraft(workspaceId, documentId)?.selectionAnchor
        : undefined);
    if (anchor) setPendingCommentAnchor({ anchor, documentId });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [documentId, canCreate, hasPendingForDocument, panelAvailable]);

  // A selection being commented on, or a run picked in the body, is answered
  // in the comments panel: open it on demand. Keyed on tick counters, not the
  // picked value itself β€” both the store and `selectedRootId` compare by
  // content, so a repeated pick of the same run would otherwise look like no
  // change β€” so picking again after the panel was closed opens it again,
  // while closing it is never undone by the pick that opened it.
  const pickVersion = usePageEditorStore((s) =>
    s.pendingCommentAnchor?.documentId === documentId ? s.pendingCommentAnchorVersion : 0,
  );
  const { pickTick, selectedRootId } = state.anchors;
  useEffect(() => {
    if (!panelAvailable || !(pickVersion || pickTick || selectedRootId)) return;
    setCommentsPanelOpen(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pickVersion, pickTick, selectedRootId]);

  // Access to the page was revoked (it went private) or it is gone: every
  // comment surface β€” list, panel, marker, header toggle β€” reads this context,
  // so publish none rather than cached threads or a stacked load failure. SWR
  // keeps the last pages next to the error, so check the error, not the data.
  return (
    <DocumentCommentsContext value={isDocumentCommentsUnavailable(state) ? null : state}>
      <DocumentCommentAnchorsProvider value={state.anchors}>
        <DocumentCommentHighlightStyle />
        {children}
      </DocumentCommentAnchorsProvider>
    </DocumentCommentsContext>
  );
};

/**
 * Hosts the comment state once for the whole editor so the panel beside the
 * text, the header toggle and the list below the body read the same caches.
 * Renders the children untouched when comments are unavailable (no
 * workspace, no document).
 */
export const DocumentCommentsProvider = ({
  children,
  documentId,
  paneRef,
  panelAvailable,
}: Omit<DocumentCommentsProviderProps, 'documentId'> & { documentId?: string }) => {
  const workspaceId = useActiveWorkspaceId();
  if (!workspaceId || !documentId) return children;
  return (
    <DocumentCommentsStateProvider
      documentId={documentId}
      key={documentId}
      paneRef={paneRef}
      panelAvailable={panelAvailable}
    >
      {children}
    </DocumentCommentsStateProvider>
  );
};

/** `null` outside a provider, i.e. where comments are unavailable. */
export const useDocumentComments = () => use(DocumentCommentsContext);