Skip to content

The open alternative to Salesforce, designed for AI.

2.6 KB
Raw Blame
import { PageLayoutType } from 'twenty-shared/types';
import { z } from 'zod';

import { FRONT_COMPONENT_WRAPPER_NAME } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-wrapper-name.constant';
import { FrontComponentBuildException } from 'src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception';
import { type FrontComponentBuildInput } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type';

const frontComponentEntryOptionsSchema = z.object({
  pageLayoutType: z.enum([
    PageLayoutType.DASHBOARD,
    PageLayoutType.RECORD_PAGE,
  ]),
});

export const buildFrontComponentEntrySource = ({
  componentId,
  name,
  source,
  pageLayoutType,
}: FrontComponentBuildInput): string => {
  const parsedOptions = frontComponentEntryOptionsSchema.safeParse({
    pageLayoutType,
  });

  if (!parsedOptions.success) {
    throw new FrontComponentBuildException({
      message: parsedOptions.error.message,
      code: 'INVALID_SETTINGS',
    });
  }

  return `import { useSyncExternalStore as useTwentySyncExternalStore } from 'react';
import { defineFrontComponent } from 'twenty-sdk/define';
import {
  THEME_DARK as TWENTY_THEME_DARK,
  THEME_LIGHT as TWENTY_THEME_LIGHT,
  ThemeProvider as TwentyThemeProvider,
} from 'twenty-ui/theme';
import { PageLayoutType as TwentyPageLayoutType } from 'twenty-shared/types';
import 'twenty-ui/style.css';
import 'twenty-ui/theme-light.css';
${source}
const TWENTY_DARK_COLOR_SCHEME_QUERY = '(prefers-color-scheme: dark)';
function subscribeToTwentyColorScheme(onColorSchemeChange: () => void) {
  const mediaQueryList = window.matchMedia(TWENTY_DARK_COLOR_SCHEME_QUERY);
  mediaQueryList.addEventListener('change', onColorSchemeChange);
  return () => mediaQueryList.removeEventListener('change', onColorSchemeChange);
}
function getTwentyColorScheme(): 'light' | 'dark' {
  return window.matchMedia(TWENTY_DARK_COLOR_SCHEME_QUERY).matches ? 'dark' : 'light';
}
function ${FRONT_COMPONENT_WRAPPER_NAME}() {
  const colorScheme = useTwentySyncExternalStore(subscribeToTwentyColorScheme, getTwentyColorScheme);
  return (
    <TwentyThemeProvider colorScheme={colorScheme} theme={colorScheme === 'dark' ? TWENTY_THEME_DARK : TWENTY_THEME_LIGHT}>
      <Component />
    </TwentyThemeProvider>
  );
}
export default defineFrontComponent({
  universalIdentifier: ${JSON.stringify(componentId)},
  name: ${JSON.stringify(name)},
  component: ${FRONT_COMPONENT_WRAPPER_NAME},
  widgetAvailability: { pageLayoutType: TwentyPageLayoutType.${parsedOptions.data.pageLayoutType} },
});
`;
};