All files / src/components/owner WorkspaceGuard.tsx

100% Statements 24/24
84.44% Branches 38/45
100% Functions 5/5
100% Lines 23/23

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109                                      104x               299x 299x 299x 299x 1x     1x       299x     299x       299x       299x 299x     299x 299x 299x   299x 173x 1x       299x 5x   299x 299x                           1x                                                      
import React, { useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import { ArrowUpRight, ArrowDownToLine, Copy } from "lucide-react";
// The unwrapped router: these links and redirects go *between* workspaces,
// which the app's own (routes/router.tsx) would keep inside this one.
import { Link, useLocation, useNavigate } from "react-router";
import { encodeResourceId } from "@/components/detail/useResourceId";
import { useWorkspace } from "@/context/WorkspaceContext";
import type { Resource } from "@/objects/Doc";
import { useApiHandler } from "@/services/useApiHandler";
import { errorDetail } from "@/util/apiError";
import { homeOf, originIn } from "./origin";
 
/**
 * On a resource's own page: sends it to the workspace it belongs to when it
 * was opened in another (an old link, a bookmark from before workspaces),
 * and says so when the project this is shows its parent's — usable here,
 * changed only there.
 */
export const WorkspaceGuard: React.FC<{
  resource: (Resource & { is_system?: boolean }) | null | undefined;
  /** What it is, for the banner: "agent", "rule", … */
  noun: string;
  /** The kind svc-core copies it as (`/ownership/copy`), when a project
   *  may make its own editable copy of an inherited one. */
  copyKind?: string;
}> = ({ resource, noun, copyKind }) => {
  const ws = useWorkspace();
  const navigate = useNavigate();
  const { getApiHandler } = useApiHandler();
  const copy = useMutation({
    mutationFn: () => getApiHandler().ownership_router.copy(copyKind!, resource!.id),
    // Open the copy where the original was: same page, its id.
    onSuccess: (made) =>
      navigate(
        pathname.replace(encodeResourceId(resource!.id), encodeResourceId(made.id)),
      ),
  });
  const { pathname, search, hash } = useLocation();
  // A project's parent is only known once the workspace resolves; until
  // then an inherited row would read as somebody else's.
  const settled = ws.kind === "personal" || !!ws.info;
  // A row with no owner columns at all (a skill run) has no workspace of its
  // own to belong to or be inherited from.
  const ownable =
    !!resource &&
    ("owner_user_id" in resource ||
      "owner_organisation_id" in resource ||
      "owner_project_id" in resource);
  const origin = resource && ownable && settled ? originIn(resource, ws) : null;
  const home = resource ? homeOf(resource) : null;
  // Only a page under this workspace's own prefix is redirected — once it
  // has moved, the page re-renders under the workspace it moved to.
  const here = pathname.startsWith(ws.prefix);
  const rest = here ? pathname.slice(ws.prefix.length) : "";
  const there = home ? `${home.prefix}${rest}${search}${hash}` : null;
 
  useEffect(() => {
    if (origin === "elsewhere" && here && there && home?.key !== ws.key) {
      navigate(there, { replace: true });
    }
  }, [origin, here, there, home?.key, ws.key, navigate]);
 
  if (origin !== "inherited" && origin !== "required") return null;
  const parent = ws.info?.parent;
  const from =
    parent?.kind === "personal" ? "your personal workspace" : (parent?.name ?? "the parent");
  return (
    <div
      role="note"
      className="mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-sky-200 dark:border-sky-900/60 bg-sky-50 dark:bg-sky-950/20 px-3 py-2 text-xs text-sky-800 dark:text-sky-200"
    >
      <ArrowDownToLine className="size-3.5 shrink-0" />
      <span className="flex-1 min-w-0">
        {origin === "required"
          ? `${from} requires this ${noun} of every project. It governs this project and is changed only there.`
          : `Inherited from ${from}. This project uses this ${noun}; it is changed only there.`}
      </span>
      {copyKind && (
        <button
          type="button"
          onClick={() => copy.mutate()}
          disabled={copy.isPending}
          className="inline-flex items-center gap-1 font-medium underline-offset-2 hover:underline disabled:opacity-50"
        >
          <Copy className="size-3" />
          {copy.isPending ? "Copying…" : "Make a copy here"}
        </button>
      )}
      {copy.isError && (
        <span role="alert" className="basis-full text-red-700 dark:text-red-300">
          {errorDetail(copy.error, "Couldn't copy it.")}
        </span>
      )}
      {there && (
        <Link
          to={there}
          className="inline-flex items-center gap-1 font-medium underline-offset-2 hover:underline"
        >
          Open in {parent?.kind === "personal" ? "Personal" : (parent?.name ?? "parent")}
          <ArrowUpRight className="size-3" />
        </Link>
      )}
    </div>
  );
};
 
export default WorkspaceGuard;