All files / src/components/owner origin.ts

95.83% Statements 23/24
80.64% Branches 25/31
100% Functions 3/3
100% Lines 18/18

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                            234x 188x 188x 9x   179x                         227x 222x 178x 168x     10x     227x 9x 227x   9x     9x   1x       104x 30x  
import type { Resource } from "@/objects/Doc";
import type { WorkspaceContextValue } from "@/context/WorkspaceContext";
import {
  PERSONAL_WORKSPACE,
  WorkspaceRef,
  workspaceRef,
} from "@/routes/workspace";
 
/** Why a resource is in the workspace a page is showing — or `elsewhere`,
 *  when it belongs to another workspace entirely. */
export type Origin = "own" | "inherited" | "required" | "built_in" | "elsewhere";
 
/** The workspace that owns `resource` (null for a built-in). */
export function homeOf(resource: Resource & { is_system?: boolean }): WorkspaceRef | null {
  if (resource.is_system) return null;
  Iif (resource.owner_project_id) return workspaceRef("project", resource.owner_project_id);
  if (resource.owner_organisation_id) {
    return workspaceRef("organisation", resource.owner_organisation_id);
  }
  return PERSONAL_WORKSPACE;
}
 
/**
 * `resource`'s origin in workspace `ws`: what a list annotated, or — for a
 * detail page, whose response carries none — what its owner says. A
 * project's parent's resource is inherited (the page could only load it if
 * it is); anything else not owned here belongs elsewhere.
 */
export function originIn(
  resource: Resource & { is_system?: boolean },
  ws: Pick<WorkspaceContextValue, "kind" | "id" | "info">,
): Origin {
  if (resource.origin) return resource.origin;
  if (resource.is_system) return "built_in";
  if (ws.kind === "personal") {
    return resource.owner_user_id ? "own" : "elsewhere";
  }
  const own =
    ws.kind === "organisation"
      ? resource.owner_organisation_id === ws.id
      : resource.owner_project_id === ws.id;
  if (own) return "own";
  const parent = ws.kind === "project" ? ws.info?.parent : undefined;
  if (parent) {
    const parentOwns =
      parent.kind === "organisation"
        ? resource.owner_organisation_id === parent.id
        : !!resource.owner_user_id && resource.owner_user_id === parent.id;
    if (parentOwns) return "inherited";
  }
  return "elsewhere";
}
 
/** Read-only here: inherited, required, or built in. */
export const readOnlyOrigin = (origin: Origin) =>
  origin === "inherited" || origin === "required" || origin === "built_in";