Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

15.2 KB
Raw Blame
import type { EnvironmentThreadShell } from "@akeru/client-runtime/state/shell";
import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@akeru/contracts";
import { useAtomValue } from "@effect/atom-react";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useWindowDimensions, View } from "react-native";
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import { AsyncResult } from "effect/unstable/reactivity";
import {
  deriveFileInspectorPaneLayout,
  deriveLayout,
  deriveWorkspacePaneLayout,
  type WorkspaceAuxiliaryPaneRole,
} from "../../lib/layout";
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { mobilePreferencesAtom } from "../../state/preferences";
import {
  DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
  resolveMobileProjectGroupingSettings,
} from "../../state/project-grouping";
import {
  parseActiveThreadPath,
  useHardwareKeyboardCommand,
} from "../keyboard/hardwareKeyboardCommands";
import { AndroidHomeFabLayout } from "../home/AndroidHomeFab";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
import { AdaptiveWorkspaceContext } from "./workspace-pane-context";

export {
  useAdaptiveWorkspaceLayout,
  useAdaptiveWorkspacePaneRole,
  useRegisterWorkspaceInspector,
} from "./workspace-pane-context";

export function AdaptiveWorkspaceLayout(props: {
  readonly children: ReactNode;
  readonly pathname: string;
}) {
  const preferencesResult = useAtomValue(mobilePreferencesAtom);

  if (!AsyncResult.isSuccess(preferencesResult)) {
    return AsyncResult.isFailure(preferencesResult) ? (
      <AdaptiveWorkspaceLayoutContent
        {...props}
        projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
      />
    ) : null;
  }

  const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);

  return (
    <AdaptiveWorkspaceLayoutContent
      {...props}
      projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
    />
  );
}

function AdaptiveWorkspaceLayoutContent(
  props: {
    readonly children: ReactNode;
    readonly pathname: string;
  } & {
    readonly projectGroupingMode: SidebarProjectGroupingMode;
  },
) {
  const projectGroupingMode = props.projectGroupingMode;
  const { width, height } = useWindowDimensions();
  const pathname = props.pathname;
  const navigation = useNavigation();
  const activeRoleOwner = useRef<symbol | null>(null);
  const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true);
  const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true);

  const [supplementaryPanePreferredWidth, setSupplementaryPanePreferredWidth] = useState<
    number | null
  >(null);

  const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true);

  const [fileInspectorPreferredWidth, setFileInspectorPreferredWidth] = useState<number | null>(
    null,
  );

  const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");

  const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =
    useState<WorkspaceAuxiliaryPaneRole | null>(null);

  const baseLayout = useMemo(() => deriveLayout({ width, height }), [height, width]);
  const layout = baseLayout;
  // In split layouts the sidebar IS the thread list — it renders on every
  // route, including Home (which shows an empty-detail pane instead of the
  // compact list).
  const shouldRenderPrimarySidebar = layout.usesSplitView;

  const fileInspector = useMemo(
    () =>
      deriveFileInspectorPaneLayout({
        layout,
        viewportWidth: width,
        preferredWidth: fileInspectorPreferredWidth ?? undefined,
        reservedLeadingWidth:
          shouldRenderPrimarySidebar && primarySidebarPreferredVisible
            ? (layout.listPaneWidth ?? 0)
            : 0,
      }),
    [
      fileInspectorPreferredWidth,
      layout,
      primarySidebarPreferredVisible,
      shouldRenderPrimarySidebar,
      width,
    ],
  );

  const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =
    focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");

  const auxiliaryPanePreferredVisible =
    auxiliaryPaneRole === "inspector"
      ? fileInspectorPreferredVisible
      : supplementaryPanePreferredVisible;

  const auxiliaryPanePreferredWidth =
    auxiliaryPaneRole === "inspector"
      ? fileInspectorPreferredWidth
      : supplementaryPanePreferredWidth;

  const panes = useMemo(
    () =>
      deriveWorkspacePaneLayout({
        layout,
        viewportWidth: width,
        primarySidebarPreferredVisible,
        auxiliaryPanePreferredVisible,
        auxiliaryPaneRole,
        auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
      }),
    [
      auxiliaryPanePreferredVisible,
      auxiliaryPaneRole,
      auxiliaryPanePreferredWidth,
      layout,
      primarySidebarPreferredVisible,
      width,
    ],
  );

  const activeThread = parseActiveThreadPath(pathname);
  const environmentId = activeThread?.environmentId ?? null;
  const threadId = activeThread?.threadId ?? null;

  const selectedThreadKey = useMemo(() => {
    if (environmentId === null || threadId === null) {
      return null;
    }

    try {
      return scopedThreadKey(EnvironmentId.make(environmentId), ThreadId.make(threadId));
    } catch {
      return null;
    }
  }, [environmentId, threadId]);

  // Wrapped in an object: bare functions in useState would be treated as
  // lazy initializers/updaters. `active: false` keeps the outgoing route's
  // content mounted so the pane can animate closed (or be replaced
  // seamlessly by the next route's registration in the same commit).
  const [workspaceInspector, setWorkspaceInspector] = useState<{
    readonly render: () => ReactNode;
    readonly active: boolean;
  } | null>(null);

  const workspaceInspectorOwner = useRef<symbol | null>(null);

  const registerWorkspaceInspector = useCallback((render: () => ReactNode) => {
    const owner = Symbol("workspace-inspector");
    workspaceInspectorOwner.current = owner;
    setWorkspaceInspector({ render, active: true });

    return () => {
      // During a push/replace the outgoing screen deactivates AFTER the
      // incoming screen registered — only the current owner may deactivate.
      if (workspaceInspectorOwner.current !== owner) {
        return;
      }

      setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false }));
    };
  }, []);

  // Once the close animation settles, drop the stale content entirely.
  const handleWorkspaceInspectorClosed = useCallback(() => {
    setWorkspaceInspector((current) => (current !== null && !current.active ? null : current));
  }, []);

  const activateAuxiliaryPaneRole = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
    const owner = Symbol(role);
    activeRoleOwner.current = owner;
    setFocusedAuxiliaryPaneRole(role);

    return () => {
      if (activeRoleOwner.current !== owner) {
        return;
      }

      activeRoleOwner.current = null;
      setFocusedAuxiliaryPaneRole(null);
    };
  }, []);

  const togglePrimarySidebar = useCallback(() => {
    if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) {
      setFileInspectorPreferredVisible(false);
      setPrimarySidebarPreferredVisible(true);

      return;
    }

    setPrimarySidebarPreferredVisible((current) => !current);
  }, [panes.primarySidebarSuppressedByAuxiliary, panes.primarySidebarVisible]);

  const revealPrimarySidebar = useCallback(() => {
    if (panes.primarySidebarSuppressedByAuxiliary) {
      setFileInspectorPreferredVisible(false);
    }

    setPrimarySidebarPreferredVisible(true);
  }, [panes.primarySidebarSuppressedByAuxiliary]);

  const handleToggleSidebarCommand = useCallback(() => {
    togglePrimarySidebar();

    return true;
  }, [togglePrimarySidebar]);

  useHardwareKeyboardCommand("toggleSidebar", handleToggleSidebarCommand);

  const showAuxiliaryPane = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
    if (role === "inspector") {
      setFocusedAuxiliaryPaneRole("inspector");
      setFileInspectorPreferredVisible(true);

      return;
    }

    setFocusedAuxiliaryPaneRole("supplementary");
    setSupplementaryPanePreferredVisible(true);
  }, []);

  const toggleAuxiliaryPane = useCallback(() => {
    if (auxiliaryPaneRole === "inspector") {
      setFileInspectorPreferredVisible((current) => !current);

      return;
    }

    setSupplementaryPanePreferredVisible((current) => !current);
  }, [auxiliaryPaneRole]);

  const setAuxiliaryPaneWidth = useCallback(
    (nextWidth: number) => {
      if (auxiliaryPaneRole === "inspector") {
        setFileInspectorPreferredWidth(nextWidth);

        return;
      }

      setSupplementaryPanePreferredWidth(nextWidth);
    },
    [auxiliaryPaneRole],
  );

  const contextValue = useMemo(
    () => ({
      layout,
      panes,
      fileInspector,
      primarySidebarSearchQuery,
      activateAuxiliaryPaneRole,
      registerWorkspaceInspector,
      setPrimarySidebarSearchQuery,
      showAuxiliaryPane,
      toggleAuxiliaryPane,
      togglePrimarySidebar,
      setAuxiliaryPaneWidth,
    }),
    [
      activateAuxiliaryPaneRole,
      fileInspector,
      layout,
      panes,
      primarySidebarSearchQuery,
      registerWorkspaceInspector,
      showAuxiliaryPane,
      setPrimarySidebarSearchQuery,
      setAuxiliaryPaneWidth,
      toggleAuxiliaryPane,
      togglePrimarySidebar,
    ],
  );

  const handleOpenSettings = useCallback(() => {
    navigation.navigate("SettingsSheet", {
      screen: "SettingsContent",
      params: {
        screen: "Settings",
        params: {
          environmentId: environmentId === null ? null : EnvironmentId.make(environmentId),
        },
      },
    });
  }, [environmentId, navigation]);

  const handleStartNewTask = useCallback(() => {
    navigation.navigate("NewTaskSheet", { screen: "NewTask" });
  }, [navigation]);

  // Minted here (root stack navigation) so the sidebar pane stays free of
  // navigation hooks — on iOS it renders inside an independent nav tree.
  const handleOpenEnvironmentSettings = useCallback(() => {
    navigation.navigate("SettingsSheet", {
      screen: "SettingsContent",
      params: { screen: "SettingsEnvironments" },
    });
  }, [navigation]);

  const renderedSidebarWidth = useSharedValue(
    panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0,
  );

  useEffect(() => {
    const targetWidth = panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) : 0;
    renderedSidebarWidth.value = withTiming(targetWidth, WORKSPACE_PANE_TIMING);
  }, [layout.listPaneWidth, panes.primarySidebarVisible, renderedSidebarWidth]);

  const sidebarAnimatedStyle = useAnimatedStyle(() => ({
    opacity: Math.min(1, renderedSidebarWidth.value / 80),
    width: renderedSidebarWidth.value,
  }));

  // Freeze the content pane at its SETTLED width while the side panes
  // animate. The navigator (native header + markdown feed) lays out ONCE per
  // pane toggle instead of re-measuring on every animation frame — the
  // animating columns merely clip/reveal it over a matching background.
  // Continuously re-wrapping the chat feed was the main source of dropped
  // frames during sidebar/inspector transitions.
  const inspectorColumnTargetWidth =
    workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible
      ? (panes.auxiliaryPaneWidth ?? 0)
      : 0;

  const contentSettledWidth = layout.usesSplitView
    ? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth)
    : null;

  const handleSelectThread = useCallback(
    (thread: EnvironmentThreadShell) => {
      const params = {
        environmentId: String(thread.environmentId),
        threadId: String(thread.id),
      };

      const navigationAction = resolveThreadSelectionNavigationAction({
        usesSplitView: layout.usesSplitView,
        pathname,
      });

      if (navigationAction === "set-params") {
        const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);

        if (nextThreadKey === selectedThreadKey) {
          return;
        }

        setFileInspectorPreferredVisible(false);
        navigation.navigate("Thread", params);

        return;
      }

      if (navigationAction === "replace") {
        setFileInspectorPreferredVisible(false);
        navigation.dispatch(StackActions.replace("Thread", params));

        return;
      }

      navigation.navigate("Thread", params);
    },
    [layout.usesSplitView, pathname, navigation, selectedThreadKey],
  );

  return (
    <HomeListOptionsProvider projectGroupingMode={projectGroupingMode}>
      <AdaptiveWorkspaceContext.Provider value={contextValue}>
        <View testID="adaptive-workspace-layout" className="flex-1 flex-row">
          {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? (
            <Animated.View
              className="self-stretch overflow-hidden"
              accessibilityElementsHidden={!panes.primarySidebarVisible}
              collapsable={false}
              importantForAccessibility={
                panes.primarySidebarVisible ? "auto" : "no-hide-descendants"
              }
              pointerEvents={panes.primarySidebarVisible ? "auto" : "none"}
              style={sidebarAnimatedStyle}
            >
              <View className="flex-1" style={{ width: layout.listPaneWidth }}>
                <AndroidHomeFabLayout onStartNewTask={handleStartNewTask}>
                  <ThreadNavigationSidebar
                    width={layout.listPaneWidth}
                    visible={panes.primarySidebarVisible}
                    onRequestVisibility={revealPrimarySidebar}
                    selectedThreadKey={selectedThreadKey}
                    onOpenSettings={handleOpenSettings}
                    onOpenEnvironmentSettings={handleOpenEnvironmentSettings}
                    onSelectThread={handleSelectThread}
                    onSearchQueryChange={setPrimarySidebarSearchQuery}
                    searchQuery={primarySidebarSearchQuery}
                  />
                </AndroidHomeFabLayout>
              </View>
            </Animated.View>
          ) : null}
          <View className="flex-1 overflow-hidden bg-screen" collapsable={false}>
            <View
              collapsable={false}
              style={
                contentSettledWidth !== null ? { flex: 1, width: contentSettledWidth } : { flex: 1 }
              }
            >
              {props.children}
            </View>
          </View>
          <WorkspaceInspectorPane
            active={workspaceInspector?.active ?? false}
            panes={panes}
            renderInspector={workspaceInspector?.render}
            setAuxiliaryPaneWidth={setAuxiliaryPaneWidth}
            onClosed={handleWorkspaceInspectorClosed}
          />
        </View>
      </AdaptiveWorkspaceContext.Provider>
    </HomeListOptionsProvider>
  );
}