All files / src/context WorkspaceContext.tsx

100% Statements 10/10
100% Branches 0/0
100% Functions 5/5
100% Lines 9/9

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                                                          118x   668x               118x   118x 13775x   118x         591x 2800x     591x        
import React, { createContext, useContext, useMemo } from "react";
import type { OrganisationRole, AccessMap } from "@/objects/Organisation";
import {
  PERSONAL_WORKSPACE,
  WorkspaceKind,
  WorkspaceRef,
  pathIn,
} from "@/routes/workspace";
 
/** What svc-core says about a workspace (`GET /workspaces/resolve`). */
export interface WorkspaceInfo {
  key: string;
  kind: WorkspaceKind;
  id: string;
  name?: string | null;
  parent?: { key: string; kind: WorkspaceKind; id: string; name?: string | null } | null;
  role?: OrganisationRole | null;
  access?: AccessMap | null;
  /** An admin by position (of the organisation, or as the owner). */
  implicit?: boolean;
}
 
export interface WorkspaceContextValue extends WorkspaceRef {
  /** Loaded once the workspace resolves; absent for Personal until then. */
  info?: WorkspaceInfo;
  /** `to` inside this workspace (`routes/workspace.ts` `pathIn`). */
  path: (to: string) => string;
}
 
const personal: WorkspaceContextValue = {
  ...PERSONAL_WORKSPACE,
  path: (to) => to,
};
 
/**
 * The workspace the page is showing. Personal outside any provider, so a
 * page rendered on its own (a test, the smoke suite) behaves as it always
 * has.
 */
export const WorkspaceContext = createContext<WorkspaceContextValue>(personal);
 
export const useWorkspace = (): WorkspaceContextValue =>
  useContext(WorkspaceContext);
 
export const WorkspaceProvider: React.FC<{
  workspace: WorkspaceRef;
  info?: WorkspaceInfo;
  children: React.ReactNode;
}> = ({ workspace, info, children }) => {
  const value = useMemo<WorkspaceContextValue>(
    () => ({ ...workspace, info, path: (to) => pathIn(workspace, to) }),
    [workspace, info],
  );
  return (
    <WorkspaceContext.Provider value={value}>{children}</WorkspaceContext.Provider>
  );
};