Skip to content

The open alternative to Salesforce, designed for AI.

3.8 KB
Raw Blame
import { atom, type WritableAtom } from 'jotai';
import { atomWithStorage, createJSONStorage } from 'jotai/utils';
import { isDefined } from 'twenty-shared/utils';

import { type State } from '@/ui/utilities/state/jotai/types/State';
import { createJotaiCookieStorage } from '@/ui/utilities/state/jotai/utils/createJotaiCookieStorage';
import { registerRoutedFlowStateScopeRelease } from '@/ui/utilities/state/jotai/utils/routedFlowStateScopeRegistry';

type CookieStorageConfig<ValueType> = {
  cookieKey: string;
  attributes?: {
    expires?: number | Date;
    path?: string;
    domain?: string;
    secure?: boolean;
  };
  validateInitFn?: (payload: NonNullable<ValueType>) => boolean;
};

type StateAtom<ValueType> = WritableAtom<
  ValueType,
  [ValueType | ((prev: ValueType) => ValueType)],
  void
>;

type LocalStorageOptions = { getOnInit?: boolean };

const createValidatedLocalStorage = <ValueType>(
  validateInitFn: (payload: NonNullable<ValueType>) => boolean,
) => {
  const storage = createJSONStorage<ValueType>(() => localStorage);

  return {
    ...storage,
    getItem: (key: string, initialValue: ValueType): ValueType => {
      const value = storage.getItem(key, initialValue) as ValueType;

      if (
        isDefined(value) &&
        !validateInitFn(value as NonNullable<ValueType>)
      ) {
        return initialValue;
      }

      return value;
    },
  };
};

export const createAtomState = <ValueType>({
  key,
  defaultValue,
  useLocalStorage = false,
  useSessionStorage = false,
  localStorageOptions,
  validateInitFn,
  useCookieStorage,
  scope,
}: {
  key: string;
  defaultValue: ValueType;
  useLocalStorage?: boolean;
  useSessionStorage?: boolean;
  localStorageOptions?: LocalStorageOptions;
  validateInitFn?: (payload: NonNullable<ValueType>) => boolean;
  useCookieStorage?: CookieStorageConfig<ValueType>;
  scope?: 'routed-flow';
}): State<ValueType> => {
  const buildBaseAtom = (atomKey: string): StateAtom<ValueType> => {
    let baseAtom: StateAtom<ValueType>;

    if (isDefined(useCookieStorage)) {
      const cookieKey = atomKey === key ? useCookieStorage.cookieKey : atomKey;
      const storage = createJotaiCookieStorage<ValueType>({
        cookieKey,
        attributes: useCookieStorage.attributes,
        validateInitFn: useCookieStorage.validateInitFn,
      });
      baseAtom = atomWithStorage<ValueType>(cookieKey, defaultValue, storage, {
        getOnInit: true,
      }) as StateAtom<ValueType>;
    } else if (useSessionStorage) {
      const storage = createJSONStorage<ValueType>(() => sessionStorage);
      baseAtom = atomWithStorage<ValueType>(atomKey, defaultValue, storage, {
        getOnInit: true,
      }) as StateAtom<ValueType>;
    } else if (useLocalStorage) {
      const storage = isDefined(validateInitFn)
        ? createValidatedLocalStorage<ValueType>(validateInitFn)
        : undefined;
      baseAtom = atomWithStorage<ValueType>(
        atomKey,
        defaultValue,
        storage,
        localStorageOptions ?? undefined,
      ) as StateAtom<ValueType>;
    } else {
      baseAtom = atom(defaultValue);
    }

    baseAtom.debugLabel = atomKey;

    return baseAtom;
  };

  const baseAtom = buildBaseAtom(key);
  const scopedAtomCache = new Map<string, StateAtom<ValueType>>();

  if (scope === 'routed-flow') {
    registerRoutedFlowStateScopeRelease((scopeId) => {
      scopedAtomCache.delete(scopeId);
    });
  }

  return {
    type: 'State',
    key,
    scope,
    atom: baseAtom,
    getAtom: (scopeId: string | null) => {
      if (scope !== 'routed-flow' || scopeId === null) {
        return baseAtom;
      }

      const existingAtom = scopedAtomCache.get(scopeId);

      if (isDefined(existingAtom)) {
        return existingAtom;
      }

      const scopedAtom = buildBaseAtom(`${key}__${scopeId}`);
      scopedAtomCache.set(scopeId, scopedAtom);

      return scopedAtom;
    },
  };
};