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.

8.5 KB
Raw Blame
import type {
  MakePersistedStateOptions,
  PersistenceStorage,
} from '@app/lib/persistence';
import {
  createEntryPersistenceStorage,
  type EntryPersistenceHandle,
} from '@components/app/split-layout/entry-persistence';
import { createUserScopedStorage } from '@core/util/userScopedStorage';
import type { Accessor } from 'solid-js';
import { z } from 'zod';
import {
  CHANNELS_DEFAULT_SORT_BY,
  clampChannelSectionHeight,
} from './constants';
import type { ChannelsViewState } from './types';

const CHANNELS_ENTRY_STATE_KEY = 'channels.view';
const channelsLocalStateStorage = createUserScopedStorage(
  'macro:channels:view-state:v1'
);
const channelsPreferencesStorage = createUserScopedStorage(
  'macro:channels:preferences:v1'
);

const channelsExpandedGroupsSchema = z.preprocess(
  (value) => {
    if (typeof value !== 'object' || value === null || Array.isArray(value)) {
      return value;
    }

    const groups = value as Record<string, unknown>;
    return {
      ...groups,
      direct_messages: groups.direct_messages ?? groups['direct-messages'],
    };
  },
  z.object({
    favorites: z.boolean().default(true),
    team_channels: z.boolean().default(true),
    channels: z.boolean().default(true),
    direct_messages: z.boolean().default(true),
  })
);

const channelsEntryStateSchemaWithDefaults = z.object({
  version: z.literal(1).default(1),
  tab: z.enum(['browse', 'recents', 'threads']).default('browse'),
  expandedGroups: channelsExpandedGroupsSchema.default({
    favorites: true,
    team_channels: true,
    channels: true,
    direct_messages: true,
  }),
  collapsedLabels: z.array(z.string()).default([]),
  threadsChannelId: z.string().optional(),
});

type ChannelsEntryState = z.infer<typeof channelsEntryStateSchemaWithDefaults>;

const DEFAULT_CHANNELS_ENTRY_STATE = {
  version: 1,
  tab: 'browse',
  expandedGroups: {
    favorites: true,
    team_channels: true,
    channels: true,
    direct_messages: true,
  },
  collapsedLabels: [],
  threadsChannelId: undefined,
} satisfies ChannelsEntryState;

const channelsPreferencesSchema = z.object({
  version: z.literal(1).default(1),
  sortBy: z
    .object({
      team_channels: z
        .enum(['viewed_at', 'updated_at', 'created_at'])
        .default(CHANNELS_DEFAULT_SORT_BY.team_channels),
      channels: z
        .enum(['viewed_at', 'updated_at', 'created_at'])
        .default(CHANNELS_DEFAULT_SORT_BY.channels),
      direct_messages: z
        .enum(['viewed_at', 'updated_at', 'created_at'])
        .default(CHANNELS_DEFAULT_SORT_BY.direct_messages),
      threads: z
        .enum(['viewed_at', 'updated_at', 'created_at'])
        .default(CHANNELS_DEFAULT_SORT_BY.threads),
    })
    .default(CHANNELS_DEFAULT_SORT_BY),
  sectionPreferences: z
    .record(
      z.string(),
      z
        .object({
          sort: z
            .enum(['viewed_at', 'updated_at', 'created_at', 'name', 'manual'])
            .optional(),
          unreadOnly: z.boolean().optional(),
          height: z
            .number()
            .finite()
            .transform(clampChannelSectionHeight)
            .optional(),
        })
        .optional()
    )
    .default({}),
  sectionOrder: z
    .array(
      z.union([
        z.enum(['favorites', 'direct_messages', 'team_channels', 'channels']),
        z.custom<`label:${string}`>(
          (value) => typeof value === 'string' && value.startsWith('label:')
        ),
      ])
    )
    .default([]),
});

type ChannelsPreferences = z.infer<typeof channelsPreferencesSchema>;

const DEFAULT_CHANNELS_PREFERENCES = {
  version: 1,
  sortBy: CHANNELS_DEFAULT_SORT_BY,
  sectionPreferences: {},
  sectionOrder: [],
} satisfies ChannelsPreferences;

function selectEntryState(state: ChannelsViewState): ChannelsEntryState {
  return {
    version: 1,
    tab: state.tab,
    expandedGroups: state.expandedGroups,
    collapsedLabels: state.collapsedLabels,
    threadsChannelId: state.threadsChannelId,
  };
}

function restoreChannelsEntryState(
  current: ChannelsViewState,
  stored: unknown
): ChannelsViewState {
  const result = channelsEntryStateSchemaWithDefaults.safeParse(stored);
  const restored = result.success ? result.data : DEFAULT_CHANNELS_ENTRY_STATE;

  return {
    ...current,
    tab: restored.tab,
    expandedGroups: restored.expandedGroups,
    collapsedLabels: restored.collapsedLabels,
    threadsChannelId: restored.threadsChannelId,
  };
}

function createChannelsEntryStorage(options: {
  handle: EntryPersistenceHandle;
  restore: boolean;
}): PersistenceStorage<ChannelsViewState> {
  return createEntryPersistenceStorage({
    handle: options.handle,
    key: CHANNELS_ENTRY_STATE_KEY,
    restore: (current, stored) => {
      if (!options.restore) return undefined;

      return restoreChannelsEntryState(current, stored);
    },
    select: selectEntryState,
  });
}

function createChannelsLocalStateStorage(options: {
  userId: Accessor<string | undefined>;
  restore: boolean;
}): PersistenceStorage<ChannelsViewState> {
  let previous: string | undefined;
  const serialize = (state: ChannelsViewState) =>
    JSON.stringify(selectEntryState(state));

  return {
    restore: (current) => {
      if (!options.restore) return undefined;

      const userId = options.userId();
      if (!userId) return undefined;

      const raw = channelsLocalStateStorage.read(userId);
      if (raw === null) return undefined;

      try {
        return restoreChannelsEntryState(current, JSON.parse(raw));
      } catch {
        return restoreChannelsEntryState(current, undefined);
      }
    },
    initialize: (current) => {
      previous = serialize(current);
    },
    write: (current) => {
      const userId = options.userId();
      if (!userId) return;

      const serialized = serialize(current);
      if (serialized === previous) return;

      previous = serialized;
      channelsLocalStateStorage.write(userId, serialized);
    },
  };
}

function createChannelsPreferencesStorage(options: {
  userId: Accessor<string | undefined>;
  restore: boolean;
  restoreSectionOrder: boolean;
}): PersistenceStorage<ChannelsViewState> {
  let previous: string | undefined;
  const serialize = (state: ChannelsViewState) =>
    JSON.stringify({
      version: 1,
      sortBy: state.sortBy,
      sectionPreferences: state.sectionPreferences,
      sectionOrder: state.sectionOrder,
    } satisfies ChannelsPreferences);

  return {
    restore: (current) => {
      if (!options.restore) return undefined;

      const userId = options.userId();
      if (!userId) return undefined;

      const raw = channelsPreferencesStorage.read(userId);
      if (raw === null) return undefined;

      try {
        const result = channelsPreferencesSchema.safeParse(JSON.parse(raw));
        const restored = result.success
          ? result.data
          : DEFAULT_CHANNELS_PREFERENCES;

        return {
          ...current,
          sortBy: restored.sortBy,
          sectionPreferences: restored.sectionPreferences,
          sectionOrder: options.restoreSectionOrder
            ? restored.sectionOrder
            : current.sectionOrder,
        };
      } catch {
        return {
          ...current,
          sortBy: DEFAULT_CHANNELS_PREFERENCES.sortBy,
          sectionPreferences: DEFAULT_CHANNELS_PREFERENCES.sectionPreferences,
          sectionOrder: options.restoreSectionOrder
            ? DEFAULT_CHANNELS_PREFERENCES.sectionOrder
            : current.sectionOrder,
        };
      }
    },
    initialize: (current) => {
      previous = serialize(current);
    },
    write: (current) => {
      const userId = options.userId();
      if (!userId) return;

      const serialized = serialize(current);
      if (serialized === previous) return;

      previous = serialized;
      channelsPreferencesStorage.write(userId, serialized);
    },
  };
}

export function createChannelsViewPersistence(options: {
  handle: EntryPersistenceHandle;
  userId: Accessor<string | undefined>;
  restoreEntryState?: boolean;
  restoreLocalState?: boolean;
  restorePreferences?: boolean;
  restoreSectionOrder?: boolean;
}): MakePersistedStateOptions<ChannelsViewState> {
  return {
    storages: [
      createChannelsPreferencesStorage({
        userId: options.userId,
        restore: options.restorePreferences ?? true,
        restoreSectionOrder: options.restoreSectionOrder ?? true,
      }),
      createChannelsLocalStateStorage({
        userId: options.userId,
        restore: options.restoreLocalState ?? true,
      }),
      createChannelsEntryStorage({
        handle: options.handle,
        restore: options.restoreEntryState ?? true,
      }),
    ],
  };
}