Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

1.7 KB
Raw Blame
import type { EqualityFn } from './selectorCore';

export interface ReadableExternalStore<Snapshot> {
  getSnapshot(): Snapshot;
  subscribe(listener: () => void): () => void;
}

interface ProjectedExternalStoreOptions<Source, Snapshot> {
  source: ReadableExternalStore<Source>;
  select: (source: Source) => Snapshot;
  isEqual?: EqualityFn<Snapshot>;
}

/** Share the source subscription lazily and preserve snapshot identity when the projection is equal. */
export const createProjectedExternalStore = <Source, Snapshot>({
  isEqual = Object.is,
  select,
  source,
}: ProjectedExternalStoreOptions<Source, Snapshot>): ReadableExternalStore<Snapshot> => {
  let sourceSnapshot = source.getSnapshot();
  let snapshot = select(sourceSnapshot);
  const listeners = new Set<() => void>();
  let unsubscribeSource: (() => void) | null = null;

  const refresh = (): boolean => {
    const nextSourceSnapshot = source.getSnapshot();
    if (Object.is(nextSourceSnapshot, sourceSnapshot)) {
      return false;
    }
    sourceSnapshot = nextSourceSnapshot;

    const nextSnapshot = select(nextSourceSnapshot);
    if (isEqual(snapshot, nextSnapshot)) {
      return false;
    }
    snapshot = nextSnapshot;
    return true;
  };

  const notifyIfChanged = (): void => {
    if (!refresh()) {
      return;
    }

    for (const listener of listeners) {
      listener();
    }
  };

  return {
    getSnapshot: () => {
      refresh();
      return snapshot;
    },
    subscribe: (listener) => {
      listeners.add(listener);
      unsubscribeSource ??= source.subscribe(notifyIfChanged);

      return () => {
        listeners.delete(listener);
        if (listeners.size === 0) {
          unsubscribeSource?.();
          unsubscribeSource = null;
        }
      };
    },
  };
};