Skip to content

The open alternative to Salesforce, designed for AI.

2.0 KB
Raw Blame
import { styled } from '@linaria/react';
import { useRef, useState } from 'react';

import { JsonDisplay } from '@/ui/field/display/components/JsonDisplay/JsonDisplay';
import { ExpandedFieldDisplay } from '@/ui/layout/expandable-list/components/ExpandedFieldDisplay';
import { isDefined } from 'twenty-shared/utils';
import { JsonTree } from 'twenty-ui/components/data-display';
import { themeCssVariables } from 'twenty-ui/theme';
import { type JsonValue } from 'type-fest';
import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
import { useLingui } from '@lingui/react/macro';

type EventLogJsonCellProps = {
  value: Record<string, unknown> | null | undefined;
};

const StyledJsonContainer = styled.div`
  cursor: pointer;
`;

const StyledEmptyCell = styled.span`
  color: ${themeCssVariables.font.color.tertiary};
`;

export const EventLogJsonCell = ({ value }: EventLogJsonCellProps) => {
  const { t } = useLingui();
  const { copyToClipboard } = useCopyToClipboard();
  const [isExpanded, setIsExpanded] = useState(false);
  const anchorRef = useRef<HTMLDivElement>(null);

  if (!isDefined(value) || Object.keys(value).length === 0) {
    return <StyledEmptyCell>-</StyledEmptyCell>;
  }

  const handleClick = () => {
    setIsExpanded(true);
  };

  const handleClickOutside = () => {
    setIsExpanded(false);
  };

  return (
    <>
      <StyledJsonContainer ref={anchorRef} onClick={handleClick}>
        <JsonDisplay text={JSON.stringify(value)} />
      </StyledJsonContainer>
      {isExpanded && (
        <ExpandedFieldDisplay
          anchorElement={anchorRef.current ?? undefined}
          onClickOutside={handleClickOutside}
        >
          <JsonTree
            value={value as JsonValue}
            emptyArrayLabel={t`Empty Array`}
            emptyObjectLabel={t`Empty Object`}
            emptyStringLabel={t`[empty string]`}
            arrowButtonCollapsedLabel={t`Expand`}
            arrowButtonExpandedLabel={t`Collapse`}
            onNodeValueClick={copyToClipboard}
          />
        </ExpandedFieldDisplay>
      )}
    </>
  );
};