All files / src/components/dashboard SaveToDashboard.tsx

38.7% Statements 12/31
33.33% Branches 8/24
15.38% Functions 2/13
42.3% Lines 11/26

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                                                    13x             548x 548x   548x 548x   548x             548x   548x                                                 548x 194x           548x                                                                                                                                                          
import { MessageListTarget } from "@/objects/Dashboard";
import { APP_ROUTES } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Bookmark, BookmarkCheck, Home, Loader2 } from "lucide-react";
import React from "react";
import { Link } from "react-router-dom";
 
export interface SaveToDashboardProps {
  /** The message being saved. */
  content: string;
  role?: string;
  conversationId?: string | null;
  /** Shown under the saved entry, e.g. the agent or model that answered. */
  sourceLabel?: string | null;
  className?: string;
}
 
/** Save a chat message into a saved-messages widget on one of the user's
 *  dashboards.
 *
 *  The target list is chosen from a flat picker served by the API, so this
 *  costs one request regardless of how many boards the user has. Appending is
 *  a server-side operation, so nothing here has to read the widget first.
 */
const SaveToDashboard: React.FC<SaveToDashboardProps> = ({
  content,
  role = "assistant",
  conversationId,
  sourceLabel,
  className = "",
}) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
 
  const [open, setOpen] = React.useState(false);
  const [savedTo, setSavedTo] = React.useState<string | null>(null);
 
  const { data, isLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.DASHBOARD_MESSAGE_LISTS],
    queryFn: () => getApiHandler().dashboard_router.messageLists(),
    // Only look them up once the user actually opens the menu.
    enabled: open,
  });
 
  const targets: MessageListTarget[] = (data as MessageListTarget[]) ?? [];
 
  const save = useMutation({
    mutationFn: (target: MessageListTarget) =>
      getApiHandler().dashboard_router.saveMessage(
        target.dashboard_id,
        target.widget_id,
        {
          content,
          role,
          conversation_id: conversationId ?? null,
          source_label: sourceLabel ?? null,
        },
      ),
    onSuccess: (_result, target) => {
      setSavedTo(target.dashboard_name);
      setOpen(false);
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.DASHBOARD_MESSAGE_LISTS],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.DASHBOARD_BY_ID, target.dashboard_id],
      });
      window.setTimeout(() => setSavedTo(null), 2500);
    },
  });
 
  React.useEffect(() => {
    Eif (!open) return undefined;
    const close = () => setOpen(false);
    window.addEventListener("click", close);
    return () => window.removeEventListener("click", close);
  }, [open]);
 
  return (
    <span className="relative inline-flex">
      <button
        type="button"
        title={savedTo ? `Saved to ${savedTo}` : "Save to dashboard"}
        onClick={(e) => {
          e.stopPropagation();
          setOpen((current) => !current);
        }}
        className={className}
      >
        {savedTo ? (
          <BookmarkCheck className="w-3.5 h-3.5 text-emerald-500" />
        ) : (
          <Bookmark className="w-3.5 h-3.5" />
        )}
      </button>
 
      {open && (
        <div
          onClick={(e) => e.stopPropagation()}
          className="absolute right-0 top-7 z-30 w-60 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-lg py-1"
        >
          <p className="px-3 py-1.5 text-[11px] font-medium text-gray-400 dark:text-gray-500">
            Save to
          </p>
 
          {isLoading ? (
            <p className="flex items-center gap-2 px-3 py-2 text-xs text-gray-400">
              <Loader2 className="w-3 h-3 animate-spin" /> Loading lists…
            </p>
          ) : targets.length === 0 ? (
            <div className="px-3 py-2">
              <p className="text-[11px] leading-snug text-gray-500 dark:text-gray-400">
                No saved-message lists yet. Add a “Saved messages” widget to a
                dashboard first.
              </p>
              <Link
                to={APP_ROUTES.USER.dashboards}
                className="mt-1.5 inline-block text-[11px] font-medium text-blue-600 dark:text-blue-400 hover:underline"
              >
                Open dashboards
              </Link>
            </div>
          ) : (
            <ul className="max-h-56 overflow-auto">
              {targets.map((target) => (
                <li key={target.widget_id}>
                  <button
                    type="button"
                    disabled={save.isPending}
                    onClick={() => save.mutate(target)}
                    className="flex w-full flex-col items-stretch px-3 py-1.5 text-left hover:bg-gray-50 dark:hover:bg-gray-700/60 disabled:opacity-50"
                  >
                    <span className="flex items-center gap-1.5">
                      {target.dashboard_is_home && (
                        <Home className="w-2.5 h-2.5 shrink-0 text-gray-400" />
                      )}
                      <span className="text-xs text-gray-800 dark:text-gray-100 truncate">
                        {target.widget_title || "Saved messages"}
                      </span>
                    </span>
                    <span className="block text-[10px] text-gray-400 dark:text-gray-500 truncate">
                      {target.dashboard_name} · {target.item_count} saved
                    </span>
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </span>
  );
};
 
export default SaveToDashboard;