forked from shesha-io/shesha-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.tsx
More file actions
216 lines (189 loc) · 6.54 KB
/
utils.tsx
File metadata and controls
216 lines (189 loc) · 6.54 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
import React, { FC } from 'react';
import { Button, Popover, Skeleton, Typography, UploadFile } from 'antd';
import { HistoryOutlined } from '@ant-design/icons';
import filesize from 'filesize';
import { ConfigurableForm, DateDisplay } from '@/components';
import { useStoredFileGetFileVersions, StoredFileVersionInfoDto } from '@/apis/storedFile';
import { IStoredFile } from '@/providers/storedFiles/contexts';
import { FormIdentifier } from '@/providers/form/models';
import { listType } from '@/designer-components/attachmentsEditor/attachmentsEditor';
import { buildUrl } from '@/utils/url';
export interface IFileVersionsButtonProps {
fileId: string;
onDownload: (versionNo: number, fileName: string) => void;
}
export interface IExtraContentProps {
file: IStoredFile;
formId?: FormIdentifier;
}
/**
* Creates a placeholder file object for stub/preview rendering in design mode.
*
* @returns A mock IStoredFile with example properties
*/
export const createPlaceholderFile = (): IStoredFile => ({
uid: 'placeholder-file-1',
name: 'example-file.pdf',
status: 'done',
url: '',
type: 'application/pdf',
size: 1024000,
id: 'placeholder-id',
fileCategory: 'documents',
temporary: false,
userHasDownloaded: false,
});
/**
* Determines the appropriate Ant Design Upload list type based on configuration.
*
* @param type - The configured list type from component props
* @param isDragger - Whether the component is in dragger mode
* @returns The Upload component list type to use
*/
export const getListTypeAndLayout = (
type: listType | undefined, isDragger: boolean,
): 'text' | 'picture' | 'picture-card' => {
return type === 'text' || !type || isDragger ? 'text' : 'picture-card';
};
/**
* Result object returned by fetchStoredFile containing the object URL and cleanup function.
*/
export interface IFetchStoredFileResult {
/** The blob URL that can be used in img src, etc. */
url: string;
/** Cleanup function that revokes the object URL to prevent memory leaks. Must be called when the URL is no longer needed. */
revoke: () => void;
}
/**
* Fetches a stored file and returns a blob URL for display/preview along with a cleanup function.
*
* **Important**: The returned object contains a `revoke()` function that MUST be called when
* the URL is no longer needed to prevent memory leaks. The revoke function is safe to call
* multiple times.
*
* @param url - The file URL to fetch
* @param httpHeaders - Optional HTTP headers to include in the request
* @returns A Promise resolving to an object containing the blob URL and revoke function
* @throws {Error} If the fetch fails (non-ok response status)
*
* @example
* ```typescript
* const { url, revoke } = await fetchStoredFile('/api/files/123');
* try {
* // Use the URL...
* imgElement.src = url;
* } finally {
* // Always clean up
* revoke();
* }
* ```
*/
export const fetchStoredFile = async (
url: string,
httpHeaders: Record<string, string> = {},
): Promise<IFetchStoredFileResult> => {
const fetchUrl = buildUrl(url, { skipMarkDownload: 'true' });
const response = await fetch(fetchUrl, {
headers: { ...httpHeaders },
});
if (!response.ok) {
throw new Error(`Failed to fetch file: ${response.status} ${response.statusText}`);
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
let revoked = false;
const revoke = (): void => {
if (!revoked) {
URL.revokeObjectURL(objectUrl);
revoked = true;
}
};
return { url: objectUrl, revoke };
};
export const FileVersionsButton: FC<IFileVersionsButtonProps> = ({ fileId, onDownload }) => {
const {
loading,
refetch: fetchHistory,
data: serverData,
} = useStoredFileGetFileVersions({
fileId,
lazy: true,
});
if (fileId == null) return null;
const handleVisibleChange = (visible: boolean): void => {
if (visible) {
fetchHistory();
}
};
const uploads = serverData?.success ? serverData.result : [];
const handleVersionDownloadClick = (fileVersion: StoredFileVersionInfoDto): void => {
onDownload(fileVersion.versionNo, fileVersion.fileName);
};
const content = (
<Skeleton loading={loading}>
<ul>
{uploads &&
uploads.map((item, i) => (
<li key={item.versionNo ?? `version-${i}`}>
<strong>Version {item.versionNo}</strong> Uploaded{' '}
{item.dateUploaded && <DateDisplay>{item.dateUploaded}</DateDisplay>} by {item.uploadedBy}
<br />
<Button type="link" onClick={() => handleVersionDownloadClick(item)}>
{item.fileName} ({filesize(item.size)})
</Button>
</li>
))}
</ul>
</Skeleton>
);
return (
<Popover content={content} title="History" trigger="hover" onOpenChange={handleVisibleChange}>
<Button size="small" icon={<HistoryOutlined />} title="View history" />
</Popover>
);
};
export const ExtraContent: FC<IExtraContentProps> = ({ file, formId }) => {
if (!formId) {
return null;
}
return <ConfigurableForm formId={formId} mode="readonly" initialValues={file} />;
};
const { Text } = Typography;
// Helper function to format file size
const formatFileSize = (bytes?: number): string => {
if (bytes === undefined) return '';
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};
// Helper component to render file name with ellipsis and title
export const FileNameDisplay: FC<{
file: UploadFile;
className?: string;
popoverContent?: React.ReactNode;
popoverClassName?: string;
}> = ({ file, className, popoverContent, popoverClassName }) => {
const sizeStr = formatFileSize(file.size);
const title = sizeStr ? `${file.name} (${sizeStr})` : file.name;
const textElement = (
<Text
ellipsis
title={title}
style={{ display: 'block' }}
>
{file.name}
</Text>
);
return (
<div className={className} style={{ overflow: 'hidden', flex: 1 }}>
{popoverContent ? (
<Popover content={popoverContent} trigger="hover" placement="top" classNames={{ root: popoverClassName }}>
{textElement}
</Popover>
) : (
textElement
)}
</div>
);
};