All files / src/components/detail DetailTabs.tsx

100% Statements 12/12
100% Branches 5/5
100% Functions 4/4
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                                    159x 159x 159x 159x   4x 4x 4x 3x 4x       159x                           99x        
import {
  SectionTabBar,
  SectionTabConfig,
} from "@/components/nav/SectionNav/SectionNav";
import React, { useCallback } from "react";
import { useSearchParams } from "react-router-dom";
 
/**
 * Tabs on a detail page, in the address: `?tab=<key>`, so a tab is a link —
 * "the Usage of this source" can be shared, and Back returns to it. The
 * default tab is never written (the plain address is it); an unknown value
 * falls back to the default rather than blanking the page; every other
 * parameter the page carries (a list's filters, `?workspace=`) is kept.
 *
 * The tab bar is the section navigation's (`SectionTabBar`), so a detail
 * page's tabs look like a section page's.
 *
 * ```tsx
 * const [tab, setTab] = useDetailTab(["overview", "content", "usage"] as const);
 * <DetailTabs tabs={TABS} active={tab} onChange={setTab} />
 * ```
 */
export function useDetailTab<K extends string>(
  keys: readonly K[],
  fallback: K = keys[0],
): [K, (key: K) => void] {
  const [params, setParams] = useSearchParams();
  const raw = params.get("tab");
  const active = keys.includes(raw as K) ? (raw as K) : fallback;
  const setActive = useCallback(
    (key: K) =>
      setParams((current) => {
        const next = new URLSearchParams(current);
        if (key === fallback) next.delete("tab");
        else next.set("tab", key);
        return next;
      }),
    [setParams, fallback],
  );
  return [active, setActive];
}
 
export interface DetailTabsProps<K extends string> {
  tabs: SectionTabConfig<K>[];
  active: K;
  onChange: (key: K) => void;
}
 
export function DetailTabs<K extends string>({
  tabs,
  active,
  onChange,
}: DetailTabsProps<K>) {
  return <SectionTabBar tabs={tabs} active={active} onChange={onChange} />;
}
 
export default DetailTabs;