Skip to content

The open alternative to Salesforce, designed for AI.

8.4 KB
Raw Blame
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
import { type Editor } from '@tiptap/core';
import {
  TIPTAP_NODE_TYPES,
  isDefined,
  resolveCanvasTheme,
} from 'twenty-shared/utils';
import { IconTrash } from 'twenty-ui/icon';
import { Button } from 'twenty-ui/primitives/input';
import { themeCssVariables } from 'twenty-ui/theme';

import { activeEmailEditorState } from '@/activities/emails/states/activeEmailEditorState';
import { ADVANCED_TEXT_EDITOR_BLOCK_CATALOG } from '@/advanced-text-editor/constants/AdvancedTextEditorBlockCatalog';
import { useLiveEditorState } from '@/advanced-text-editor/hooks/useLiveEditorState';
import { type AdvancedTextEditorBlockSetting } from '@/advanced-text-editor/types/AdvancedTextEditorBlockCatalog';
import { getBlockSelectionTarget } from '@/advanced-text-editor/utils/getBlockSelectionTarget';
import { getBlockStyle } from '@/advanced-text-editor/utils/getBlockStyle';
import { EmailBlockSettingsFieldInput } from '@/side-panel/pages/email-block-settings/components/EmailBlockSettingsFieldInput';
import {
  EmailBoxSidesInput,
  type CssBoxSides,
} from '@/side-panel/pages/email-block-settings/components/EmailBoxSidesInput';
import { StyledEmailSidePanelHint } from '@/side-panel/pages/email-block-settings/components/StyledEmailSidePanelHint';
import { getEffectiveSectionStyleValue } from '@/side-panel/pages/email-block-settings/utils/getEffectiveSectionStyleValue';
import { SidePanelPageTitleSyncEffect } from '@/side-panel/components/SidePanelPageTitleSyncEffect';
import { useSidePanelHistory } from '@/side-panel/hooks/useSidePanelHistory';
import { SidePanelFooter } from '@/ui/layout/side-panel/components/SidePanelFooter';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';

const StyledContainer = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
`;

const StyledContent = styled.div`
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: ${themeCssVariables.spacing[4]};
  overflow-y: auto;
  padding: ${themeCssVariables.spacing[4]} ${themeCssVariables.spacing[3]};
`;

const BORDER_STYLE_COMPANIONS: Record<string, string> = {
  borderWidth: 'borderStyle',
  borderTopWidth: 'borderTopStyle',
};

const BOX_FIELD_SIDE_PROPERTIES: Record<
  string,
  [string, string, string, string]
> = {
  padding: ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],
  margin: ['marginTop', 'marginRight', 'marginBottom', 'marginLeft'],
  borderRadius: [
    'borderTopLeftRadius',
    'borderTopRightRadius',
    'borderBottomRightRadius',
    'borderBottomLeftRadius',
  ],
};

const EmailBlockSettingsContent = ({ editor }: { editor: Editor }) => {
  const { i18n, t } = useLingui();
  const { goBackFromSidePanel } = useSidePanelHistory();
  const target = useLiveEditorState(editor, (currentEditor) =>
    getBlockSelectionTarget(currentEditor),
  );

  if (!isDefined(target)) {
    return (
      <StyledEmailSidePanelHint>{t`Select a block to edit its style.`}</StyledEmailSidePanelHint>
    );
  }

  const blockDefinition = ADVANCED_TEXT_EDITOR_BLOCK_CATALOG[target.nodeType];
  const fields = blockDefinition.settingsFields;
  const styles = getBlockStyle(target.attrs.style);
  const canvasTheme = resolveCanvasTheme(editor.state.doc.attrs.canvasTheme);

  const inheritsCanvasTypography = (property: string) => {
    switch (target.nodeType) {
      case TIPTAP_NODE_TYPES.SECTION:
      case TIPTAP_NODE_TYPES.PARAGRAPH:
      case TIPTAP_NODE_TYPES.BLOCKQUOTE:
        return true;
      case TIPTAP_NODE_TYPES.HEADING:
        return property !== 'fontSize' && property !== 'lineHeight';
      default:
        return false;
    }
  };

  const displayedStyleValue = (property: string) =>
    styles[property] ??
    (inheritsCanvasTypography(property)
      ? getEffectiveSectionStyleValue(property, canvasTheme)
      : '');

  const updateTargetAttributes = (attrs: Record<string, unknown>) => {
    editor
      .chain()
      .command(({ tr }) => {
        const node = tr.doc.nodeAt(target.pos);
        if (!isDefined(node)) {
          return false;
        }

        tr.setNodeMarkup(target.pos, undefined, { ...node.attrs, ...attrs });
        return true;
      })
      .run();
  };

  const handleRemoveBlock = () => {
    editor
      .chain()
      .focus()
      .command(({ tr }) => {
        const node = tr.doc.nodeAt(target.pos);
        if (!isDefined(node)) {
          return false;
        }

        tr.delete(target.pos, target.pos + node.nodeSize);
        return true;
      })
      .run();
    goBackFromSidePanel();
  };

  const handleFieldChange = (
    field: AdvancedTextEditorBlockSetting,
    value: string,
  ) => {
    if (field.kind === 'attribute') {
      if (field.property === 'width') {
        const trimmed = value.trim();
        if (trimmed === '' || trimmed === 'auto') {
          updateTargetAttributes({ width: null });
        } else if (Number.isFinite(Number(trimmed)) && Number(trimmed) >= 0) {
          updateTargetAttributes({ width: Number(trimmed) });
        }
        return;
      }

      updateTargetAttributes({ [field.property]: value });
      return;
    }

    const nextStyles = { ...styles };
    if (value.trim() === '') {
      delete nextStyles[field.property];
    } else {
      nextStyles[field.property] = value;
    }

    const borderStyleProperty = BORDER_STYLE_COMPANIONS[field.property];
    if (isDefined(borderStyleProperty)) {
      if (value.trim() === '' || value.trim() === '0px') {
        delete nextStyles[borderStyleProperty];
      } else {
        nextStyles[borderStyleProperty] ??= 'solid';
      }
    }

    updateTargetAttributes({ style: nextStyles });
  };

  const handleBoxFieldChange = (
    sideProperties: [string, string, string, string],
    sides: CssBoxSides,
  ) => {
    const nextStyles = { ...styles };
    const sideValues = [sides.top, sides.right, sides.bottom, sides.left];

    sideProperties.forEach((property, index) => {
      if (sideValues[index].trim() === '') {
        delete nextStyles[property];
      } else {
        nextStyles[property] = sideValues[index];
      }
    });

    updateTargetAttributes({ style: nextStyles });
  };

  const blockLabel = i18n._(blockDefinition.label);

  return (
    <StyledContainer>
      <SidePanelPageTitleSyncEffect pageTitle={t`${blockLabel} style`} />
      <StyledContent>
        {fields.map((field) => {
          const key = `${target.nodeType}-${target.pos}-${field.property}`;
          const sideProperties = BOX_FIELD_SIDE_PROPERTIES[field.property];

          if (
            field.kind === 'style' &&
            field.input === 'box' &&
            isDefined(sideProperties)
          ) {
            return (
              <EmailBoxSidesInput
                key={key}
                label={i18n._(field.label)}
                sides={{
                  top: displayedStyleValue(sideProperties[0]),
                  right: displayedStyleValue(sideProperties[1]),
                  bottom: displayedStyleValue(sideProperties[2]),
                  left: displayedStyleValue(sideProperties[3]),
                }}
                onChange={(sides) =>
                  handleBoxFieldChange(sideProperties, sides)
                }
                placeholder={field.placeholder}
              />
            );
          }

          return (
            <EmailBlockSettingsFieldInput
              key={key}
              field={field}
              value={
                field.kind === 'attribute'
                  ? String(target.attrs[field.property] ?? '')
                  : displayedStyleValue(field.property)
              }
              onChange={(value) => handleFieldChange(field, value)}
            />
          );
        })}
      </StyledContent>
      <SidePanelFooter
        actions={[
          <Button
            key="delete"
            size="sm"
            onClick={handleRemoveBlock}
            startIcon={<IconTrash />}
            color="danger"
          >{t`Delete`}</Button>,
        ]}
      />
    </StyledContainer>
  );
};

export const SidePanelEmailBlockSettingsPage = () => {
  const { t } = useLingui();
  const activeEmailEditor = useAtomStateValue(activeEmailEditorState);

  if (!isDefined(activeEmailEditor) || activeEmailEditor.isDestroyed) {
    return (
      <StyledEmailSidePanelHint>{t`Open an email editor to edit block settings.`}</StyledEmailSidePanelHint>
    );
  }

  return <EmailBlockSettingsContent editor={activeEmailEditor} />;
};