summaryrefslogtreecommitdiff
path: root/components/client-table/client-table-preset.tsx
blob: 64930e7a208193c9f337376d5e11e6ea04f60d53 (plain)
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
"use client";

import * as React from "react";
import { Table } from "@tanstack/react-table";
import { useSession } from "next-auth/react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Bookmark, Save, Trash2 } from "lucide-react";
import {
  getPresets,
  savePreset,
  deletePreset,
} from "./preset-actions";
import { Preset } from "./preset-types";
import { toast } from "sonner"; 

interface ClientTablePresetProps<TData> {
  table: Table<TData>;
  tableKey: string;
}

export function ClientTablePreset<TData>({
  table,
  tableKey,
}: ClientTablePresetProps<TData>) {
  const { data: session } = useSession();
  const [savedPresets, setSavedPresets] = React.useState<Preset[]>([]);
  const [isPresetDialogOpen, setIsPresetDialogOpen] = React.useState(false);
  const [newPresetName, setNewPresetName] = React.useState("");
  const [isLoading, setIsLoading] = React.useState(false);

  const fetchSettings = React.useCallback(async () => {
    const userIdVal = session?.user?.id;
    if (!userIdVal) return;
    
    const userId = Number(userIdVal); 
    if (isNaN(userId)) return;

    const res = await getPresets(tableKey, userId);
    if (res.success && res.data) {
      setSavedPresets(res.data);
    }
  }, [session, tableKey]);

  React.useEffect(() => {
    if (session) {
      fetchSettings();
    }
  }, [fetchSettings, session]);

  const handleSavePreset = async () => {
    const userIdVal = session?.user?.id;
    if (!newPresetName.trim() || !userIdVal) return;
    const userId = Number(userIdVal);
    if (isNaN(userId)) return;

    setIsLoading(true);
    const state = table.getState();
    const settingToSave = {
      sorting: state.sorting,
      columnFilters: state.columnFilters,
      globalFilter: state.globalFilter,
      columnVisibility: state.columnVisibility,
      columnPinning: state.columnPinning,
      columnOrder: state.columnOrder,
      grouping: state.grouping,
      pagination: { pageSize: state.pagination.pageSize }, 
    };

    const res = await savePreset(userId, tableKey, newPresetName, settingToSave);
    setIsLoading(false);

    if (res.success) {
      toast.success("Preset saved successfully");
      setIsPresetDialogOpen(false);
      setNewPresetName("");
      fetchSettings();
    } else {
      toast.error("Failed to save preset");
    }
  };

  const handleLoadPreset = (preset: Preset) => {
    const s = preset.setting as Record<string, any>;
    if (!s) return;

    if (s.sorting) table.setSorting(s.sorting);
    if (s.columnFilters) table.setColumnFilters(s.columnFilters);
    if (s.globalFilter !== undefined) table.setGlobalFilter(s.globalFilter);
    if (s.columnVisibility) table.setColumnVisibility(s.columnVisibility);
    if (s.columnPinning) table.setColumnPinning(s.columnPinning);
    if (s.columnOrder) table.setColumnOrder(s.columnOrder);
    if (s.grouping) table.setGrouping(s.grouping);
    if (s.pagination?.pageSize) table.setPageSize(s.pagination.pageSize);
    
    toast.success(`Preset "${preset.name}" loaded`);
  };

  const handleDeletePreset = async (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
    if (!confirm("Are you sure you want to delete this preset?")) return;

    const res = await deletePreset(id);
    if (res.success) {
      toast.success("Preset deleted");
      fetchSettings();
    } else {
      toast.error("Failed to delete preset");
    }
  };

  if (!session) return null;

  return (
    <>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="ml-2 hidden h-8 lg:flex">
              <Bookmark className="mr-2 h-4 w-4" />
              Presets
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-[200px]">
            <DropdownMenuLabel>Saved Presets</DropdownMenuLabel>
            <DropdownMenuSeparator />
            {savedPresets.length === 0 ? (
                <div className="p-2 text-sm text-muted-foreground text-center">No saved presets</div>
            ) : (
                savedPresets.map((preset) => (
                    <DropdownMenuItem key={preset.id} onClick={() => handleLoadPreset(preset)} className="flex justify-between cursor-pointer">
                        <span className="truncate flex-1">{preset.name}</span>
                        <Button variant="ghost" size="icon" className="h-4 w-4" onClick={(e) => handleDeletePreset(e, preset.id)}>
                            <Trash2 className="h-3 w-3 text-destructive" />
                        </Button>
                    </DropdownMenuItem>
                ))
            )}
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={() => setIsPresetDialogOpen(true)} className="cursor-pointer">
                <Save className="mr-2 h-4 w-4" />
                Save Current Preset
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>

        <Dialog open={isPresetDialogOpen} onOpenChange={setIsPresetDialogOpen}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Save Preset</DialogTitle>
                    <DialogDescription>
                        Save the current table configuration as a preset.
                    </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                    <Input 
                        placeholder="Preset Name" 
                        value={newPresetName} 
                        onChange={(e) => setNewPresetName(e.target.value)}
                    />
                </div>
                <DialogFooter>
                    <Button variant="outline" onClick={() => setIsPresetDialogOpen(false)}>Cancel</Button>
                    <Button onClick={handleSavePreset} disabled={isLoading}>Save</Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    </>
  );
}