Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

3.9 KB
Raw Blame
import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';
import { createSearchState } from '@app/features/soup/search/create-search-state';
import { type ChannelEntity, isChannelEntity } from '@entity';
import { type Accessor, createMemo } from 'solid-js';
import { match } from 'ts-pattern';
import {
  type ChannelsDataSource,
  type ChannelsSourceScope,
  filterChannelsForScope,
} from '../queries';

export function createChannelSearchSource(options: {
  text: Accessor<string>;
  enabled?: Accessor<boolean>;
  scope: Accessor<ChannelsSourceScope>;
  source: Accessor<ChannelsDataSource>;
  additionalLocalChannels?: Accessor<readonly ChannelEntity[]>;
}): ChannelsDataSource {
  const enabled = () => options.enabled?.() ?? true;
  const searching = () => options.text().trim().length > 0;
  // Loaded rows carry the unread and preview metadata the rail renders, so a
  // loaded row replaces the additional entity for the same channel.
  const localChannels = createMemo(() => {
    const byId = new Map<string, ChannelEntity>();
    for (const channel of options.additionalLocalChannels?.() ?? []) {
      byId.set(channel.id, channel);
    }
    for (const channel of options.source().items()) {
      byId.set(channel.id, channel);
    }
    return byId;
  });
  const search = createSearchState({
    surface: () => 'channels',
    enabled,
    text: options.text,
    localPool: () => [...localChannels().values()].map((data) => ({ data })),
    buildRequest: ({ query, matchType }) => ({
      params: { page_size: 100 },
      body: {
        query,
        match_type: matchType,
        search_on: 'name',
        filters: {
          ...QUERY_FILTERS_BASE,
          channel_filters: {
            is_participant: true,
            channel_types: match(options.scope())
              .with('direct_messages', () => ['direct_message'])
              .with('team_channels', () => ['team'])
              .with('channels', () => ['public', 'private'])
              .with('recents', 'search', 'threads', () => undefined)
              .exhaustive(() => undefined),
          },
        },
      },
    }),
  });
  const items = createMemo(() => {
    if (!enabled()) return [];
    if (!searching()) return [...options.source().items()];

    // Search records lack loaded conversation metadata, including message previews.
    const loadedById = localChannels();
    const matches = search
      .data()
      .filter(isChannelEntity)
      .map((channel) => ({
        ...channel,
        ...loadedById.get(channel.id),
      }));
    // Recent and Threads search include both channels and DMs, even without
    // message metadata.
    const scope = options.scope();
    return filterChannelsForScope(
      scope === 'recents' || scope === 'threads' ? 'search' : scope,
      matches
    );
  });
  const isFetching = () =>
    enabled() &&
    (searching() ? search.isFetching() : options.source().isFetching());
  const hasMore = () =>
    enabled() &&
    (searching() ? search.hasNextPage() : options.source().hasMore());
  const isLoadingMore = () =>
    enabled() &&
    (searching()
      ? search.isFetchingNextPage()
      : options.source().isLoadingMore());
  const error = () => {
    if (!enabled()) return;
    if (!searching()) return options.source().error();
    return search.usesServiceSearch() ? search.error() : undefined;
  };

  return {
    items,
    isLoading: () =>
      enabled() &&
      items().length === 0 &&
      (searching() ? search.isLoading() : options.source().isLoading()),
    isFetching,
    error,
    hasMore,
    isLoadingMore,
    loadMore: async () => {
      if (!hasMore() || isFetching()) return;
      if (searching()) await search.fetchNextPage();
      else await options.source().loadMore();
    },
    refresh: async () => {
      if (!enabled()) return;
      await Promise.all([
        options.source().refresh(),
        ...(searching() ? [search.refresh()] : []),
      ]);
    },
  };
}