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.3 KB
Raw Blame
import { useSearchParams } from '@solidjs/router';
import {
  type Accessor,
  batch,
  createContext,
  type ParentProps,
  useContext,
} from 'solid-js';
import { createStore } from 'solid-js/store';

type ParamSchema = Record<string, string>;

type ParamMap = Record<string, string | undefined>;

// Use a version-bumping pattern to trigger successive reactive updates when
// calling goToLocationFromParams multiple times even with same values.
type ParamVersions = Record<string, number | undefined>;

type ResolvedParams<T extends ParamSchema> = {
  [K in keyof T]: Accessor<string | undefined>;
};

/**
 * Provides stable per-param accessors so unrelated params do not invalidate
 * consumers.
 */
type ParamsContextValue = {
  getParam: (param: string) => Accessor<string | undefined>;
  getNavigationCount: (param: string) => Accessor<number>;
};

const ParamsContext = createContext<ParamsContextValue>({
  getParam: () => () => undefined,
  getNavigationCount: () => () => 0,
});

function flattenParamValue(
  val: string | string[] | undefined
): string | undefined {
  return Array.isArray(val) ? val[0] : val;
}

export function createParamsState() {
  const [blockParams, setBlockParams] = createStore<ParamMap>({});
  const [navigationVersions, setNavigationVersions] =
    createStore<ParamVersions>({});

  return {
    getParam: (param: string) => () => {
      navigationVersions[param];
      return blockParams[param];
    },
    getNavigationCount: (param: string) => () => navigationVersions[param] ?? 0,
    navigate: (params: Record<string, string>) => {
      batch(() => {
        const paramNames = new Set([
          ...Object.keys(blockParams),
          ...Object.keys(params),
        ]);

        for (const param of paramNames) {
          setBlockParams(param, params[param]);
        }

        for (const param of Object.keys(params)) {
          setNavigationVersions(param, (navigationVersions[param] ?? 0) + 1);
        }
      });
    },
  };
}

export type ParamsState = ReturnType<typeof createParamsState>;

export function ParamsProvider(
  props: ParentProps<{
    state?: ParamsState;
  }>
) {
  const [searchParams] = useSearchParams();
  const state = props.state ?? createParamsState();
  const context: ParamsContextValue = {
    getParam: (param) => {
      const blockValue = state.getParam(param);
      return () => blockValue() ?? flattenParamValue(searchParams[param]);
    },
    getNavigationCount: state.getNavigationCount,
  };

  return (
    <ParamsContext.Provider value={context}>
      {props.children}
    </ParamsContext.Provider>
  );
}

/**
 * Returns URL/block params scoped to the requested schema keys. The context
 * provides additional logic for retriggering signals on successive calls
 * to `goToLocationFromParams` with the same values.
 */
export function useUrlParams<T extends ParamSchema>(
  schema: T
): ResolvedParams<T> {
  const params = useContext(ParamsContext);

  return Object.fromEntries(
    Object.entries(schema).map(([key, param]) => [key, params.getParam(param)])
  ) as ResolvedParams<T>;
}

/**
 * Counts `goToLocationFromParams` calls that named `param`, including repeats
 * with the same value. Stays 0 while the value only comes from the URL.
 */
export function useParamNavigationCount(param: string): Accessor<number> {
  return useContext(ParamsContext).getNavigationCount(param);
}