@mgamadeus/ddd-clouddrive 0.0.0-stage → 0.1.0-rc.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,791 @@
1
+ 'use client';
2
+
3
+ // src/screen/CloudDriveScreen.tsx
4
+ import { useCallback, useEffect, useMemo as useMemo3, useState as useState3 } from "react";
5
+ import { FileManager } from "@mgamadeus/ddd-admin-ui/files";
6
+ import { useTranslate as useTranslate2 } from "@mgamadeus/ddd-admin-ui/i18n";
7
+ import { useMemoryUrlState } from "@mgamadeus/ddd-admin-ui/logic";
8
+ import { PageHeader } from "@mgamadeus/ddd-admin-ui/page";
9
+ import { Card, CardContent } from "@mgamadeus/ddd-admin-ui/primitives";
10
+ import { Skeleton } from "@mgamadeus/ddd-admin-ui/primitives";
11
+
12
+ // src/screen/CloudDriveSpacePicker.tsx
13
+ import { Check, ChevronsUpDown, HardDrive } from "lucide-react";
14
+ import { useMemo, useState } from "react";
15
+ import { formatBytes } from "@mgamadeus/ddd-admin-ui/files";
16
+ import { useTranslate } from "@mgamadeus/ddd-admin-ui/i18n";
17
+ import { Button } from "@mgamadeus/ddd-admin-ui/primitives";
18
+ import { cn } from "@mgamadeus/ddd-admin-ui/primitives";
19
+ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@mgamadeus/ddd-admin-ui/primitives";
20
+ import { Popover, PopoverContent, PopoverTrigger } from "@mgamadeus/ddd-admin-ui/primitives";
21
+
22
+ // src/screen/driveFileMapping.ts
23
+ import { m, translateText } from "@mgamadeus/ddd-admin-ui/i18n";
24
+ import {
25
+ fileFamilyOfContentType,
26
+ fileFamilyOfExtension
27
+ } from "@mgamadeus/ddd-admin-ui/files";
28
+ var DRIVE_LIST_PAGE_SIZE = 100;
29
+ var DRIVE_LIST_MAX_LIMIT = 1e3;
30
+ var DRIVE_EMPTY_TRASH_MAX_CALLS = 200;
31
+ var DRIVE_FAMILIES = ["PDF", "SPREADSHEET", "DOCUMENT", "PRESENTATION", "TEXT", "IMAGE", "VECTOR", "VIDEO", "ARCHIVE"];
32
+ var DRIVE_EVENT_LABELS = {
33
+ READ_BY_AGENT: m("Read by the agent"),
34
+ VIEWED: m("Viewed", { context: "file-event" }),
35
+ DOWNLOADED: m("Downloaded", { context: "file-event" })
36
+ };
37
+ var driveScanStatusOf = (scanStatus) => {
38
+ switch (scanStatus) {
39
+ case "CLEAN":
40
+ case "PENDING":
41
+ case "UPLOADING":
42
+ case "INFECTED":
43
+ case "BLOCKED":
44
+ case "FAILED":
45
+ return scanStatus;
46
+ case "PURGING":
47
+ return "FAILED";
48
+ default:
49
+ return "PENDING";
50
+ }
51
+ };
52
+ var driveFamilyOf = (item) => {
53
+ if (item.family && DRIVE_FAMILIES.includes(item.family)) return item.family;
54
+ const extension = (item.extension ?? "") || extensionOfName(item.name);
55
+ const byExtension = fileFamilyOfExtension(extension);
56
+ if (byExtension !== "OTHER") return byExtension;
57
+ return fileFamilyOfContentType(item.contentType) ?? "OTHER";
58
+ };
59
+ var extensionOfName = (name) => {
60
+ const dot = name.lastIndexOf(".");
61
+ return dot > 0 && dot < name.length - 1 ? name.slice(dot + 1).toLowerCase() : "";
62
+ };
63
+ var driveFolderIdOf = (parentNodeId, rootNodeId) => parentNodeId === null || parentNodeId === void 0 || parentNodeId === rootNodeId ? null : parentNodeId;
64
+ var driveFileViewOf = (item, rootNodeId) => ({
65
+ id: item.id,
66
+ areaKey: item.driveSpaceId,
67
+ folderId: driveFolderIdOf(item.parentNodeId, rootNodeId),
68
+ name: item.name,
69
+ extension: (item.extension ?? "") || extensionOfName(item.name),
70
+ family: driveFamilyOf(item),
71
+ mimeType: item.contentType ?? null,
72
+ sizeBytes: item.sizeBytes ?? 0,
73
+ contentVersion: item.versionNumber ?? null,
74
+ description: item.description ?? null,
75
+ scanStatus: item.scanStatus ? driveScanStatusOf(item.scanStatus) : "UPLOADING",
76
+ hasPendingVersion: item.hasPendingVersion === true,
77
+ newestVersionStatus: item.latestVersionScanStatus ? driveScanStatusOf(item.latestVersionScanStatus) : null,
78
+ newestVersionNumber: item.latestVersionNumber ?? null,
79
+ newestVersionReason: item.latestVersionStateReason ?? null,
80
+ hasWorkingCopyChanges: item.hasWorkingCopyChanges === true,
81
+ thumbnailUrl: item.thumbnailUrl ?? null,
82
+ uploadedBy: item.createdByName ?? null,
83
+ uploadedOnBehalfOf: item.createdOnBehalfOfName ?? null,
84
+ createdAt: item.createdAt ?? null,
85
+ updatedAt: item.updatedAt ?? null,
86
+ deletedAt: item.trashedAt ?? null,
87
+ deletedBy: item.trashedByName ?? null,
88
+ purgeAfter: item.purgeAfter ?? null,
89
+ ...item.nodeType === "FOLDER" ? { isFolder: true } : {}
90
+ });
91
+ var driveFolderViewsOf = (items, rootNodeId) => items.filter((item) => item.nodeType === "FOLDER" && item.parentNodeId !== null && item.parentNodeId !== void 0 && item.id !== rootNodeId).map((item) => ({
92
+ id: item.id,
93
+ areaKey: item.driveSpaceId,
94
+ parentId: driveFolderIdOf(item.parentNodeId, rootNodeId),
95
+ name: item.name,
96
+ entryCount: item.childCount ?? null,
97
+ createdBy: item.createdByName ?? null,
98
+ createdOnBehalfOf: item.createdOnBehalfOfName ?? null,
99
+ createdAt: item.createdAt ?? null,
100
+ updatedAt: item.updatedAt ?? null
101
+ }));
102
+ var DRIVE_VERSION_NOTE_CODES = {
103
+ RESTORED_FROM_VERSION: "RESTORED_FROM_VERSION",
104
+ TRANSFERRED_FROM_SPACE: "MOVED_FROM_AREA",
105
+ COPIED_FROM_PATH: "COPIED_FROM_PATH"
106
+ };
107
+ var driveVersionNoteOf = (item) => {
108
+ const code = item.commentCode ? DRIVE_VERSION_NOTE_CODES[item.commentCode] : void 0;
109
+ if (!code) return null;
110
+ return {
111
+ code,
112
+ versionNumber: item.commentParameters?.versionNumber ?? null,
113
+ sourceAreaName: item.commentParameters?.sourceSpaceDisplayName ?? null,
114
+ sourcePath: item.commentParameters?.sourcePath ?? null
115
+ };
116
+ };
117
+ var driveVersionViewOf = (item) => ({
118
+ id: item.id,
119
+ versionNumber: item.versionNumber,
120
+ sizeBytes: item.sizeBytes ?? 0,
121
+ scanStatus: driveScanStatusOf(item.scanStatus),
122
+ scanResultDetail: item.scanDetail ?? null,
123
+ isCurrent: item.isCurrent,
124
+ uploadedBy: item.authorName ?? null,
125
+ uploadedOnBehalfOf: item.onBehalfOfName ?? null,
126
+ createdAt: item.createdAt ?? null,
127
+ comment: item.comment ?? null,
128
+ systemNote: driveVersionNoteOf(item)
129
+ });
130
+ var driveEventViewOf = (item) => ({
131
+ id: item.eventSource ? `${item.eventSource}-${item.id}` : item.id,
132
+ type: item.eventType,
133
+ occurredAt: item.occurredAt ?? null,
134
+ actor: item.actorName ?? null,
135
+ impersonatedBy: item.onBehalfOfName ?? null,
136
+ detail: item.previousPath && item.path && item.previousPath !== item.path ? `${item.previousPath} \u2192 ${item.path}` : item.detail ?? null,
137
+ audience: item.audience ?? null,
138
+ variant: item.contentVariant ?? null,
139
+ clientIp: item.clientIp ?? null
140
+ });
141
+ var driveLocationResolutionOf = (response) => {
142
+ const item = response.item ?? null;
143
+ const rootNodeId = response.ancestors?.elements?.[0]?.id ?? (item && (item.parentNodeId === null || item.parentNodeId === void 0) ? item.id : null);
144
+ const isFile = item !== null && item.nodeType === "FILE";
145
+ const folderId = item === null ? null : isFile ? driveFolderIdOf(item.parentNodeId, rootNodeId) : item.id === rootNodeId ? null : item.id;
146
+ return {
147
+ found: true,
148
+ areaKey: response.driveSpaceId,
149
+ folderId,
150
+ fileId: isFile && item ? item.id : null,
151
+ path: `/${response.path.replace(/^\/+/, "")}`
152
+ };
153
+ };
154
+ var driveLocationMissOf = (error) => {
155
+ const failure = error;
156
+ if (!failure || failure.status !== 404) return null;
157
+ const body = failure.data ?? {};
158
+ const deepest = body.deepestFolder ?? null;
159
+ return {
160
+ found: false,
161
+ deepestFolderPath: deepest ? deepest.parentNodeId === null || deepest.parentNodeId === void 0 ? "/" : deepest.name : null,
162
+ missingSegment: body.missingSegment ?? null,
163
+ message: body.error ?? null
164
+ };
165
+ };
166
+ var DRIVE_USAGE_PART_LABELS = {
167
+ currentVersionBytes: m("Current versions"),
168
+ olderVersionBytes: m("Older versions"),
169
+ trashedBytes: m("Trash", { context: "drive-usage" }),
170
+ pendingBytes: m("Uploads being checked")
171
+ };
172
+ var driveUsagePartsOf = (quota) => {
173
+ const parts = [];
174
+ for (const key of Object.keys(DRIVE_USAGE_PART_LABELS)) {
175
+ const bytes = quota[key];
176
+ if (typeof bytes === "number") parts.push({ label: translateText(DRIVE_USAGE_PART_LABELS[key], key === "trashedBytes" ? { context: "drive-usage" } : {}), bytes });
177
+ }
178
+ return parts.length > 0 ? parts : null;
179
+ };
180
+ var effectiveQuotaOf = (quota) => {
181
+ const quotaBytes = quota.effectiveQuotaBytes ?? quota.quotaBytes;
182
+ return typeof quotaBytes === "number" && quotaBytes > 0 ? quotaBytes : null;
183
+ };
184
+ var driveAreaViewOf = (item) => ({
185
+ areaKey: item.id,
186
+ isEnabled: true,
187
+ quotaBytes: effectiveQuotaOf(item.quota),
188
+ usedBytes: item.quota.usedBytes,
189
+ maxFileSizeBytes: item.quota.maxFileSizeBytes > 0 ? item.quota.maxFileSizeBytes : null,
190
+ trashRetentionDays: item.quota.trashRetentionDays > 0 ? item.quota.trashRetentionDays : null,
191
+ fileCount: item.quota.fileCount,
192
+ folderCount: item.quota.folderCount,
193
+ usageParts: driveUsagePartsOf(item.quota)
194
+ });
195
+ var driveAreaRefOf = (item) => ({
196
+ key: item.id,
197
+ name: item.displayName || item.title || `#${item.id}`,
198
+ // `groupLabel` is the translated heading; `displayGroup` is an ordering code (`LIBRARY`), shown only without a label.
199
+ groupLabel: item.groupLabel ?? item.displayGroup ?? null
200
+ });
201
+ var DRIVE_ORDERS = ["name", "created", "size"];
202
+ var driveChildrenArgOf = (query, rootNodeId, limit) => {
203
+ const q = query.q?.trim() ?? "";
204
+ const isFolderView = query.folderId !== void 0 && q === "";
205
+ const folderNodeId = !isFolderView ? null : query.folderId === "root" ? rootNodeId ?? null : Number(query.folderId);
206
+ return {
207
+ driveSpaceId: Number(query.areaKey),
208
+ folderNodeId: folderNodeId ?? void 0,
209
+ recursive: isFolderView ? void 0 : true,
210
+ query: q === "" ? void 0 : q,
211
+ family: query.family && DRIVE_FAMILIES.includes(query.family) ? query.family : void 0,
212
+ createdFrom: query.createdFrom || void 0,
213
+ createdTo: query.createdTo || void 0,
214
+ createdByMe: query.uploadedByMe ? true : void 0,
215
+ orderBy: query.orderBy && DRIVE_ORDERS.includes(query.orderBy) ? query.orderBy : void 0,
216
+ orderDirection: query.orderDirection,
217
+ limit,
218
+ includeSystem: false
219
+ };
220
+ };
221
+ var driveFileItemsOf = (items) => (items ?? []).filter((item) => item.nodeType === "FILE" && item.isSystem !== true);
222
+ var nextDriveListLimit = (limit) => limit >= DRIVE_LIST_MAX_LIMIT ? null : Math.min(DRIVE_LIST_MAX_LIMIT, limit + DRIVE_LIST_PAGE_SIZE);
223
+ var emptyDriveTrashFully = async (emptyOnce, maxCalls = DRIVE_EMPTY_TRASH_MAX_CALLS) => {
224
+ const outcome = { calls: 0, processedCount: 0, fileCount: 0, folderCount: 0, hasMore: false };
225
+ for (; ; ) {
226
+ const result = await emptyOnce();
227
+ outcome.calls += 1;
228
+ outcome.processedCount += result.processedCount;
229
+ outcome.fileCount += result.fileCount;
230
+ outcome.folderCount += result.folderCount;
231
+ outcome.hasMore = result.hasMore;
232
+ if (!result.hasMore || result.processedCount === 0 || outcome.calls >= maxCalls) return outcome;
233
+ }
234
+ };
235
+ var groupDriveSpaces = (areas) => {
236
+ const groups = /* @__PURE__ */ new Map();
237
+ for (const area of areas) {
238
+ const label = area.groupLabel ?? "";
239
+ const group = groups.get(label);
240
+ if (group) group.push(area);
241
+ else groups.set(label, [area]);
242
+ }
243
+ return [...groups.entries()].map(([label, groupAreas]) => ({ label, areas: groupAreas }));
244
+ };
245
+
246
+ // src/screen/CloudDriveSpacePicker.tsx
247
+ import { jsx, jsxs } from "react/jsx-runtime";
248
+ var CloudDriveSpacePicker = ({ areas, areaKey, onSelectArea, spaces, className }) => {
249
+ const { t } = useTranslate();
250
+ const [open, setOpen] = useState(false);
251
+ const groups = useMemo(() => groupDriveSpaces(areas), [areas]);
252
+ const current = areas.find((area) => String(area.key) === String(areaKey));
253
+ const detailOf = (key) => {
254
+ const space = spaces?.find((item) => String(item.id) === String(key));
255
+ if (!space) return null;
256
+ return `${t("{count, plural, one {# file} other {# files}}", { count: space.quota.fileCount })} \xB7 ${formatBytes(space.quota.usedBytes)}`;
257
+ };
258
+ return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
259
+ /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(Button, { variant: "outline", role: "combobox", "aria-expanded": open, className: cn("w-full max-w-sm justify-between gap-2", className), children: [
260
+ /* @__PURE__ */ jsxs("span", { className: "flex min-w-0 items-center gap-2", children: [
261
+ /* @__PURE__ */ jsx(HardDrive, { className: "size-4 shrink-0 text-muted-foreground", "aria-hidden": true }),
262
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: current?.name ?? t("Choose a space") }),
263
+ current?.groupLabel && /* @__PURE__ */ jsxs("span", { className: "truncate text-xs text-muted-foreground", children: [
264
+ "\xB7 ",
265
+ current.groupLabel
266
+ ] })
267
+ ] }),
268
+ /* @__PURE__ */ jsx(ChevronsUpDown, { className: "size-4 shrink-0 opacity-50", "aria-hidden": true })
269
+ ] }) }),
270
+ /* @__PURE__ */ jsx(PopoverContent, { className: "w-(--radix-popover-trigger-width) min-w-72 p-0", align: "start", children: /* @__PURE__ */ jsxs(Command, { children: [
271
+ /* @__PURE__ */ jsx(CommandInput, { placeholder: t("Search spaces\u2026") }),
272
+ /* @__PURE__ */ jsxs(CommandList, { children: [
273
+ /* @__PURE__ */ jsx(CommandEmpty, { children: t("No space matches.") }),
274
+ groups.map((group) => /* @__PURE__ */ jsx(CommandGroup, { heading: group.label || void 0, children: group.areas.map((area) => /* @__PURE__ */ jsxs(
275
+ CommandItem,
276
+ {
277
+ value: `${area.name} ${area.groupLabel ?? ""} ${String(area.key)}`,
278
+ onSelect: () => {
279
+ onSelectArea(area.key);
280
+ setOpen(false);
281
+ },
282
+ children: [
283
+ /* @__PURE__ */ jsx(Check, { className: cn("size-4 shrink-0", String(area.key) === String(areaKey) ? "opacity-100" : "opacity-0"), "aria-hidden": true }),
284
+ /* @__PURE__ */ jsxs("span", { className: "flex min-w-0 flex-col", children: [
285
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: area.name }),
286
+ detailOf(area.key) && /* @__PURE__ */ jsx("span", { className: "truncate text-xs text-muted-foreground tabular-nums", children: detailOf(area.key) })
287
+ ] })
288
+ ]
289
+ },
290
+ String(area.key)
291
+ )) }, group.label || "__ungrouped__"))
292
+ ] })
293
+ ] }) })
294
+ ] });
295
+ };
296
+
297
+ // src/screen/useCloudDriveFileAdapter.ts
298
+ import { useMemo as useMemo2, useState as useState2 } from "react";
299
+ import { translateText as translateText3 } from "@mgamadeus/ddd-admin-ui/i18n";
300
+
301
+ // src/screen/driveFileActions.ts
302
+ import { translateText as translateText2 } from "@mgamadeus/ddd-admin-ui/i18n";
303
+
304
+ // src/screen/upload.ts
305
+ var sendRequest = async (request, body, signal) => {
306
+ const response = await fetch(request.url, { method: request.method, headers: request.headers ?? {}, body, signal });
307
+ if (!response.ok) {
308
+ throw new Error(`Upload refused by the store (${response.status})`);
309
+ }
310
+ };
311
+ var sendDriveUpload = async (reservation, file, onProgress, signal) => {
312
+ if (reservation.isContentKnown) {
313
+ onProgress?.(file.size, file.size);
314
+ return;
315
+ }
316
+ if (!reservation.isMultipart) {
317
+ if (!reservation.uploadRequest) throw new Error("The reservation has no upload request");
318
+ await sendRequest(reservation.uploadRequest, file, signal);
319
+ onProgress?.(file.size, file.size);
320
+ return;
321
+ }
322
+ const partSize = reservation.partSizeBytes ?? 0;
323
+ let sentBytes = 0;
324
+ for (const part of reservation.partRequests?.elements ?? []) {
325
+ const start = (part.partNumber - 1) * partSize;
326
+ const chunk = file.slice(start, Math.min(file.size, start + partSize));
327
+ await sendRequest(part.request, chunk, signal);
328
+ sentBytes += chunk.size;
329
+ onProgress?.(sentBytes, file.size);
330
+ }
331
+ };
332
+ var formatDriveSize = (sizeBytes) => {
333
+ if (sizeBytes === null || sizeBytes === void 0) return "";
334
+ if (sizeBytes < 1024) return `${sizeBytes} B`;
335
+ if (sizeBytes < 1024 * 1024) return `${(sizeBytes / 1024).toFixed(1)} KB`;
336
+ if (sizeBytes < 1024 * 1024 * 1024) return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
337
+ return `${(sizeBytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
338
+ };
339
+ var parseDriveTime = (value) => {
340
+ if (!value) return null;
341
+ const isoValue = value.includes("T") ? value : value.replace(" ", "T");
342
+ const date = new Date(/(Z|[+-]\d{2}:?\d{2})$/.test(isoValue) ? isoValue : `${isoValue}Z`);
343
+ return Number.isNaN(date.getTime()) ? null : date;
344
+ };
345
+
346
+ // src/screen/driveFileActions.ts
347
+ var toSpaceId = (areaKey) => {
348
+ const spaceId = Number(areaKey);
349
+ return Number.isInteger(spaceId) && spaceId > 0 ? spaceId : 0;
350
+ };
351
+ var toNodeIds = (ids) => ids.map((id) => Number(id)).filter((id) => Number.isInteger(id) && id > 0);
352
+ var rememberDriveNodes = (nodeFacts, items) => {
353
+ for (const item of items) nodeFacts.set(item.id, { parentNodeId: item.parentNodeId ?? null, name: item.name });
354
+ };
355
+ var drivePurposeOf = (options) => options.variant === "THUMBNAIL" ? "THUMBNAIL" : options.variant === "PREVIEW" || options.variant === void 0 && options.disposition === "inline" ? "INLINE" : "DOWNLOAD";
356
+ var buildCloudDriveFileActions = (triggers, context) => {
357
+ const { reserveUpload, completeUpload, requestContent, moveNode, updateMetadata, createFolder, moveNodes, trashNodes, restoreNodes, purgeNodes, emptyTrash, restoreVersion } = triggers;
358
+ const { spaceId, rootNodeId, canManage, nodeFacts } = context;
359
+ const rememberNodes = (items) => rememberDriveNodes(nodeFacts, items);
360
+ const folderNodeIdOf = (folderId) => folderId === null ? rootNodeId : Number(folderId);
361
+ const fileViewOfResponse = (response) => {
362
+ if (response.isConflict) {
363
+ throw new Error(translateText2("A file with this name exists already in this folder."));
364
+ }
365
+ const item = response.item;
366
+ if (!item) throw new Error(translateText2("The drive answered without the file."));
367
+ rememberNodes([item]);
368
+ return driveFileViewOf(item, rootNodeId);
369
+ };
370
+ const uploadInto = async (driveSpaceId, folderNodeId, file, callbacks, options) => {
371
+ const { reservation } = await reserveUpload({ driveSpaceId, sizeBytes: file.size, contentType: file.type || null }).unwrap();
372
+ await sendDriveUpload(reservation, file, (sent, total) => callbacks.onProgress?.(sent, total), callbacks.signal);
373
+ const response = await completeUpload({
374
+ driveBlobId: reservation.driveBlobId,
375
+ folderNodeId,
376
+ name: file.name,
377
+ comment: options.comment ?? null,
378
+ replaceExisting: options.replaceExisting ?? false
379
+ }).unwrap();
380
+ return fileViewOfResponse(response);
381
+ };
382
+ const actions = {
383
+ upload: (input, callbacks) => uploadInto(toSpaceId(input.areaKey), folderNodeIdOf(input.folderId), input.file, callbacks, { comment: input.description }),
384
+ uploadVersion: async (fileId, file, callbacks) => {
385
+ const fact = nodeFacts.get(Number(fileId));
386
+ if (!fact) throw new Error(translateText2("Open the file again and retry."));
387
+ return uploadInto(spaceId, fact.parentNodeId, new File([file], fact.name, { type: file.type }), callbacks, { replaceExisting: true });
388
+ },
389
+ getDownload: async (fileId, options) => {
390
+ const { grant } = await requestContent({
391
+ driveNodeId: Number(fileId),
392
+ purpose: drivePurposeOf(options),
393
+ versionId: options.versionId === void 0 ? null : Number(options.versionId)
394
+ }).unwrap();
395
+ return { url: grant.url, fileName: grant.fileName, expiresAt: grant.expiresAt ?? null };
396
+ },
397
+ patchFile: async (fileId, patch) => {
398
+ const driveNodeId = Number(fileId);
399
+ if (patch.name !== void 0 || patch.folderId !== void 0) {
400
+ await moveNode({
401
+ driveNodeId,
402
+ targetFolderNodeId: patch.folderId === void 0 ? null : folderNodeIdOf(patch.folderId),
403
+ name: patch.name ?? null
404
+ }).unwrap();
405
+ }
406
+ if (patch.description !== void 0) {
407
+ await updateMetadata({ driveNodeId, description: patch.description }).unwrap();
408
+ }
409
+ },
410
+ moveFiles: async (fileIds, folderId) => (await moveNodes({ driveSpaceId: spaceId, driveNodeIds: toNodeIds(fileIds), targetFolderNodeId: folderNodeIdOf(folderId) }).unwrap()).result,
411
+ trashFiles: async (fileIds) => (await trashNodes({ driveSpaceId: spaceId, driveNodeIds: toNodeIds(fileIds) }).unwrap()).result,
412
+ restoreFiles: async (fileIds) => (await restoreNodes({ driveSpaceId: spaceId, driveNodeIds: toNodeIds(fileIds) }).unwrap()).result,
413
+ createFolder: async (input) => {
414
+ const response = await createFolder({
415
+ driveSpaceId: toSpaceId(input.areaKey),
416
+ parentNodeId: input.parentFolderId === null ? null : Number(input.parentFolderId),
417
+ name: input.name
418
+ }).unwrap();
419
+ const node = response.item ?? null;
420
+ return {
421
+ id: node?.id ?? response.driveNode.id,
422
+ areaKey: toSpaceId(input.areaKey),
423
+ parentId: driveFolderIdOf(node?.parentNodeId ?? response.driveNode.parentNodeId, rootNodeId),
424
+ name: node?.name ?? response.driveNode.name,
425
+ fileCount: 0
426
+ };
427
+ },
428
+ patchFolder: async (folderId, patch) => {
429
+ await moveNode({
430
+ driveNodeId: Number(folderId),
431
+ targetFolderNodeId: patch.parentFolderId === void 0 ? null : folderNodeIdOf(patch.parentFolderId),
432
+ name: patch.name ?? null
433
+ }).unwrap();
434
+ },
435
+ deleteFolder: async (folderId) => {
436
+ const { result } = await trashNodes({ driveSpaceId: spaceId, driveNodeIds: toNodeIds([folderId]) }).unwrap();
437
+ return { trashedFiles: result.fileCount, deletedFolders: result.folderCount };
438
+ },
439
+ restoreVersion: async (fileId, versionId) => restoreVersion({ driveNodeId: Number(fileId), driveFileVersionId: Number(versionId) }).unwrap()
440
+ };
441
+ if (canManage) {
442
+ actions.purgeFiles = async (fileIds) => (await purgeNodes({ driveSpaceId: spaceId, driveNodeIds: toNodeIds(fileIds) }).unwrap()).result;
443
+ actions.emptyTrash = async (areaKey) => emptyDriveTrashFully(async () => (await emptyTrash({ driveSpaceId: toSpaceId(areaKey) }).unwrap()).result);
444
+ }
445
+ return actions;
446
+ };
447
+
448
+ // src/screen/useCloudDriveFileAdapter.ts
449
+ var DRIVE_ACTIVITY_LIMIT = 20;
450
+ var CLOUD_DRIVE_FILE_CAPABILITIES = {
451
+ versions: { replacementExtension: "same" },
452
+ activity: { limit: DRIVE_ACTIVITY_LIMIT },
453
+ filters: { family: true, created: true, uploadedByMe: true, orders: ["name", "created", "size"] },
454
+ workingCopy: {},
455
+ malwareScan: { enabled: true }
456
+ };
457
+ var EMPTY_LIST = { items: [], isLoading: false, isFetchingMore: false, hasMore: false, loadMore: () => void 0, isError: false };
458
+ var toSpaceId2 = (areaKey) => {
459
+ const spaceId = Number(areaKey);
460
+ return Number.isInteger(spaceId) && spaceId > 0 ? spaceId : 0;
461
+ };
462
+ var useGrowingLimit = (key) => {
463
+ const [state, setState] = useState2({ key, limit: DRIVE_LIST_PAGE_SIZE });
464
+ const limit = state.key === key ? state.limit : DRIVE_LIST_PAGE_SIZE;
465
+ return [limit, (next) => setState({ key, limit: next })];
466
+ };
467
+ var createCloudDriveFileAdapter = (api, spaceId) => {
468
+ const nodeFacts = /* @__PURE__ */ new Map();
469
+ let resolveTrigger = null;
470
+ const rememberNodes = (items) => rememberDriveNodes(nodeFacts, items);
471
+ const useSpaceItem = (areaKey) => {
472
+ const driveSpaceId = toSpaceId2(areaKey);
473
+ const spaceQuery = api.useDriveSpaceQuery({ driveSpaceId }, { skip: driveSpaceId === 0 });
474
+ const loadedItem = spaceQuery.data?.item ?? void 0;
475
+ const item = loadedItem !== void 0 && loadedItem.id === driveSpaceId ? loadedItem : void 0;
476
+ return { item, isLoading: spaceQuery.isLoading || driveSpaceId !== 0 && item === void 0 && !spaceQuery.isError, isError: spaceQuery.isError };
477
+ };
478
+ const useArea = (areaKey) => {
479
+ const space = useSpaceItem(areaKey);
480
+ return { data: space.item ? driveAreaViewOf(space.item) : void 0, isLoading: space.isLoading, isError: space.isError };
481
+ };
482
+ const useFolders = (areaKey) => {
483
+ const space = useSpaceItem(areaKey);
484
+ const driveSpaceId = toSpaceId2(areaKey);
485
+ const foldersQuery = api.useDriveFoldersQuery({ driveSpaceId, includeSystem: false }, { skip: driveSpaceId === 0 });
486
+ const isStale = foldersQuery.isFetching && foldersQuery.currentData === void 0;
487
+ const foldersData = isStale ? void 0 : foldersQuery.data;
488
+ const data = useMemo2(
489
+ () => foldersData && space.item ? driveFolderViewsOf(foldersData.items.elements ?? [], space.item.rootNodeId) : void 0,
490
+ [foldersData, space.item]
491
+ );
492
+ return { data, isLoading: foldersQuery.isLoading || space.isLoading, isFetching: foldersQuery.isFetching, isError: foldersQuery.isError };
493
+ };
494
+ const useFiles = (query) => {
495
+ const space = useSpaceItem(query?.areaKey);
496
+ const [limit, setLimit] = useGrowingLimit(JSON.stringify(query));
497
+ const rootNodeId = space.item?.rootNodeId;
498
+ const skip = query === null || space.item === void 0;
499
+ const childrenQuery = api.useDriveChildrenQuery(
500
+ query && !skip ? driveChildrenArgOf(query, rootNodeId, limit) : { driveSpaceId: 0 },
501
+ { skip }
502
+ );
503
+ const items = useMemo2(() => {
504
+ const fileItems = driveFileItemsOf(childrenQuery.data?.items?.elements);
505
+ rememberNodes(fileItems);
506
+ return fileItems.map((item) => driveFileViewOf(item, rootNodeId));
507
+ }, [childrenQuery.data, rootNodeId]);
508
+ const nextLimit = nextDriveListLimit(limit);
509
+ const hasMore = Boolean(childrenQuery.data?.nextCursor) && nextLimit !== null;
510
+ if (skip) return EMPTY_LIST;
511
+ return {
512
+ items,
513
+ isLoading: childrenQuery.isLoading || space.isLoading,
514
+ isRefetching: childrenQuery.isFetching && childrenQuery.data !== void 0 && childrenQuery.currentData !== void 0,
515
+ isFetchingMore: childrenQuery.isFetching && childrenQuery.data !== void 0 && childrenQuery.currentData === void 0,
516
+ hasMore,
517
+ loadMore: () => {
518
+ if (nextLimit !== null) setLimit(nextLimit);
519
+ },
520
+ isError: childrenQuery.isError,
521
+ refetch: () => void childrenQuery.refetch()
522
+ };
523
+ };
524
+ const useTrash = (query) => {
525
+ const space = useSpaceItem(query?.areaKey);
526
+ const [limit, setLimit] = useGrowingLimit(JSON.stringify(query));
527
+ const driveSpaceId = toSpaceId2(query?.areaKey);
528
+ const skip = query === null || driveSpaceId === 0;
529
+ const trashQuery = api.useDriveTrashQuery({ driveSpaceId, limit }, { skip });
530
+ const rootNodeId = space.item?.rootNodeId;
531
+ const items = useMemo2(
532
+ () => (trashQuery.data?.items?.elements ?? []).filter((item) => item.nodeType === "FILE" || item.nodeType === "FOLDER").map((item) => driveFileViewOf(item, rootNodeId)),
533
+ [trashQuery.data, rootNodeId]
534
+ );
535
+ const nextLimit = nextDriveListLimit(limit);
536
+ if (skip) return EMPTY_LIST;
537
+ return {
538
+ items,
539
+ isLoading: trashQuery.isLoading,
540
+ isRefetching: trashQuery.isFetching && trashQuery.currentData !== void 0,
541
+ isFetchingMore: trashQuery.isFetching && trashQuery.data !== void 0 && trashQuery.currentData === void 0,
542
+ hasMore: Boolean(trashQuery.data?.nextCursor) && nextLimit !== null,
543
+ loadMore: () => {
544
+ if (nextLimit !== null) setLimit(nextLimit);
545
+ },
546
+ isError: trashQuery.isError
547
+ };
548
+ };
549
+ const useFile = (fileId, options) => {
550
+ const driveNodeId = fileId === null ? 0 : Number(fileId);
551
+ const skip = !Number.isInteger(driveNodeId) || driveNodeId <= 0;
552
+ const pollingInterval = skip ? 0 : Math.max(0, options?.pollingIntervalMs ?? 0);
553
+ const nodeQuery = api.useDriveNodeQuery({ driveNodeId }, { skip, pollingInterval });
554
+ const versionsQuery = api.useDriveVersionsQuery({ driveNodeId }, { skip, pollingInterval });
555
+ const eventsQuery = api.useDriveEventsQuery({ driveNodeId, limit: DRIVE_ACTIVITY_LIMIT, eventGroup: "changes" }, { skip });
556
+ const item = nodeQuery.data?.item ?? void 0;
557
+ const space = useSpaceItem(item?.driveSpaceId);
558
+ const data = useMemo2(() => {
559
+ if (!item || item.nodeType !== "FILE") return void 0;
560
+ rememberNodes([item]);
561
+ return {
562
+ ...driveFileViewOf(item, space.item?.rootNodeId),
563
+ sha256: nodeQuery.data?.driveNode.sha256 ?? null,
564
+ versions: versionsQuery.data?.items?.elements?.map(driveVersionViewOf),
565
+ events: eventsQuery.data?.items?.elements?.map(driveEventViewOf)
566
+ };
567
+ }, [item, nodeQuery.data, versionsQuery.data, eventsQuery.data, space.item]);
568
+ return {
569
+ data,
570
+ isLoading: nodeQuery.isLoading,
571
+ isFetching: nodeQuery.isFetching || versionsQuery.isFetching,
572
+ isError: nodeQuery.isError,
573
+ refetch: () => {
574
+ if (skip) return;
575
+ void nodeQuery.refetch();
576
+ void versionsQuery.refetch();
577
+ }
578
+ };
579
+ };
580
+ const useAccessEvents = (fileId) => {
581
+ const driveNodeId = fileId === null ? 0 : Number(fileId);
582
+ const skip = !Number.isInteger(driveNodeId) || driveNodeId <= 0;
583
+ const accessesQuery = api.useDriveEventsQuery({ driveNodeId, limit: DRIVE_ACTIVITY_LIMIT, eventGroup: "accesses" }, { skip });
584
+ const data = useMemo2(() => accessesQuery.data?.items?.elements?.map(driveEventViewOf), [accessesQuery.data]);
585
+ return { data, isLoading: accessesQuery.isLoading, isFetching: accessesQuery.isFetching, isError: accessesQuery.isError };
586
+ };
587
+ const resolveLocation = async (areaKey, input) => {
588
+ if (!resolveTrigger) throw new Error(translateText3("The location could not be opened."));
589
+ try {
590
+ return driveLocationResolutionOf(await resolveTrigger({ driveSpaceId: toSpaceId2(areaKey) || spaceId, path: input.trim() }).unwrap());
591
+ } catch (error) {
592
+ const miss = driveLocationMissOf(error);
593
+ if (miss) return miss;
594
+ throw error;
595
+ }
596
+ };
597
+ const useActions = () => {
598
+ const space = useSpaceItem(spaceId);
599
+ const [resolve] = api.useResolveDriveLocationMutation();
600
+ resolveTrigger = resolve;
601
+ const [reserveUpload] = api.useReserveDriveUploadMutation();
602
+ const [completeUpload] = api.useCompleteDriveUploadMutation();
603
+ const [requestContent] = api.useDriveContentMutation();
604
+ const [moveNode] = api.useMoveDriveNodeMutation();
605
+ const [updateMetadata] = api.useUpdateDriveNodeMetadataMutation();
606
+ const [createFolder] = api.useCreateDriveFolderMutation();
607
+ const [moveNodes] = api.useMoveDriveNodesMutation();
608
+ const [trashNodes] = api.useTrashDriveNodesMutation();
609
+ const [restoreNodes] = api.useRestoreDriveNodesMutation();
610
+ const [purgeNodes] = api.usePurgeDriveNodesMutation();
611
+ const [emptyTrash] = api.useEmptyDriveTrashMutation();
612
+ const [restoreVersion] = api.useRestoreDriveVersionMutation();
613
+ const rootNodeId = space.item?.rootNodeId ?? null;
614
+ const canManage = space.item?.canManage === true;
615
+ const triggers = {
616
+ reserveUpload,
617
+ completeUpload,
618
+ requestContent,
619
+ moveNode,
620
+ updateMetadata,
621
+ createFolder,
622
+ moveNodes,
623
+ trashNodes,
624
+ restoreNodes,
625
+ purgeNodes,
626
+ emptyTrash,
627
+ restoreVersion
628
+ };
629
+ return useMemo2(
630
+ () => buildCloudDriveFileActions(triggers, { spaceId, rootNodeId, canManage, nodeFacts }),
631
+ [canManage, rootNodeId, reserveUpload, completeUpload, requestContent, moveNode, updateMetadata, createFolder, moveNodes, trashNodes, restoreNodes, purgeNodes, emptyTrash, restoreVersion]
632
+ );
633
+ };
634
+ return {
635
+ useArea,
636
+ useFolders,
637
+ useFiles,
638
+ useFile,
639
+ useActions,
640
+ capabilities: {
641
+ ...CLOUD_DRIVE_FILE_CAPABILITIES,
642
+ trash: { useTrash },
643
+ activity: { limit: DRIVE_ACTIVITY_LIMIT, useAccessEvents },
644
+ location: { resolveLocation },
645
+ ...api.audience === "shared" ? { audience: "partner" } : {}
646
+ }
647
+ };
648
+ };
649
+ var useCloudDriveFileAdapter = ({ api, spaceId }) => useMemo2(() => createCloudDriveFileAdapter(api, spaceId), [api, spaceId]);
650
+
651
+ // src/screen/CloudDriveScreen.tsx
652
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
653
+ var CLOUD_DRIVE_URL_KEYS = { area: "space", folder: "path", order: "sort", file: "file", fileTab: "fileTab", tab: "tab" };
654
+ var CLOUD_DRIVE_NODE_KEY = "node";
655
+ var CloudDriveScreen = ({
656
+ api,
657
+ title,
658
+ description,
659
+ initialSpaceId,
660
+ initialFolderNodeId,
661
+ initialNodeId,
662
+ headerActions,
663
+ urlStateAdapter,
664
+ drawerUrlAdapter,
665
+ loadPdfJs,
666
+ renderAreaMaintenance,
667
+ renderAreaSettings,
668
+ formatEventType,
669
+ defaultView,
670
+ variant
671
+ }) => {
672
+ const { t } = useTranslate2();
673
+ const spacesQuery = api.useDriveSpacesQuery();
674
+ const spaceItems = spacesQuery.data?.items?.elements;
675
+ const areas = useMemo3(() => (spaceItems ?? []).map(driveAreaRefOf), [spaceItems]);
676
+ const memory = useMemoryUrlState();
677
+ const listUrl = urlStateAdapter ?? memory.urlStateAdapter;
678
+ const drawerUrl = drawerUrlAdapter ?? memory.drawerUrlAdapter;
679
+ const urlSpace = Number(listUrl.get(CLOUD_DRIVE_URL_KEYS.area));
680
+ const urlSpaceId = Number.isInteger(urlSpace) && urlSpace > 0 && spaceItems?.some((item) => item.id === urlSpace) ? urlSpace : null;
681
+ const initialSpace = initialSpaceId !== void 0 && spaceItems?.some((item) => item.id === initialSpaceId) ? initialSpaceId : null;
682
+ const spaceId = urlSpaceId ?? initialSpace ?? (areas[0] ? Number(areas[0].key) : null);
683
+ const spaceItem = spaceItems?.find((item) => item.id === spaceId);
684
+ const adapter = useCloudDriveFileAdapter({ api, spaceId: spaceId ?? 0 });
685
+ const isPartner = api.audience === "shared";
686
+ const urlNode = Number(listUrl.get(CLOUD_DRIVE_NODE_KEY));
687
+ const deepLinkNodeId = Number.isInteger(urlNode) && urlNode > 0 ? urlNode : initialNodeId ?? initialFolderNodeId;
688
+ const [appliedNodeId, setAppliedNodeId] = useState3(null);
689
+ const deepLinkPending = deepLinkNodeId !== void 0 && appliedNodeId !== deepLinkNodeId;
690
+ const deepLinkQuery = api.useDriveNodeQuery({ driveNodeId: deepLinkNodeId ?? 0 }, { skip: !deepLinkPending });
691
+ const deepLinkSpace = spaceItems?.find((item) => item.id === deepLinkQuery.data?.driveNode.driveSpaceId);
692
+ useEffect(() => {
693
+ if (!deepLinkPending || deepLinkNodeId === void 0) return;
694
+ if (deepLinkQuery.isError) {
695
+ setAppliedNodeId(deepLinkNodeId);
696
+ listUrl.replace({ [CLOUD_DRIVE_NODE_KEY]: null });
697
+ return;
698
+ }
699
+ if (!deepLinkQuery.data || !deepLinkSpace) return;
700
+ const { driveNode } = deepLinkQuery.data;
701
+ const isFolder = driveNode.nodeType === "FOLDER";
702
+ const folderId = isFolder ? driveFolderIdOf(driveNode.id, deepLinkSpace.rootNodeId) : driveFolderIdOf(driveNode.parentNodeId, deepLinkSpace.rootNodeId);
703
+ listUrl.replace({
704
+ [CLOUD_DRIVE_NODE_KEY]: null,
705
+ [CLOUD_DRIVE_URL_KEYS.area]: String(driveNode.driveSpaceId),
706
+ [CLOUD_DRIVE_URL_KEYS.folder]: folderId === null ? null : String(folderId)
707
+ });
708
+ if (!isFolder) drawerUrl.replace({ [CLOUD_DRIVE_URL_KEYS.file]: String(driveNode.id) });
709
+ setAppliedNodeId(deepLinkNodeId);
710
+ }, [deepLinkPending, deepLinkNodeId, deepLinkQuery.data, deepLinkQuery.isError, deepLinkSpace, listUrl, drawerUrl]);
711
+ const eventLabel = useCallback(
712
+ (type) => formatEventType?.(type) ?? (DRIVE_EVENT_LABELS[type] ? t(DRIVE_EVENT_LABELS[type]) : null),
713
+ [formatEventType, t]
714
+ );
715
+ const heading = title ?? t("Drive");
716
+ if (spacesQuery.isLoading || deepLinkPending && deepLinkQuery.isLoading) {
717
+ return /* @__PURE__ */ jsxs2("div", { className: "space-y-4", children: [
718
+ /* @__PURE__ */ jsx2(PageHeader, { title: heading, description, actions: headerActions }),
719
+ /* @__PURE__ */ jsx2(Skeleton, { className: "h-10 w-72" }),
720
+ /* @__PURE__ */ jsx2(Skeleton, { className: "h-64 w-full" })
721
+ ] });
722
+ }
723
+ if (spaceId === null || spaceItems === void 0) {
724
+ return /* @__PURE__ */ jsxs2("div", { className: "space-y-4", children: [
725
+ /* @__PURE__ */ jsx2(PageHeader, { title: heading, description, actions: headerActions }),
726
+ /* @__PURE__ */ jsx2(Card, { children: /* @__PURE__ */ jsx2(CardContent, { className: "py-10 text-center text-sm text-muted-foreground", children: spacesQuery.isError ? t("The spaces could not be loaded.") : spaceItems === void 0 && spacesQuery.data ? t("This drive needs mgamadeus/ddd-clouddrive 0.1.0-rc.10 or newer on the server.") : t("There is no space you may read.") }) })
727
+ ] });
728
+ }
729
+ return /* @__PURE__ */ jsx2(
730
+ FileManager,
731
+ {
732
+ adapter,
733
+ variant,
734
+ areas,
735
+ urlKeys: CLOUD_DRIVE_URL_KEYS,
736
+ title: heading,
737
+ description,
738
+ headerActions,
739
+ canWrite: spaceItem?.canWrite ?? false,
740
+ urlStateAdapter: listUrl,
741
+ drawerUrlAdapter: drawerUrl,
742
+ loadPdfJs,
743
+ defaultView,
744
+ renderAreaPicker: (props) => /* @__PURE__ */ jsx2(CloudDriveSpacePicker, { ...props, spaces: spaceItems }),
745
+ renderAreaMaintenance: isPartner ? void 0 : renderAreaMaintenance,
746
+ renderAreaSettings: isPartner ? void 0 : renderAreaSettings,
747
+ formatEventType: eventLabel,
748
+ readOnlyNotice: t("You may read this space, but not change it.")
749
+ }
750
+ );
751
+ };
752
+ export {
753
+ CLOUD_DRIVE_FILE_CAPABILITIES,
754
+ CLOUD_DRIVE_NODE_KEY,
755
+ CLOUD_DRIVE_URL_KEYS,
756
+ CloudDriveScreen,
757
+ CloudDriveSpacePicker,
758
+ DRIVE_ACTIVITY_LIMIT,
759
+ DRIVE_EMPTY_TRASH_MAX_CALLS,
760
+ DRIVE_EVENT_LABELS,
761
+ DRIVE_LIST_MAX_LIMIT,
762
+ DRIVE_LIST_PAGE_SIZE,
763
+ DRIVE_USAGE_PART_LABELS,
764
+ buildCloudDriveFileActions,
765
+ createCloudDriveFileAdapter,
766
+ driveAreaRefOf,
767
+ driveAreaViewOf,
768
+ driveChildrenArgOf,
769
+ driveEventViewOf,
770
+ driveFamilyOf,
771
+ driveFileItemsOf,
772
+ driveFileViewOf,
773
+ driveFolderIdOf,
774
+ driveFolderViewsOf,
775
+ driveLocationMissOf,
776
+ driveLocationResolutionOf,
777
+ drivePurposeOf,
778
+ driveScanStatusOf,
779
+ driveUsagePartsOf,
780
+ driveVersionNoteOf,
781
+ driveVersionViewOf,
782
+ effectiveQuotaOf,
783
+ emptyDriveTrashFully,
784
+ formatDriveSize,
785
+ groupDriveSpaces,
786
+ nextDriveListLimit,
787
+ parseDriveTime,
788
+ sendDriveUpload,
789
+ useCloudDriveFileAdapter
790
+ };
791
+ //# sourceMappingURL=index.js.map