Skip to content

The open alternative to Salesforce, designed for AI.

7.8 KB
Raw Blame
import { SkeletonLine } from '@/ui/feedback/skeleton/components/SkeletonLine';
import { styled } from '@linaria/react';
import { Fragment } from 'react';
import { useInView } from 'react-intersection-observer';

import { isDefined } from 'twenty-shared/utils';
import { themeCssVariables } from 'twenty-ui/theme';

import { LogConsoleTableHeaderCell } from '@/log-console/components/LogConsoleTableHeaderCell';
import { LOG_CONSOLE_ANIMATION_EASING } from '@/log-console/constants/LogConsoleAnimationEasing';
import { LOG_CONSOLE_TABLE_HTML_ID } from '@/log-console/constants/LogConsoleTableHtmlId';
import { LOG_CONSOLE_TABLE_SCROLL_WRAPPER_ID } from '@/log-console/constants/LogConsoleTableScrollWrapperId';
import { logConsoleColumnWidthsFamilyState } from '@/log-console/states/logConsoleColumnWidthsFamilyState';
import { type LogConsoleSource } from '@/log-console/types/LogConsoleSource';
import { getLogConsoleColumnWidthCSSVariableName } from '@/log-console/utils/getLogConsoleColumnWidthCSSVariableName';
import { updateLogConsoleTableCSSVariable } from '@/log-console/utils/updateLogConsoleTableCSSVariable';
import { Table } from '@/ui/layout/table/components/Table';
import { TableCell } from '@/ui/layout/table/components/TableCell';
import { TableRow } from '@/ui/layout/table/components/TableRow';
import { useAtomFamilyState } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyState';
import { ScrollWrapper } from '@/ui/utilities/scroll/components/ScrollWrapper';
import { useScrollWrapperHTMLElement } from '@/ui/utilities/scroll/hooks/useScrollWrapperHTMLElement';
import { type EventLogRecord } from '~/generated-metadata/graphql';
import { isDeeplyEqual } from '~/utils/isDeeplyEqual';

const SKELETON_ROW_COUNT = 8;

const StyledHeaderRow = styled(TableRow)`
  background-color: ${themeCssVariables.background.primary};
  border-radius: 0;
  box-shadow: inset 0 -1px 0 ${themeCssVariables.border.color.light};
  position: sticky;
  top: 0;
  z-index: 2;
`;

const StyledLiveEntryRow = styled(TableRow)`
  animation:
    logConsoleLiveEntryEntrance
      calc(${themeCssVariables.animation.duration.normal} * 1s)
      ${LOG_CONSOLE_ANIMATION_EASING},
    logConsoleLiveEntryHighlight
      calc(${themeCssVariables.animation.duration.slow} * 1s) ease-out;
  overflow: hidden;

  @keyframes logConsoleLiveEntryEntrance {
    from {
      height: 0;
      opacity: 0;
    }
  }

  @keyframes logConsoleLiveEntryHighlight {
    from {
      background-color: ${themeCssVariables.accent.quaternary};
    }
  }

  @media (prefers-reduced-motion: reduce) {
    animation: none;
  }
`;

const StyledTable = styled(Table)`
  box-sizing: border-box;
  min-width: min-content;
  padding-inline: ${themeCssVariables.spacing[3]};

  > [data-table-row] > :first-child {
    background-color: ${themeCssVariables.background.primary};
    border-radius: ${themeCssVariables.border.radius.md} 0 0
      ${themeCssVariables.border.radius.md};
    left: 0;
    position: sticky;
    z-index: 1;
  }

  > [data-table-row][data-clickable='true']:hover > :first-child,
  > [data-table-row][data-expanded] > :first-child {
    box-shadow: inset 0 0 0 100vmax
      ${themeCssVariables.background.transparent.light};
  }
`;

const StyledLoadMoreTrigger = styled.div`
  height: 1px;
`;

type LogConsoleTableProps = {
  source: LogConsoleSource;
  entries: EventLogRecord[];
  liveEntryCount: number;
  loading: boolean;
  hasNextPage: boolean;
  selectedEntry?: EventLogRecord;
  onLoadMore: () => void;
  onEntryClick: (entry: EventLogRecord) => void;
};

export const LogConsoleTable = ({
  source,
  entries,
  liveEntryCount,
  loading,
  hasNextPage,
  selectedEntry,
  onLoadMore,
  onEntryClick,
}: LogConsoleTableProps) => {
  const { scrollWrapperHTMLElement } = useScrollWrapperHTMLElement(
    LOG_CONSOLE_TABLE_SCROLL_WRAPPER_ID,
  );

  const { ref: loadMoreTriggerRef } = useInView({
    root: scrollWrapperHTMLElement,
    rootMargin: '400px',
    onChange: (inView) => {
      if (inView) {
        onLoadMore();
      }
    },
  });

  const [columnWidths, setColumnWidths] = useAtomFamilyState(
    logConsoleColumnWidthsFamilyState,
    source.id,
  );

  const columns = source.columns;

  const gridTemplateColumns = columns
    .map((column) => {
      const storedWidth = columnWidths[column.id];
      const track = isDefined(storedWidth)
        ? `${storedWidth}px`
        : column.gridTrack;

      return `var(${getLogConsoleColumnWidthCSSVariableName(column.id)}, ${track})`;
    })
    .join(' ');

  const clearColumnWidthPreview = (columnId: string) => {
    updateLogConsoleTableCSSVariable(
      getLogConsoleColumnWidthCSSVariableName(columnId),
      null,
    );
  };

  const handleColumnWidthPreview = (columnId: string, width: number) => {
    updateLogConsoleTableCSSVariable(
      getLogConsoleColumnWidthCSSVariableName(columnId),
      `${width}px`,
    );
  };

  const handleColumnWidthCommitted = (columnId: string, width: number) => {
    clearColumnWidthPreview(columnId);
    setColumnWidths((previousColumnWidths) => ({
      ...previousColumnWidths,
      [columnId]: width,
    }));
  };

  const handleColumnWidthReset = (columnId: string) => {
    clearColumnWidthPreview(columnId);
    setColumnWidths(
      ({ [columnId]: _resetColumnWidth, ...remainingColumnWidths }) =>
        remainingColumnWidths,
    );
  };

  const isInitialLoading = loading && entries.length === 0;

  const isLoadingNextPage = loading && hasNextPage;

  const storedEntryCount = entries.length - liveEntryCount;

  const renderEntryRow = (
    entry: EventLogRecord,
    key: number,
    isLiveEntry: boolean,
  ) => {
    const EntryRow = isLiveEntry ? StyledLiveEntryRow : TableRow;

    return (
      <EntryRow
        key={key}
        gridTemplateColumns={gridTemplateColumns}
        height={themeCssVariables.spacing[8]}
        isClickable
        isExpanded={
          isDefined(selectedEntry) && isDeeplyEqual(entry, selectedEntry)
        }
        onClick={() => onEntryClick(entry)}
      >
        {columns.map((column) => (
          <Fragment key={column.id}>{column.renderCell(entry)}</Fragment>
        ))}
      </EntryRow>
    );
  };

  return (
    <ScrollWrapper componentInstanceId={LOG_CONSOLE_TABLE_SCROLL_WRAPPER_ID}>
      <StyledTable id={LOG_CONSOLE_TABLE_HTML_ID}>
        <StyledHeaderRow
          gridTemplateColumns={gridTemplateColumns}
          hoverBackgroundColor={themeCssVariables.background.primary}
        >
          {columns.map((column) => (
            <LogConsoleTableHeaderCell
              key={column.id}
              column={column}
              onWidthPreview={(width) =>
                handleColumnWidthPreview(column.id, width)
              }
              onWidthCommitted={(width) =>
                handleColumnWidthCommitted(column.id, width)
              }
              onWidthReset={() => handleColumnWidthReset(column.id)}
              onResizeEnd={() => clearColumnWidthPreview(column.id)}
            />
          ))}
        </StyledHeaderRow>
        {entries.map((entry, entryIndex) =>
          renderEntryRow(
            entry,
            liveEntryCount - entryIndex,
            entryIndex < liveEntryCount,
          ),
        )}
        {hasNextPage && (
          <StyledLoadMoreTrigger
            key={storedEntryCount}
            ref={loadMoreTriggerRef}
          />
        )}
        {(isInitialLoading || isLoadingNextPage) && (
          <>
            {Array.from({ length: SKELETON_ROW_COUNT }, (_, rowIndex) => (
              <TableRow
                key={`skel-${rowIndex}`}
                gridTemplateColumns={gridTemplateColumns}
              >
                {columns.map((column) => (
                  <TableCell key={column.id}>
                    <SkeletonLine width={80} height={16} />
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </>
        )}
      </StyledTable>
    </ScrollWrapper>
  );
};