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.

6.9 KB
Raw Blame
import { fireAndForget } from '@core/util/fireAndForget';
import { untrack } from 'solid-js';
import type {
  ExternalChange,
  HistoryAdapter,
  InterceptHandler,
} from '../history/types';
import { type ChangedPane, changedPanes } from '../panes/diff';
import {
  decodePanes,
  parseLocation,
  sameExternalLocation,
} from '../routes/codec';
import type { SplitRoutesManifest } from '../routes/manifest';
import { resolveTarget } from '../routes/targets';
import type {
  Entry,
  ExternalLocation,
  SplitLocation,
  SplitNavigationTarget,
  WriteMode,
} from '../routes/types';
import { type MaybePromise, UNCANCELLABLE } from '../utils';
import { createEntry, sameVisit } from './entries';
import {
  checksFor,
  type LeaveGuards,
  PANE_LEVEL,
  runChecks,
} from './leave-guards';
import type { Runner } from './runner';
import {
  CANCELLED_RESULT,
  type Navigation,
  type NavigationCause,
  type NavigationResult,
  type PaneTarget,
  type RouterPanes,
  type SplitNavigateOptions,
} from './types';
import type { Url } from './url';

type UrlNavigationOptions = {
  cause: NavigationCause;
  /** How applying it writes the URL back. */
  mode: WriteMode;
  revert?: () => MaybePromise<void>;
};

// The URL owns the location and history state owns route state; the stored
// entry keeps its in-memory props and metadata.
const adopt = (stored: Entry, incoming: Entry): Entry => ({
  ...stored,
  location: incoming.location,
  state: incoming.state,
});

function toTarget(change: ChangedPane<Entry>): PaneTarget {
  if (change.kind === 'change') {
    return { pane: change.pane, from: change.from, to: change.to };
  }

  return { pane: change.pane, to: change.entry };
}

/** The panes following the URL: the first load, Back/Forward, and links from outside. */
export function createUrlNavigation(options: {
  routes: SplitRoutesManifest;
  history: HistoryAdapter;
  panes: RouterPanes;
  url: Url;
  runner: Runner;
  guards: LeaveGuards;
  markReady(): void;
}) {
  const { routes, history, panes, url, runner, guards } = options;

  /** Makes every pane show `location`; a URL nothing handles is written back as the default route. */
  const navigationTo = (
    location: ExternalLocation,
    { cause, mode, revert }: UrlNavigationOptions
  ): Navigation => {
    const decoded = decodePanes(routes, location);
    const diff = panes.diff(decoded.panes, { same: sameVisit, adopt });

    const apply = (entries: readonly Entry[]): NavigationResult => {
      panes.applyDiff(diff, entries, { shape: decoded.shape });
      url.write(mode, { landed: location });
      options.markReady();

      const [first] = diff.panes;

      return { status: 'committed', pane: first!.pane };
    };

    return {
      cause,
      externalSearch: location.search,
      targets: changedPanes(diff).map(toTarget),
      removed: diff.removed,
      revert,
      apply,
    };
  };

  /** A navigation from the base to one location, which becomes the only pane. */
  const navigateToLocation = (
    location: SplitLocation,
    navigateOptions: SplitNavigateOptions
  ): MaybePromise<NavigationResult> => {
    const entry = createEntry(routes, location, undefined, navigateOptions);
    const diff = panes.diff([{ entry }], { same: sameVisit, adopt });

    const navigation: Navigation = {
      cause: 'navigate',
      targets: changedPanes(diff).map(toTarget),
      removed: diff.removed,
      apply: (entries) => {
        panes.applyDiff(diff, entries);
        url.write(navigateOptions.replace ? 'replace' : 'push');

        const [first] = diff.panes;

        return { status: 'committed', pane: first!.pane };
      },
    };

    return runner.startUrl(navigation, false);
  };

  /**
   * A navigation from the base, as any router's: a path's panes replace the
   * open ones, and a route or location target becomes the only pane. Panes
   * already showing their entry stay mounted.
   */
  const navigate = (
    to: SplitNavigationTarget,
    navigateOptions: SplitNavigateOptions = {}
  ): MaybePromise<NavigationResult> => {
    if (typeof to === 'string') {
      const mode = navigateOptions.replace ? 'replace' : 'push';
      const navigation = navigationTo(parseLocation(to), {
        cause: 'navigate',
        mode,
      });

      return runner.startUrl(navigation, false);
    }

    const location = resolveTarget(routes, undefined, to, navigateOptions);
    if (!location) return CANCELLED_RESULT;

    return navigateToLocation(location, navigateOptions);
  };

  /** The first load; pane actions wait for it. */
  const load = (location: ExternalLocation) => {
    const navigation = navigationTo(location, {
      cause: 'initial',
      mode: 'replace',
    });

    return runner.startUrl(navigation, true);
  };

  /** Back/Forward, or any URL change the router didn't make; it can be put back. */
  const follow = (change: ExternalChange) => {
    // Adapters may report our own writes and reverts landing; those match what we show.
    const alreadyShown = sameExternalLocation(change.location, url.lastKnown());
    if (alreadyShown) return;

    const previous = url.lastKnown();
    url.remember(change.location);

    const revert = () => {
      url.remember(previous);

      return change.revert();
    };

    const navigation = navigationTo(change.location, {
      cause: 'external',
      mode: 'replace',
      revert,
    });

    fireAndForget(runner.startUrl(navigation, false), 'split-router');
  };

  /** A link into the router's routes, handled before it lands; the router writes the URL itself. */
  const takeOver = (location: ExternalLocation) => {
    const navigation = navigationTo(location, {
      cause: 'external',
      mode: 'push',
    });

    fireAndForget(runner.startUrl(navigation, false), 'split-router');

    return false;
  };

  /** Whether every pane's guards let the host leave the router's routes. */
  const canLeave = () => {
    const checks = untrack(panes.ids).flatMap((pane) => {
      const from = untrack(() => panes.current(pane));
      if (!from) return [];

      const context = {
        pane,
        from,
        cause: 'external' as const,
        signal: UNCANCELLABLE,
        // The host only asks permission; the router cannot observe its commit.
        onCommit: () => {},
      };

      return checksFor(guards.select(pane, PANE_LEVEL), context);
    });

    return runChecks(checks);
  };

  const intercept: InterceptHandler = (location) => {
    const leavingRouter = !location;
    if (leavingRouter) return canLeave();

    return takeOver(location);
  };

  return {
    navigate,
    navigateToLocation,

    /** Loads the URL and follows the history adapter until the returned stop is called. */
    connect(): () => void {
      const unsubscribe = history.subscribe(follow);
      const stopIntercept = history.intercept?.(intercept);

      fireAndForget(load(url.lastKnown()), 'split-router');

      return () => {
        unsubscribe();
        stopIntercept?.();
      };
    },
  };
}