-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionsPanel.tsx
More file actions
370 lines (347 loc) · 14.2 KB
/
Copy pathCollectionsPanel.tsx
File metadata and controls
370 lines (347 loc) · 14.2 KB
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetDescription,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { FolderPlus, Download, Upload } from "lucide-react"
import { useCollectionStore } from "@/store/collections"
import { Collection, SavedRequest, Tab } from "@/types"
import { useEnvironmentStore } from "@/store/environments"
import { getRequestNameFromUrl } from "@/utils/url"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useState, forwardRef, useRef } from "react"
import { toast } from "sonner"
import { useThemeClass } from "@/hooks/useThemeClass"
import { importFromOpenapi } from '@/utils/collection-converter'
import { CollectionCard } from "./collections/CollectionCard"
import { savedRequestToTab } from "./collections/collectionUtils"
import { useResizablePanel } from "@/hooks/useResizablePanel"
import { OpenapiUrlImportModal } from "./OpenapiUrlImportModal"
import { OpenapiImportModal } from "./OpenapiImportModal"
interface CollectionsPanelProps {
open: boolean
onOpenChange: (open: boolean) => void
currentRequest?: Tab
onRequestSelect: (request: Tab) => void
}
export const CollectionsPanel = forwardRef<HTMLDivElement, CollectionsPanelProps>(
({ open, onOpenChange, currentRequest, onRequestSelect }, _ref) => {
const {
collections,
addCollection,
updateCollection,
deleteCollection,
addRequest,
deleteRequest,
exportCollections,
exportToPostman,
importCollections,
importFromPostman,
} = useCollectionStore()
const { environments, activeEnvironmentId, setActiveEnvironment, setVariable } =
useEnvironmentStore()
const [expandedCollections, setExpandedCollections] = useState<Set<string>>(new Set())
const [openapiUrlModalOpen, setOpenapiUrlModalOpen] = useState(false)
const [openapiRawModalOpen, setOpenapiRawModalOpen] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
const themeClass = useThemeClass()
const { width, isDragging, setIsDragging } = useResizablePanel(600, 450)
const shouldLogImportErrors =
typeof import.meta !== "undefined" &&
Boolean(import.meta.env?.DEV) &&
import.meta.env?.MODE !== "test"
const toggleCollection = (id: string) => {
setExpandedCollections(prev => {
const next = new Set(prev)
if (next.has(id)) {
next.delete(id)
} else {
next.add(id)
}
return next
})
}
const handleAddCollection = () => {
addCollection("New Collection")
}
const handleSaveCurrentRequest = (collectionId: string) => {
if (!currentRequest) return
const { id, loading, response, isEditing, activeSession, ...requestData } = currentRequest
addRequest(collectionId, {
...requestData,
name: getRequestNameFromUrl(requestData.url)
})
}
const handleSelectRequest = (request: Tab) => {
onRequestSelect(request)
onOpenChange(false)
}
/**
* Switch to the collection's environment before opening anything from it.
* A collection written against `{{baseUrl}}` is meaningless without the
* environment that defines it, and silently sending a dev request at prod
* (or the reverse) is exactly the mistake worth designing out.
*/
const activateCollectionEnvironment = (collection?: Collection) => {
if (!collection?.environmentId) return
if (collection.environmentId === activeEnvironmentId) return
if (!environments.some((env) => env.id === collection.environmentId)) return
setActiveEnvironment(collection.environmentId)
}
const handleSelectSavedRequest = (request: SavedRequest, collection?: Collection) => {
activateCollectionEnvironment(collection)
handleSelectRequest(savedRequestToTab(request, collection))
}
const handleRestoreAllRequests = (collectionId: string) => {
const targetCollection = collections.find((collection) => collection.id === collectionId)
if (!targetCollection) return
activateCollectionEnvironment(targetCollection)
targetCollection.requests.forEach((request) => {
onRequestSelect(savedRequestToTab(request, targetCollection))
})
onOpenChange(false)
}
const handleExport = () => {
const blob = new Blob([exportCollections()], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'litepost-collections.json'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
const handleExportPostman = () => {
const blob = new Blob([exportToPostman()], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'postman-collections.json'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
try {
const collections = JSON.parse(e.target?.result as string)
importCollections(collections)
toast.success('Collections imported successfully')
} catch (error) {
if (shouldLogImportErrors) {
console.error('Failed to import collections:', error)
}
toast.error('Failed to import collections')
}
}
reader.readAsText(file)
event.target.value = ''
}
const handleImportPostmanClick = () => {
if (fileInputRef.current) {
const originalOnChange = fileInputRef.current.onchange
fileInputRef.current.onchange = (event) => {
const file = (event.target as HTMLInputElement).files?.[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
try {
importFromPostman(e.target?.result as string)
toast.success('Postman collections imported successfully')
} catch (error) {
if (shouldLogImportErrors) {
console.error('Failed to import Postman collections:', error)
}
toast.error(
error instanceof Error
? error.message
: 'Invalid Postman collection format'
)
}
}
reader.readAsText(file)
if (event.target) {
(event.target as HTMLInputElement).value = ''
}
fileInputRef.current!.onchange = originalOnChange
}
fileInputRef.current.click()
}
}
/**
* Shared by both OpenAPI modals — they differ only in how the document is
* obtained (fetched vs pasted), not in what happens to it afterwards.
*
* Note the fetching lives in the URL modal and goes through the Rust
* backend. This used to call the webview's fetch() directly, which fails on
* any internal API server: a browser fetch enforces CORS, and an internal
* host has no reason to send Access-Control-Allow-Origin for a desktop
* app's origin.
*/
const handleOpenapiImport = (
apiDoc: unknown,
baseUrl: string,
baseUrlVariable?: string
) => {
try {
const importedCollections = importFromOpenapi(apiDoc, baseUrl, { baseUrlVariable });
const requestCount = importedCollections.reduce((sum, c) => sum + c.requests.length, 0);
if (requestCount === 0) {
toast.error("No operations found in that document — is it an OpenAPI spec?");
return;
}
// Seed the variable so the collection works immediately, rather than
// importing 19 requests that all point at an undefined {{baseUrl}}.
let variableNote = "";
if (baseUrlVariable) {
if (activeEnvironmentId) {
setVariable(baseUrlVariable, baseUrl);
const envName = environments.find((env) => env.id === activeEnvironmentId)?.name
variableNote = ` — {{${baseUrlVariable}}} set${envName ? ` in ${envName}` : ""}`;
} else {
variableNote = ` — set {{${baseUrlVariable}}} in an environment to use it`;
}
}
importCollections(importedCollections);
setOpenapiUrlModalOpen(false);
setOpenapiRawModalOpen(false);
toast.success(
`Imported ${requestCount} request${requestCount === 1 ? "" : "s"} from OpenAPI${variableNote}`
);
} catch (error) {
if (shouldLogImportErrors) {
console.error("Error importing OpenAPI:", error);
}
toast.error(error instanceof Error ? error.message : "Invalid OpenAPI format");
}
};
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
className={`${themeClass} w-full sm:max-w-none border-l border-border/30 bg-background/95 backdrop-blur-xl text-foreground [&_button>svg]:text-foreground [&_.close-button]:hover:bg-muted/60 ${isDragging ? "transition-none !duration-0" : ""}`}
style={{ width: width ? `${width}px` : undefined }}
side="right"
>
{/* Resize Handle */}
<div
className="absolute left-0 top-0 bottom-0 w-2 cursor-col-resize hover:bg-primary/20 active:bg-primary/30 z-50 transition-colors group"
onMouseDown={(e) => { e.preventDefault(); setIsDragging(true); }}
>
<div className="absolute left-1 top-1/2 -translate-x-1/2 -translate-y-1/2 w-1 h-12 bg-border/50 group-hover:bg-primary/50 rounded-full transition-colors" />
</div>
<SheetHeader>
<SheetTitle className="text-foreground">Collections</SheetTitle>
<SheetDescription>
Manage your saved API requests and collections
</SheetDescription>
</SheetHeader>
<div className="flex flex-col h-[calc(100vh-5rem)]">
<div className="flex flex-wrap items-center justify-end gap-2.5 py-4 mt-2">
<input
type="file"
ref={fileInputRef}
className="hidden"
accept=".json"
onChange={handleImport}
aria-label="Import Collections"
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-9 shadow-sm bg-background/40 hover:bg-secondary/60 transition-colors">
<Download className="h-4 w-4 mr-2" />
Import
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className={`${themeClass} bg-popover/95 backdrop-blur-xl border-border/40 shadow-xl`}>
<DropdownMenuItem onClick={() => fileInputRef.current?.click()}>
LitePost Format
</DropdownMenuItem>
<DropdownMenuItem onClick={handleImportPostmanClick}>
Postman Format
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setOpenapiUrlModalOpen(true)}>
OpenAPI from URL
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setOpenapiRawModalOpen(true)}>
OpenAPI (paste JSON)
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-9 shadow-sm bg-background/40 hover:bg-secondary/60 transition-colors">
<Upload className="h-4 w-4 mr-2" />
Export
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className={`${themeClass} bg-popover/95 backdrop-blur-xl border-border/40 shadow-xl`}>
<DropdownMenuItem onClick={handleExport}>
LitePost Format
</DropdownMenuItem>
<DropdownMenuItem onClick={handleExportPostman}>
Postman Format
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="default"
size="sm"
className="h-9 shadow-sm shadow-primary/20 transition-all font-medium"
onClick={handleAddCollection}
>
<FolderPlus className="h-4 w-4 mr-2" />
New Collection
</Button>
</div>
<ScrollArea className="flex-1 pr-4">
<div className="space-y-4">
{collections.map((collection) => (
<CollectionCard
key={collection.id}
collection={collection}
currentRequest={currentRequest}
isExpanded={expandedCollections.has(collection.id)}
onToggle={toggleCollection}
onUpdateCollection={updateCollection}
onSaveCurrentRequest={handleSaveCurrentRequest}
onRestoreAllRequests={(targetCollection) =>
handleRestoreAllRequests(targetCollection.id)
}
onDeleteCollection={deleteCollection}
onSelectRequest={handleSelectSavedRequest}
onDeleteRequest={deleteRequest}
/>
))}
</div>
</ScrollArea>
</div>
</SheetContent>
<OpenapiUrlImportModal
open={openapiUrlModalOpen}
onOpenChange={setOpenapiUrlModalOpen}
onImport={handleOpenapiImport}
/>
<OpenapiImportModal
open={openapiRawModalOpen}
onOpenChange={setOpenapiRawModalOpen}
onImport={handleOpenapiImport}
/>
</Sheet >
)
}
)
CollectionsPanel.displayName = "CollectionsPanel"