@arronqzy/react-blueprint 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,448 @@
1
+ import { useEffect, useMemo, useRef, useState } from "react";
2
+ import {
3
+ Button,
4
+ Dialog,
5
+ DialogContent,
6
+ DialogDescription,
7
+ DialogFooter,
8
+ DialogHeader,
9
+ DialogTitle,
10
+ Label,
11
+ Textarea,
12
+ cn,
13
+ } from "@arronqzy/ui";
14
+ import {
15
+ downloadApiCollectionTemplate,
16
+ getApiCollectionTemplateJson,
17
+ type ApiCollectionRecord,
18
+ type ApiCollectionSyncResult,
19
+ } from "@arronqzy/blueprint-dsl";
20
+ import { useI18nOptional as useI18n } from "@arronqzy/i18n/react";
21
+
22
+ import {
23
+ getApiCollectionRecords,
24
+ removeApiCollection,
25
+ subscribeApiCollections,
26
+ upsertApiCollectionFromJson,
27
+ } from "../library/api-collection-store";
28
+
29
+ export type ApiCollectionUploadStartInfo = {
30
+ fileNames: string[];
31
+ count: number;
32
+ };
33
+
34
+ export type ApiCollectionUploadSuccessInfo = {
35
+ collections: Array<{
36
+ id: string;
37
+ name: string;
38
+ apiCount: number;
39
+ persistLocal: boolean;
40
+ }>;
41
+ };
42
+
43
+ export type ApiCollectionManagerDialogProps = {
44
+ open: boolean;
45
+ onOpenChange: (open: boolean) => void;
46
+ onUploadStart?: (info: ApiCollectionUploadStartInfo) => void;
47
+ onUploadSuccess?: (info: ApiCollectionUploadSuccessInfo) => void;
48
+ /** 按 URL 同步当前蓝图里的 Fetch 节点 */
49
+ onSyncCollection?: (
50
+ record: ApiCollectionRecord
51
+ ) => ApiCollectionSyncResult | Promise<ApiCollectionSyncResult>;
52
+ };
53
+
54
+ function formatSyncResultMessage(
55
+ t: (key: string, params?: Record<string, string | number>) => string,
56
+ result: ApiCollectionSyncResult
57
+ ): string {
58
+ if (result.updatedCount <= 0) {
59
+ return t("blueprint.apiCollection.syncNone");
60
+ }
61
+ const names = result.nodes.map((node) => node.label).join("、");
62
+ return t("blueprint.apiCollection.syncSuccessDetail", {
63
+ count: result.updatedCount,
64
+ names,
65
+ });
66
+ }
67
+
68
+ export function ApiCollectionManagerDialog({
69
+ open,
70
+ onOpenChange,
71
+ onUploadStart,
72
+ onUploadSuccess,
73
+ onSyncCollection,
74
+ }: ApiCollectionManagerDialogProps) {
75
+ const { t } = useI18n();
76
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
77
+ const [records, setRecords] = useState<ApiCollectionRecord[]>(() =>
78
+ getApiCollectionRecords()
79
+ );
80
+ const [persistLocalDefault, setPersistLocalDefault] = useState(true);
81
+ const [error, setError] = useState<string | null>(null);
82
+ const [busy, setBusy] = useState(false);
83
+
84
+ const [editorOpen, setEditorOpen] = useState(false);
85
+ const [editingId, setEditingId] = useState<string | null>(null);
86
+ const [editorJson, setEditorJson] = useState("");
87
+ const [editorPersistLocal, setEditorPersistLocal] = useState(true);
88
+ const [editorError, setEditorError] = useState<string | null>(null);
89
+
90
+ useEffect(() => {
91
+ if (!open) return;
92
+ setRecords([...getApiCollectionRecords()]);
93
+ return subscribeApiCollections(() => setRecords([...getApiCollectionRecords()]));
94
+ }, [open]);
95
+
96
+ const sorted = useMemo(
97
+ () => [...records].sort((a, b) => b.updatedAt - a.updatedAt),
98
+ [records]
99
+ );
100
+
101
+ const openCreateEditor = () => {
102
+ setEditingId(null);
103
+ setEditorJson(getApiCollectionTemplateJson());
104
+ setEditorPersistLocal(persistLocalDefault);
105
+ setEditorError(null);
106
+ setEditorOpen(true);
107
+ };
108
+
109
+ const openEditEditor = (record: ApiCollectionRecord) => {
110
+ setEditingId(record.id);
111
+ setEditorJson(record.rawJson);
112
+ setEditorPersistLocal(record.persistLocal);
113
+ setEditorError(null);
114
+ setEditorOpen(true);
115
+ };
116
+
117
+ const handleSaveEditor = async () => {
118
+ setBusy(true);
119
+ setEditorError(null);
120
+ try {
121
+ const result = await upsertApiCollectionFromJson({
122
+ id: editingId ?? undefined,
123
+ rawJson: editorJson,
124
+ persistLocal: editorPersistLocal,
125
+ });
126
+ if (!result.ok) {
127
+ setEditorError(result.error);
128
+ return;
129
+ }
130
+ setEditorOpen(false);
131
+ } finally {
132
+ setBusy(false);
133
+ }
134
+ };
135
+
136
+ const handleDelete = async (id: string) => {
137
+ const ok = window.confirm(t("blueprint.apiCollection.confirmDelete"));
138
+ if (!ok) return;
139
+ setBusy(true);
140
+ setError(null);
141
+ try {
142
+ await removeApiCollection(id);
143
+ } catch (err) {
144
+ setError(err instanceof Error ? err.message : String(err));
145
+ } finally {
146
+ setBusy(false);
147
+ }
148
+ };
149
+
150
+ const handleSync = async (record: ApiCollectionRecord) => {
151
+ if (!onSyncCollection) {
152
+ setError(t("blueprint.apiCollection.syncUnavailable"));
153
+ return;
154
+ }
155
+ setBusy(true);
156
+ setError(null);
157
+ try {
158
+ const result = await onSyncCollection(record);
159
+ window.alert(formatSyncResultMessage(t, result));
160
+ } catch (err) {
161
+ setError(err instanceof Error ? err.message : String(err));
162
+ } finally {
163
+ setBusy(false);
164
+ }
165
+ };
166
+
167
+ const handleSyncFromEditor = async () => {
168
+ setBusy(true);
169
+ setEditorError(null);
170
+ try {
171
+ const result = await upsertApiCollectionFromJson({
172
+ id: editingId ?? undefined,
173
+ rawJson: editorJson,
174
+ persistLocal: editorPersistLocal,
175
+ });
176
+ if (!result.ok) {
177
+ setEditorError(result.error);
178
+ return;
179
+ }
180
+ setEditingId(result.record.id);
181
+ if (!onSyncCollection) {
182
+ setEditorError(t("blueprint.apiCollection.syncUnavailable"));
183
+ return;
184
+ }
185
+ const syncResult = await onSyncCollection(result.record);
186
+ window.alert(formatSyncResultMessage(t, syncResult));
187
+ } catch (err) {
188
+ setEditorError(err instanceof Error ? err.message : String(err));
189
+ } finally {
190
+ setBusy(false);
191
+ }
192
+ };
193
+
194
+ const handleFiles = async (files: FileList | null) => {
195
+ if (!files || files.length === 0) return;
196
+ const list = Array.from(files);
197
+ setBusy(true);
198
+ setError(null);
199
+ onUploadStart?.({
200
+ fileNames: list.map((file) => file.name),
201
+ count: list.length,
202
+ });
203
+
204
+ const uploaded: ApiCollectionUploadSuccessInfo["collections"] = [];
205
+ const errors: string[] = [];
206
+
207
+ try {
208
+ for (const file of list) {
209
+ const text = await file.text();
210
+ const result = await upsertApiCollectionFromJson({
211
+ rawJson: text,
212
+ persistLocal: persistLocalDefault,
213
+ fallbackName: file.name,
214
+ });
215
+ if (!result.ok) {
216
+ errors.push(`${file.name}: ${result.error}`);
217
+ continue;
218
+ }
219
+ uploaded.push({
220
+ id: result.record.id,
221
+ name: result.record.name,
222
+ apiCount: result.record.document.apis.length,
223
+ persistLocal: result.record.persistLocal,
224
+ });
225
+ }
226
+ if (uploaded.length > 0) {
227
+ onUploadSuccess?.({ collections: uploaded });
228
+ }
229
+ if (errors.length > 0) {
230
+ setError(errors.join("\n"));
231
+ }
232
+ } catch (err) {
233
+ setError(err instanceof Error ? err.message : String(err));
234
+ } finally {
235
+ setBusy(false);
236
+ if (fileInputRef.current) fileInputRef.current.value = "";
237
+ }
238
+ };
239
+
240
+ return (
241
+ <>
242
+ <Dialog open={open} onOpenChange={onOpenChange}>
243
+ <DialogContent className="flex max-h-[90vh] w-[min(96vw,960px)] flex-col sm:max-w-[960px]">
244
+ <DialogHeader>
245
+ <DialogTitle>{t("blueprint.apiCollection.managerTitle")}</DialogTitle>
246
+ <DialogDescription>
247
+ {t("blueprint.apiCollection.managerDescription")}
248
+ </DialogDescription>
249
+ </DialogHeader>
250
+
251
+ <div className="flex flex-wrap items-center gap-2 border-b border-border/60 pb-3">
252
+ <Button
253
+ type="button"
254
+ size="sm"
255
+ disabled={busy}
256
+ onClick={() => fileInputRef.current?.click()}
257
+ >
258
+ {t("blueprint.apiCollection.upload")}
259
+ </Button>
260
+ <Button
261
+ type="button"
262
+ size="sm"
263
+ variant="outline"
264
+ disabled={busy}
265
+ onClick={openCreateEditor}
266
+ >
267
+ {t("blueprint.apiCollection.create")}
268
+ </Button>
269
+ <Button
270
+ type="button"
271
+ size="sm"
272
+ variant="outline"
273
+ onClick={() => downloadApiCollectionTemplate()}
274
+ >
275
+ {t("blueprint.apiCollection.downloadTemplate")}
276
+ </Button>
277
+ <label className="ml-auto flex cursor-pointer items-center gap-2 text-[11px] text-muted-foreground">
278
+ <input
279
+ type="checkbox"
280
+ className="h-3.5 w-3.5 rounded border border-input"
281
+ checked={persistLocalDefault}
282
+ onChange={(e) => setPersistLocalDefault(e.target.checked)}
283
+ />
284
+ {t("blueprint.apiCollection.persistLocal")}
285
+ </label>
286
+ <input
287
+ ref={fileInputRef}
288
+ type="file"
289
+ accept="application/json,.json"
290
+ multiple
291
+ className="hidden"
292
+ onChange={(e) => void handleFiles(e.target.files)}
293
+ />
294
+ </div>
295
+
296
+ <p className="text-[11px] text-muted-foreground">
297
+ {t("blueprint.apiCollection.persistLocalHint")}
298
+ </p>
299
+
300
+ {error ? (
301
+ <pre className="max-h-24 overflow-auto whitespace-pre-wrap rounded border border-destructive/40 bg-destructive/5 p-2 text-[11px] text-destructive">
302
+ {error}
303
+ </pre>
304
+ ) : null}
305
+
306
+ <div className="min-h-0 flex-1 space-y-2 overflow-auto py-1">
307
+ {sorted.length === 0 ? (
308
+ <p className="py-8 text-center text-xs text-muted-foreground">
309
+ {t("blueprint.apiCollection.empty")}
310
+ </p>
311
+ ) : (
312
+ sorted.map((record) => (
313
+ <div
314
+ key={record.id}
315
+ className="flex items-start gap-2 rounded-md border border-border/70 bg-muted/20 px-2.5 py-2"
316
+ >
317
+ <div className="min-w-0 flex-1">
318
+ <div className="truncate text-xs font-medium text-foreground">
319
+ {record.name}
320
+ </div>
321
+ <div className="mt-0.5 flex flex-wrap gap-x-2 text-[10px] text-muted-foreground">
322
+ <span>
323
+ {t("blueprint.apiCollection.apiCount", {
324
+ count: record.document.apis.length,
325
+ })}
326
+ </span>
327
+ <span>
328
+ {record.persistLocal
329
+ ? t("blueprint.apiCollection.persisted")
330
+ : t("blueprint.apiCollection.memoryOnly")}
331
+ </span>
332
+ </div>
333
+ </div>
334
+ <Button
335
+ type="button"
336
+ size="sm"
337
+ variant="outline"
338
+ className="h-7 shrink-0 px-2 text-[11px]"
339
+ disabled={busy || !onSyncCollection}
340
+ title={t("blueprint.apiCollection.syncHint")}
341
+ onClick={() => void handleSync(record)}
342
+ >
343
+ {t("blueprint.apiCollection.sync")}
344
+ </Button>
345
+ <Button
346
+ type="button"
347
+ size="sm"
348
+ variant="outline"
349
+ className="h-7 shrink-0 px-2 text-[11px]"
350
+ disabled={busy}
351
+ onClick={() => openEditEditor(record)}
352
+ >
353
+ {t("common.edit")}
354
+ </Button>
355
+ <Button
356
+ type="button"
357
+ size="sm"
358
+ variant="outline"
359
+ className="h-7 shrink-0 px-2 text-[11px] text-destructive hover:bg-destructive/10"
360
+ disabled={busy}
361
+ onClick={() => void handleDelete(record.id)}
362
+ >
363
+ {t("common.delete")}
364
+ </Button>
365
+ </div>
366
+ ))
367
+ )}
368
+ </div>
369
+
370
+ <DialogFooter>
371
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
372
+ {t("common.close")}
373
+ </Button>
374
+ </DialogFooter>
375
+ </DialogContent>
376
+ </Dialog>
377
+
378
+ <Dialog open={editorOpen} onOpenChange={setEditorOpen}>
379
+ <DialogContent className="flex max-h-[90vh] w-[min(96vw,1100px)] flex-col sm:max-w-[1100px]">
380
+ <DialogHeader>
381
+ <DialogTitle>
382
+ {editingId
383
+ ? t("blueprint.apiCollection.editTitle")
384
+ : t("blueprint.apiCollection.createTitle")}
385
+ </DialogTitle>
386
+ <DialogDescription>
387
+ {t("blueprint.apiCollection.editorDescription")}
388
+ </DialogDescription>
389
+ </DialogHeader>
390
+
391
+ <div className="space-y-2">
392
+ <div className="flex items-center justify-between gap-2">
393
+ <Label className="text-xs">
394
+ {t("blueprint.apiCollection.jsonEditor")}
395
+ </Label>
396
+ <label className="flex cursor-pointer items-center gap-2 text-[11px] text-muted-foreground">
397
+ <input
398
+ type="checkbox"
399
+ className="h-3.5 w-3.5 rounded border border-input"
400
+ checked={editorPersistLocal}
401
+ onChange={(e) => setEditorPersistLocal(e.target.checked)}
402
+ />
403
+ {t("blueprint.apiCollection.persistLocal")}
404
+ </label>
405
+ </div>
406
+ <Textarea
407
+ value={editorJson}
408
+ onChange={(e) => setEditorJson(e.target.value)}
409
+ className={cn(
410
+ "min-h-[min(62vh,640px)] flex-1 font-mono text-[12px] leading-relaxed",
411
+ editorError && "border-destructive"
412
+ )}
413
+ spellCheck={false}
414
+ />
415
+ {editorError ? (
416
+ <p className="text-[11px] text-destructive">{editorError}</p>
417
+ ) : null}
418
+ </div>
419
+
420
+ <DialogFooter>
421
+ <Button
422
+ type="button"
423
+ variant="outline"
424
+ onClick={() => downloadApiCollectionTemplate()}
425
+ >
426
+ {t("blueprint.apiCollection.downloadTemplate")}
427
+ </Button>
428
+ <Button
429
+ type="button"
430
+ variant="outline"
431
+ disabled={busy || !onSyncCollection}
432
+ title={t("blueprint.apiCollection.syncHint")}
433
+ onClick={() => void handleSyncFromEditor()}
434
+ >
435
+ {t("blueprint.apiCollection.sync")}
436
+ </Button>
437
+ <Button type="button" variant="outline" onClick={() => setEditorOpen(false)}>
438
+ {t("common.cancel")}
439
+ </Button>
440
+ <Button type="button" disabled={busy} onClick={() => void handleSaveEditor()}>
441
+ {t("common.save")}
442
+ </Button>
443
+ </DialogFooter>
444
+ </DialogContent>
445
+ </Dialog>
446
+ </>
447
+ );
448
+ }