All files / src/pages/flowsheet-page/menuBar ShareFlowsheet.tsx

81.57% Statements 31/38
40% Branches 4/10
71.42% Functions 5/7
81.57% Lines 31/38

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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244                                                                62x     8135x 8135x     8135x           8135x 8135x   8135x 8135x 8135x 8135x 8135x   8135x                           3x 3x               1x 1x         1x         1x 1x       1x             1x 1x 1x                   1x           1x               1x             1x                                                               3x                                                                 25x                             1x                                 1x                          
import { defineCommand, useRegisterCommand } from "just-search-it";
import { Share2 } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/ahuora-design-system/ui/dialog";
import { Input } from "@/ahuora-design-system/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import { Separator } from "@/ahuora-design-system/ui/separator";
import {
  useCoreFlowsheetsListSharedUsersRetrieveQuery,
  useCoreFlowsheetsRemoveUserCreateMutation,
  useCoreFlowsheetsShareFlowsheetCreateMutation,
  useCoreFlowsheetsUpdateSharedUserAccessCreateMutation,
} from "@/api/apiStore.gen";
import { useProject, useProjectId } from "@/hooks/project";
import { normalizeSharedUsers } from "@/lib/flowsheetAccess";
import { ToolTipCover } from "../../../ahuora-design-system/ui/tooltip";
 
const ShareFlowsheetCommand = defineCommand<[], void>("shareFlowsheet");
 
export default function ShareFlowsheet() {
  const [email, setEmail] = useState("");
  const [shareAccess, setShareAccess] = useState<"read_only" | "editable">(
    "read_only",
  );
  const { data: emailList } = useCoreFlowsheetsListSharedUsersRetrieveQuery(
    undefined,
    {
      refetchOnMountOrArgChange: true,
    },
  );
  const [shareFlowsheet] = useCoreFlowsheetsShareFlowsheetCreateMutation();
  const [clearFlowsheetShares] = useCoreFlowsheetsRemoveUserCreateMutation();
  const [updateSharedUserAccess] =
    useCoreFlowsheetsUpdateSharedUserAccessCreateMutation();
  const flowsheetId = useProjectId();
  const project = useProject();
  const [open, setOpen] = useState(false);
  const sharedUsers = normalizeSharedUsers(emailList?.users);
 
  useRegisterCommand(
    ShareFlowsheetCommand,
    {
      name: "Share Flowsheet",
      description: "Share your flowsheet with other users",
      group: "Sharing",
      icon: <Share2 className="icon-ls" />,
    },
    () => {
      setOpen(true);
    },
  );
 
  async function share() {
    const trimmedEmail = email.trim();
    const normalizedEmail = trimmedEmail.toLowerCase();
 
    if (!trimmedEmail) {
      toast.error("Enter an email address to share this flowsheet.");
      return;
    }
 
    if (project?.owner.email?.toLowerCase() === normalizedEmail) {
      toast.error("You cannot share a flowsheet with yourself.");
      return;
    }
 
    if (
      sharedUsers.some(
        (sharedUser) => sharedUser.email.toLowerCase() === normalizedEmail,
      )
    ) {
      // Keep duplicate-share feedback local to the dialog so the owner gets a
      // fast explanation instead of waiting for a round trip to the backend.
      toast.error("This user already has access to the flowsheet.");
      return;
    }
 
    try {
      await shareFlowsheet({
        flowsheetSharing: {
          user_email: trimmedEmail,
          flowsheet: flowsheetId,
          read_only: shareAccess === "read_only",
        },
      }).unwrap();
      toast.success("Flowsheet shared successfully.");
      setEmail("");
      setShareAccess("read_only");
    } catch (error: any) {
      toast.error(
        error?.data?.error ?? "Unable to share this flowsheet right now.",
      );
    }
  }
 
  async function handleRemove(userEmail: string) {
    try {
      await clearFlowsheetShares({
        removeSharedUser: {
          user_email: userEmail,
          flowsheet: flowsheetId,
        },
      }).unwrap();
      toast.success("Access removed.");
    } catch (error: any) {
      toast.error(error?.data?.error ?? "Unable to remove access.");
    }
  }
 
  async function handleAccessChange(userEmail: string, readOnly: boolean) {
    try {
      await updateSharedUserAccess({
        updateSharedUserAccess: {
          user_email: userEmail,
          flowsheet: flowsheetId,
          read_only: readOnly,
        },
      }).unwrap();
      toast.success("Access updated.");
    } catch (error: any) {
      toast.error(error?.data?.error ?? "Unable to update access.");
    }
  }
 
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <ToolTipCover asChild content="Share your flowsheet with other users">
        <DialogTrigger asChild>
          <Button
            size="sm"
            variant="secondary"
            aria-label="share-flowsheet-dialog"
          >
            <Share2 size={18} /> Share
          </Button>
        </DialogTrigger>
      </ToolTipCover>
      <DialogContent className="flex flex-col gap-5 sm:max-w-[520px]">
        <DialogHeader className="flex flex-col gap-2">
          <DialogTitle>Share Your Flowsheet</DialogTitle>
          <DialogDescription>
            Share your flowsheet with other users by entering an email address
            in the box below.
          </DialogDescription>
        </DialogHeader>
        <div className="flex flex-col gap-2 sm:flex-row">
          <Input
            id="email"
            placeholder="Enter email"
            className="flex min-w-0 rounded-md border h-9"
            onChange={(e) => setEmail(e.target.value)}
            value={email}
            aria-label="share-flowsheet-email-input"
          />
          <Select
            value={shareAccess}
            onValueChange={(value: "read_only" | "editable") =>
              setShareAccess(value)
            }
          >
            <SelectTrigger
              className="w-full sm:w-[250px]"
              aria-label="share-flowsheet-access-select"
            >
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="read_only">Can view</SelectItem>
              <SelectItem value="editable">Can edit</SelectItem>
            </SelectContent>
          </Select>
          <Button className="shrink-0" onClick={share}>
            Share
          </Button>
        </div>
        <div className="flex flex-col gap-2">
          {sharedUsers.length !== 0 && (
            <div className="flex flex-col gap-3" aria-label="shared-users">
              <Separator />
              <h3>Shared with</h3>
            </div>
          )}
          {sharedUsers.map((sharedUser) => (
            <div
              className="flex justify-between items-center"
              key={sharedUser.email}
              aria-label={`shared-user-${sharedUser.email}`}
            >
              <div className="flex flex-col">
                <p>{sharedUser.email}</p>
              </div>
              <div className="flex items-center gap-2">
                <Select
                  value={sharedUser.read_only ? "read_only" : "editable"}
                  onValueChange={(value: "read_only" | "editable") =>
                    // The dropdown mirrors the add-user permission selector so
                    // owners can switch a share between view-only and editable
                    // without removing and re-adding the user.
                    handleAccessChange(sharedUser.email, value === "read_only")
                  }
                >
                  <SelectTrigger
                    className="w-[140px]"
                    aria-label={`shared-user-access-${sharedUser.email}`}
                  >
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="read_only">Can view</SelectItem>
                    <SelectItem value="editable">Can edit</SelectItem>
                  </SelectContent>
                </Select>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() => handleRemove(sharedUser.email)}
                  aria-label={`remove-user-${sharedUser.email}`}
                >
                  Remove
                </Button>
              </div>
            </div>
          ))}
        </div>
      </DialogContent>
    </Dialog>
  );
}