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.

7.1 KB
Raw Blame
'use client';

import { ActionIcon, Drawer, Flexbox, Icon } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { Menu, PanelLeftOpen, Pin } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Outlet, useParams, useSearchParams } from 'react-router';

import { ShellTopBar } from '@/features/PageShell';
import { RouteMetaBridge } from '@/features/RouteMeta';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';

import { useAcceptanceList } from '../hooks';
import { acceptanceHomePath } from '../Viewer/routes';
import AcceptanceListPanel from './AcceptanceListPanel';
import AcceptanceOnboarding from './AcceptanceOnboarding';
import { useAcceptanceProjectActionItems } from './AcceptanceProjectActions';
import AcceptanceScopeSwitcher from './AcceptanceScopeSwitcher';
import { useReportPanelExpand } from './useReportPanelExpand';

const styles = stylex.create({
  expandBtn: {
    cursor: 'pointer',
    position: 'absolute',
    zIndex: 20,
    insetBlockStart: '12px',
    insetInlineStart: '12px',
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: '28px',
    height: '28px',
    borderWidth: '1px',
    borderStyle: 'solid',
    borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },
    borderRadius: '6px',
    color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },
    backgroundColor: cssVar.colorBgContainer,
    backgroundImage: 'none',
  },
  main: {
    position: 'relative',
    flex: '1',
    minWidth: '0',
    height: '100%',
    backgroundColor: cssVar.colorBgContainer,
    backgroundImage: 'none',
  },
});

interface AcceptanceOnboardingState {
  data?: unknown[];
  enabled: boolean;
  error?: unknown;
  hasDeepLink?: boolean;
  isLoading?: boolean;
}

export const shouldShowAcceptanceOnboarding = ({
  data,
  enabled,
  error,
  hasDeepLink,
  isLoading,
}: AcceptanceOnboardingState) =>
  enabled && !hasDeepLink && !isLoading && !error && data?.length === 0;

interface AcceptanceWorkspaceProps {
  projectId?: string;
}

const AcceptanceWorkspace = memo<AcceptanceWorkspaceProps>(({ projectId }) => {
  const { t } = useTranslation('verify');
  const navigate = useWorkspaceAwareNavigate();
  const isSignedIn = useUserStore(authSelectors.isLogin);
  const panel = useReportPanelExpand();
  const projectActionItems = useAcceptanceProjectActionItems();
  const { acceptanceId, checkId } = useParams<{ acceptanceId: string; checkId: string }>();
  const [searchParams] = useSearchParams();
  const hasFocusedCheck = Boolean(checkId || searchParams.get('check'));

  /**
   * Inside a project the workspace is already wearing the `(main)` shell's
   * chrome, so it keeps its inline rail. The standalone `/acceptance` route —
   * registered outside `(main)`, with nothing above it — grows a top bar of
   * its own and keeps the list in a drawer, so a record can own the full width
   * without the collection disappearing. On a wide viewport the drawer can be
   * pinned into that same rail (its header then carries back + title);
   * collapsing the rail hands the list back to the drawer.
   */
  const standalone = !projectId;
  // Public report readers must not mount the private collection: its 401 would
  // trigger the global sign-in redirect, even though the report is public.
  const showList = !!isSignedIn && !hasFocusedCheck;
  const listInDrawer = standalone && (!isSignedIn || panel.isNarrow || !panel.pinned);
  const [listOpen, setListOpen] = useState(false);
  // Picking a row is what the drawer was opened for; once the route has moved
  // on (or the rail has taken over) the drawer has nothing left to do.
  useEffect(() => {
    setListOpen(false);
  }, [acceptanceId, listInDrawer]);

  const {
    data: allAcceptances,
    error,
    isLoading,
  } = useAcceptanceList(!!isSignedIn && (standalone ? !acceptanceId : showList), {
    filter: 'all',
    projectId,
  });
  const isFirstUse = shouldShowAcceptanceOnboarding({
    data: allAcceptances,
    enabled: !!isSignedIn && (standalone ? !acceptanceId : showList && !projectId),
    error,
    hasDeepLink: Boolean(acceptanceId),
    isLoading,
  });

  const topBar = standalone ? (
    <ShellTopBar
      scope={isSignedIn ? <AcceptanceScopeSwitcher /> : undefined}
      title={t('acceptance.workspace.title')}
      titleExtra={
        isSignedIn && (
          <>
            <ActionIcon
              icon={Menu}
              size={'small'}
              title={t('acceptance.shell.menu')}
              onClick={() => setListOpen(true)}
            />
            {!panel.isNarrow && (
              <ActionIcon
                icon={Pin}
                size={'small'}
                title={t('workspace.pin')}
                onClick={() => panel.setExpand(true)}
              />
            )}
          </>
        )
      }
      onBack={() => navigate(acceptanceHomePath())}
    />
  ) : null;

  if (isFirstUse) {
    return standalone ? (
      <Flexbox height={'100dvh'} style={{ overflow: 'hidden' }} width={'100%'}>
        <RouteMetaBridge />
        {topBar}
        <AcceptanceOnboarding />
      </Flexbox>
    ) : (
      <>
        <RouteMetaBridge />
        <AcceptanceOnboarding />
      </>
    );
  }

  if (!listInDrawer)
    return (
      <Flexbox horizontal height={'100dvh'} style={{ overflow: 'hidden' }} width={'100%'}>
        <RouteMetaBridge />
        {showList && (
          <AcceptanceListPanel
            {...panel}
            projectActionItems={projectActionItems}
            projectId={projectId}
          />
        )}
        <div {...stylex.props(styles.main)}>
          {showList && !panel.expand && (
            <button
              aria-label={t('workspace.expand')}
              {...stylex.props(styles.expandBtn)}
              title={t('workspace.expand')}
              type={'button'}
              onClick={() => panel.setExpand(true)}
            >
              <Icon icon={PanelLeftOpen} size={16} />
            </button>
          )}
          <Outlet />
        </div>
      </Flexbox>
    );

  return (
    <Flexbox height={'100dvh'} style={{ overflow: 'hidden' }} width={'100%'}>
      <RouteMetaBridge />
      {topBar}
      {isSignedIn && (
        <Drawer
          noHeader
          closable={false}
          containerMaxWidth={'100%'}
          open={listOpen}
          placement={'left'}
          styles={{ bodyContent: { height: '100%', minHeight: 0, overflow: 'hidden', padding: 0 } }}
          width={'min(360px, 88vw)'}
          onClose={() => setListOpen(false)}
        >
          <AcceptanceListPanel hosted {...panel} projectActionItems={projectActionItems} />
        </Drawer>
      )}
      <Flexbox horizontal flex={1} style={{ minHeight: 0 }} width={'100%'}>
        <div {...stylex.props(styles.main)}>
          <Outlet />
        </div>
      </Flexbox>
    </Flexbox>
  );
});

AcceptanceWorkspace.displayName = 'AcceptanceWorkspace';

export default AcceptanceWorkspace;