@widgetic/file-browser 0.5.48 → 0.5.49

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.
Files changed (81) hide show
  1. package/dist/actions/dragSelectedToFolder.js +115 -104
  2. package/dist/components/FolderTree.svelte.d.ts +7 -4
  3. package/dist/components/core/FileBrowser.svelte +1 -3
  4. package/dist/components/core/dropzoneClick.js +2 -3
  5. package/dist/components/previews/FilePreview.svelte.d.ts +2 -2
  6. package/dist/config.js +3 -4
  7. package/dist/i18n/context.js +2 -2
  8. package/dist/i18n/errors.js +1 -2
  9. package/dist/i18n/messages.js +2 -2
  10. package/dist/i18n/text.js +2 -2
  11. package/dist/mediaLibrary/capabilities.js +3 -4
  12. package/dist/mediaLibrary/context.js +3 -4
  13. package/dist/mediaLibrary/errors.js +35 -46
  14. package/dist/mediaLibrary/normalize.js +42 -45
  15. package/dist/mediaLibrary/paging.js +45 -100
  16. package/dist/mediaLibrary/resolve.js +95 -214
  17. package/dist/mediaLibrary/treeOps.js +20 -40
  18. package/dist/mediaLibrary/urls.js +10 -12
  19. package/dist/mediaLibrary/widgetic.js +54 -140
  20. package/dist/stores/dragStore.js +1 -1
  21. package/dist/stores/fileStore.d.ts +3 -3
  22. package/dist/stores/fileStore.js +37 -44
  23. package/dist/stores/folderCountStore.js +11 -12
  24. package/dist/stores/missingFilesStore.js +3 -3
  25. package/dist/stores/navigationStore.d.ts +1 -1
  26. package/dist/stores/navigationStore.js +178 -217
  27. package/dist/stores/persistentSelectStore.d.ts +1 -1
  28. package/dist/stores/persistentSelectStore.js +94 -117
  29. package/dist/stores/searchStore.js +1 -1
  30. package/dist/stores/uploadApiStore.js +7 -7
  31. package/dist/stores/viewportStore.js +4 -4
  32. package/dist/types/index.js +1 -0
  33. package/dist/utils/apiConfig.js +9 -9
  34. package/dist/utils/brandKitLibraryTree.js +42 -57
  35. package/dist/utils/dateUtils.js +9 -11
  36. package/dist/utils/dragToFolder/batchMoveResult.js +54 -114
  37. package/dist/utils/dragToFolder/folderDropTarget.js +17 -23
  38. package/dist/utils/dragToFolder/springStep.js +3 -4
  39. package/dist/utils/fileGoneProbe.js +16 -65
  40. package/dist/utils/fileKinds.js +13 -14
  41. package/dist/utils/fileNames.js +7 -7
  42. package/dist/utils/fileOperations.js +332 -440
  43. package/dist/utils/fileTypes.js +14 -19
  44. package/dist/utils/fileUtils.js +31 -85
  45. package/dist/utils/folderUtils.js +4 -5
  46. package/dist/utils/gridLayout.js +7 -7
  47. package/dist/utils/imagePreviewCache.js +15 -26
  48. package/dist/utils/imagePreviewFrame.js +13 -13
  49. package/dist/utils/imagePreviewVisualState.js +4 -5
  50. package/dist/utils/imageTransform.js +14 -27
  51. package/dist/utils/itemMenuCapabilities.js +7 -7
  52. package/dist/utils/libraryTree.js +39 -55
  53. package/dist/utils/pendingUploadDeletes.js +113 -289
  54. package/dist/utils/previewKeys.js +1 -1
  55. package/dist/utils/previewListNavigation.js +11 -13
  56. package/dist/utils/previewNavigation.js +7 -10
  57. package/dist/utils/recentFiles.js +6 -16
  58. package/dist/utils/recentFilesLimit.js +2 -2
  59. package/dist/utils/removeItems.js +29 -61
  60. package/dist/utils/resolveFileUrl.js +6 -6
  61. package/dist/utils/safeText.js +12 -14
  62. package/dist/utils/searchDropdownPhase.js +2 -2
  63. package/dist/utils/searchItems.js +14 -30
  64. package/dist/utils/searchNavigation.js +5 -5
  65. package/dist/utils/uploadAuth.js +36 -111
  66. package/dist/utils/uploadDisplayProgress.js +1 -1
  67. package/dist/utils/uploadLimits.js +66 -138
  68. package/dist/utils/uploadListReconcile.js +11 -24
  69. package/dist/utils/uploadPanelDismiss.js +1 -1
  70. package/dist/utils/uploadPanelProgress.js +4 -4
  71. package/dist/utils/uploadProgressMath.js +11 -13
  72. package/dist/utils/uploadRefusals.js +24 -40
  73. package/dist/utils/uploadResponseMapping.js +8 -9
  74. package/dist/utils/uploadUiHelpers.js +17 -17
  75. package/dist/utils/userUploadsStorage.js +133 -270
  76. package/dist/utils/videoFrame.js +2 -2
  77. package/dist/utils/widgeticDelete.js +30 -103
  78. package/dist/utils/widgeticTusUpload.js +105 -189
  79. package/dist/utils/widgeticUpload.js +62 -130
  80. package/dist/utils/xhrMultipartUpload.js +116 -164
  81. package/package.json +1 -1
@@ -1,59 +1,3 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
- return new (P || (P = Promise))(function (resolve, reject) {
15
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
- step((generator = generator.apply(thisArg, _arguments || [])).next());
19
- });
20
- };
21
- var __generator = (this && this.__generator) || function (thisArg, body) {
22
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
23
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
24
- function verb(n) { return function (v) { return step([n, v]); }; }
25
- function step(op) {
26
- if (f) throw new TypeError("Generator is already executing.");
27
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
28
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
29
- if (y = 0, t) op = [op[0] & 2, t.value];
30
- switch (op[0]) {
31
- case 0: case 1: t = op; break;
32
- case 4: _.label++; return { value: op[1], done: false };
33
- case 5: _.label++; y = op[1]; op = [0]; continue;
34
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
35
- default:
36
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
37
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
38
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
39
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
40
- if (t[2]) _.ops.pop();
41
- _.trys.pop(); continue;
42
- }
43
- op = body.call(thisArg, _);
44
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
45
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46
- }
47
- };
48
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
49
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
50
- if (ar || !(i in from)) {
51
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
52
- ar[i] = from[i];
53
- }
54
- }
55
- return to.concat(ar || Array.prototype.slice.call(from));
56
- };
57
1
  import { fileStore, sortCriteria, sortDirection, selectedFiles, currentFolder, fileFilter } from '../stores/fileStore';
58
2
  import { persistHistory } from '../stores/navigationStore';
59
3
  import { getFileBrowserUploadConfig } from '../stores/uploadApiStore';
@@ -66,22 +10,22 @@ import { collectFileIdsInSubtree, deleteSubtreeUploadsOnApi } from './widgeticDe
66
10
  import { removePersistedUploads } from './userUploadsStorage';
67
11
  // Add helper function for sorting folder contents
68
12
  function sortFolderContents(items) {
69
- var currentSortCriteria = get(sortCriteria);
70
- var currentSortDirection = get(sortDirection);
71
- items.sort(function (a, b) {
13
+ const currentSortCriteria = get(sortCriteria);
14
+ const currentSortDirection = get(sortDirection);
15
+ items.sort((a, b) => {
72
16
  // Always keep folders at the top
73
17
  if (a.type === 'folder' && b.type !== 'folder')
74
18
  return -1;
75
19
  if (a.type !== 'folder' && b.type === 'folder')
76
20
  return 1;
77
- var comparison = 0;
21
+ let comparison = 0;
78
22
  switch (currentSortCriteria) {
79
23
  case 'name':
80
24
  comparison = a.name.localeCompare(b.name);
81
25
  break;
82
26
  case 'date':
83
- var aDate = new Date(a.modified || 0).getTime();
84
- var bDate = new Date(b.modified || 0).getTime();
27
+ const aDate = new Date(a.modified || 0).getTime();
28
+ const bDate = new Date(b.modified || 0).getTime();
85
29
  comparison = bDate - aDate;
86
30
  break;
87
31
  case 'size':
@@ -94,42 +38,30 @@ function sortFolderContents(items) {
94
38
  /**
95
39
  * Uploads a file to the server
96
40
  */
97
- export function uploadFile(file, path) {
98
- return __awaiter(this, void 0, void 0, function () {
99
- var formData, response;
100
- return __generator(this, function (_a) {
101
- switch (_a.label) {
102
- case 0:
103
- formData = new FormData();
104
- formData.append('file', file);
105
- formData.append('path', path);
106
- return [4 /*yield*/, fetch(ENDPOINTS.UPLOAD, {
107
- method: 'POST',
108
- body: formData
109
- })];
110
- case 1:
111
- response = _a.sent();
112
- if (!response.ok) {
113
- throw new Error('File upload failed');
114
- }
115
- return [2 /*return*/, response.json()];
116
- }
117
- });
41
+ export async function uploadFile(file, path) {
42
+ const formData = new FormData();
43
+ formData.append('file', file);
44
+ formData.append('path', path);
45
+ const response = await fetch(ENDPOINTS.UPLOAD, {
46
+ method: 'POST',
47
+ body: formData
118
48
  });
49
+ if (!response.ok) {
50
+ throw new Error('File upload failed');
51
+ }
52
+ return response.json();
119
53
  }
120
54
  /**
121
55
  * Adds a file to a specific folder in the file structure
122
56
  */
123
57
  export function addFileToStructure(structure, folderId, newFile) {
124
- var _a;
125
58
  if (structure.id === folderId) {
126
- structure.children = (_a = structure.children) !== null && _a !== void 0 ? _a : [];
59
+ structure.children = structure.children ?? [];
127
60
  structure.children.push(newFile);
128
61
  return true;
129
62
  }
130
63
  if (structure.children) {
131
- for (var _i = 0, _b = structure.children; _i < _b.length; _i++) {
132
- var child = _b[_i];
64
+ for (const child of structure.children) {
133
65
  if (child.type === 'folder') {
134
66
  if (addFileToStructure(child, folderId, newFile)) {
135
67
  return true;
@@ -145,220 +77,219 @@ export function addFileToStructure(structure, folderId, newFile) {
145
77
  * @param newName New name for the item
146
78
  * @returns Promise resolving to success status
147
79
  */
148
- export function renameItem(itemId, newName) {
149
- return __awaiter(this, void 0, Promise, function () {
150
- var item, finalName_1, currentSortCriteria_1, currentSortDirection_1, response, success_1, updatedTime_1, error_1;
151
- return __generator(this, function (_a) {
152
- switch (_a.label) {
153
- case 0:
154
- _a.trys.push([0, 2, , 3]);
155
- // Validate new name
156
- if (!newName.trim() || newName.length < 1) {
157
- console.error('Invalid new name');
158
- return [2 /*return*/, false];
159
- }
160
- item = findItemById(itemId);
161
- if (!item) {
162
- console.error('Item not found:', itemId);
163
- return [2 /*return*/, false];
164
- }
165
- // Don't rename if name hasn't changed
166
- if (item.name === newName) {
167
- // console.log('Name unchanged, skipping rename');
168
- return [2 /*return*/, false];
169
- }
170
- finalName_1 = newName;
171
- if (item.type === 'file') {
172
- finalName_1 = getRenamedFileName(item.name, newName);
173
- }
174
- currentSortCriteria_1 = 'name';
175
- currentSortDirection_1 = 'asc';
176
- sortCriteria.subscribe(function (value) { return currentSortCriteria_1 = value; })();
177
- sortDirection.subscribe(function (value) { return currentSortDirection_1 = value; })();
178
- return [4 /*yield*/, mockRenameAPI(itemId, finalName_1)];
179
- case 1:
180
- response = _a.sent();
181
- if (!response.success) {
182
- throw new Error(response.error || 'Failed to rename item on server');
183
- }
184
- success_1 = false;
185
- updatedTime_1 = new Date().toISOString();
186
- // 1. Update main file structure
187
- fileStore.update(function (store) {
188
- var _a;
189
- var updateName = function (items) {
190
- var _a;
191
- for (var i = 0; i < items.length; i++) {
192
- if (items[i].id === itemId) {
193
- // Update name and modified date
194
- items[i] = __assign(__assign({}, items[i]), { name: finalName_1, modified: updatedTime_1 });
195
- success_1 = true;
196
- // Sort items based on current criteria
197
- items.sort(function (a, b) {
198
- // Always keep folders at the top
199
- if (a.type === 'folder' && b.type !== 'folder')
200
- return -1;
201
- if (a.type !== 'folder' && b.type === 'folder')
202
- return 1;
203
- var comparison = 0;
204
- switch (currentSortCriteria_1) {
205
- case 'name':
206
- comparison = a.name.localeCompare(b.name);
207
- break;
208
- case 'date':
209
- var aDate = new Date(a.modified || 0).getTime();
210
- var bDate = new Date(b.modified || 0).getTime();
211
- comparison = bDate - aDate; // Newer first
212
- break;
213
- case 'size':
214
- comparison = (b.size || 0) - (a.size || 0); // Larger first
215
- break;
216
- }
217
- return currentSortDirection_1 === 'asc' ? comparison : -comparison;
218
- });
219
- return true;
220
- }
221
- if (items[i].type === 'folder') {
222
- var children = (_a = items[i].children) !== null && _a !== void 0 ? _a : [];
223
- if (updateName(children)) {
224
- items[i].children = children;
225
- return true;
226
- }
227
- }
228
- }
229
- return false;
80
+ export async function renameItem(itemId, newName) {
81
+ try {
82
+ // Validate new name
83
+ if (!newName.trim() || newName.length < 1) {
84
+ console.error('Invalid new name');
85
+ return false;
86
+ }
87
+ // First, find the item to get its type and current name
88
+ const item = findItemById(itemId);
89
+ if (!item) {
90
+ console.error('Item not found:', itemId);
91
+ return false;
92
+ }
93
+ // Don't rename if name hasn't changed
94
+ if (item.name === newName) {
95
+ // console.log('Name unchanged, skipping rename');
96
+ return false;
97
+ }
98
+ // For files, preserve the extension to maintain correct file type
99
+ let finalName = newName;
100
+ if (item.type === 'file') {
101
+ finalName = getRenamedFileName(item.name, newName);
102
+ }
103
+ // Get current sort settings
104
+ let currentSortCriteria = 'name';
105
+ let currentSortDirection = 'asc';
106
+ sortCriteria.subscribe(value => currentSortCriteria = value)();
107
+ sortDirection.subscribe(value => currentSortDirection = value)();
108
+ // The new name is shown at once: there is no server behind this list to wait for (the saved tree, in the local cache, is
109
+ // written by the caller right after), so the old one-second pause of the mock only made the rename feel slow.
110
+ const response = await mockRenameAPI(itemId, finalName);
111
+ if (!response.success) {
112
+ throw new Error(response.error || 'Failed to rename item on server');
113
+ }
114
+ // If API call succeeds, update all relevant stores
115
+ let success = false;
116
+ const updatedTime = new Date().toISOString();
117
+ // 1. Update main file structure
118
+ fileStore.update(store => {
119
+ const updateName = (items) => {
120
+ for (let i = 0; i < items.length; i++) {
121
+ if (items[i].id === itemId) {
122
+ // Update name and modified date
123
+ items[i] = {
124
+ ...items[i],
125
+ name: finalName,
126
+ modified: updatedTime
230
127
  };
231
- var rootChildren = (_a = store.root.children) !== null && _a !== void 0 ? _a : [];
232
- updateName(rootChildren);
233
- store.root.children = rootChildren;
234
- return store;
235
- });
236
- // 2. Update selected files if the renamed item is in the selection
237
- selectedFiles.update(function (files) {
238
- return files.map(function (file) {
239
- if (file.id === itemId) {
240
- return __assign(__assign({}, file), { name: finalName_1, modified: updatedTime_1 });
128
+ success = true;
129
+ // Sort items based on current criteria
130
+ items.sort((a, b) => {
131
+ // Always keep folders at the top
132
+ if (a.type === 'folder' && b.type !== 'folder')
133
+ return -1;
134
+ if (a.type !== 'folder' && b.type === 'folder')
135
+ return 1;
136
+ let comparison = 0;
137
+ switch (currentSortCriteria) {
138
+ case 'name':
139
+ comparison = a.name.localeCompare(b.name);
140
+ break;
141
+ case 'date':
142
+ const aDate = new Date(a.modified || 0).getTime();
143
+ const bDate = new Date(b.modified || 0).getTime();
144
+ comparison = bDate - aDate; // Newer first
145
+ break;
146
+ case 'size':
147
+ comparison = (b.size || 0) - (a.size || 0); // Larger first
148
+ break;
241
149
  }
242
- return file;
150
+ return currentSortDirection === 'asc' ? comparison : -comparison;
243
151
  });
244
- });
245
- // 3. Update current folder path if needed and persist to localStorage
246
- currentFolder.update(function (path) {
247
- // If the renamed item is a folder and it's in the current path
248
- var item = findItemById(itemId);
249
- if ((item === null || item === void 0 ? void 0 : item.type) === 'folder') {
250
- var newPath = path.map(function (segment) { return segment === item.name ? finalName_1 : segment; });
251
- // Update localStorage if persistHistory is enabled
252
- var isPersisted_1 = false;
253
- persistHistory.subscribe(function (value) { return isPersisted_1 = value; })();
254
- if (isPersisted_1) {
255
- try {
256
- var navigationHistory = JSON.parse(localStorage.getItem('navigationHistory') || '{}');
257
- if (navigationHistory.paths) {
258
- // Update all instances of the old folder name in saved paths
259
- navigationHistory.paths = navigationHistory.paths.map(function (savedPath) {
260
- return savedPath.map(function (segment) { return segment === item.name ? finalName_1 : segment; });
261
- });
262
- localStorage.setItem('navigationHistory', JSON.stringify(navigationHistory));
263
- // console.log('Updated navigation history in localStorage after rename');
264
- }
265
- }
266
- catch (error) {
267
- console.error('Error updating navigation history:', error);
268
- }
269
- }
270
- return newPath;
152
+ return true;
153
+ }
154
+ if (items[i].type === 'folder') {
155
+ const children = items[i].children ?? [];
156
+ if (updateName(children)) {
157
+ items[i].children = children;
158
+ return true;
271
159
  }
272
- return path;
273
- });
274
- // Log the updates
275
- // console.log('File system updated after rename:', {
276
- // itemId,
277
- // newName: finalName,
278
- // success,
279
- // time: updatedTime
280
- // });
281
- return [2 /*return*/, success_1];
282
- case 2:
283
- error_1 = _a.sent();
284
- console.error('Error renaming item:', error_1);
285
- return [2 /*return*/, false];
286
- case 3: return [2 /*return*/];
287
- }
160
+ }
161
+ }
162
+ return false;
163
+ };
164
+ const rootChildren = store.root.children ?? [];
165
+ updateName(rootChildren);
166
+ store.root.children = rootChildren;
167
+ return store;
288
168
  });
289
- });
290
- }
291
- // Mock API function for rename
292
- function mockRenameAPI(itemId, newName) {
293
- return __awaiter(this, void 0, Promise, function () {
294
- var item;
295
- return __generator(this, function (_a) {
296
- try {
297
- item = findItemById(itemId);
298
- if (!item) {
299
- return [2 /*return*/, {
300
- success: false,
301
- error: 'Item not found'
302
- }];
169
+ // 2. Update selected files if the renamed item is in the selection
170
+ selectedFiles.update(files => {
171
+ return files.map(file => {
172
+ if (file.id === itemId) {
173
+ return {
174
+ ...file,
175
+ name: finalName,
176
+ modified: updatedTime
177
+ };
303
178
  }
304
- // Skip blob URL checks for files since they can cause ERR_METHOD_NOT_SUPPORTED
305
- if (item.type === 'file' && item.url && item.url.startsWith('blob:')) {
306
- // console.log('Skipping blob URL check for file:', item.name);
307
- // Just return success for blob URLs
308
- return [2 /*return*/, {
309
- success: true
310
- }];
179
+ return file;
180
+ });
181
+ });
182
+ // 3. Update current folder path if needed and persist to localStorage
183
+ currentFolder.update(path => {
184
+ // If the renamed item is a folder and it's in the current path
185
+ const item = findItemById(itemId);
186
+ if (item?.type === 'folder') {
187
+ const newPath = path.map(segment => segment === item.name ? finalName : segment);
188
+ // Update localStorage if persistHistory is enabled
189
+ let isPersisted = false;
190
+ persistHistory.subscribe((value) => isPersisted = value)();
191
+ if (isPersisted) {
192
+ try {
193
+ const navigationHistory = JSON.parse(localStorage.getItem('navigationHistory') || '{}');
194
+ if (navigationHistory.paths) {
195
+ // Update all instances of the old folder name in saved paths
196
+ navigationHistory.paths = navigationHistory.paths.map((savedPath) => savedPath.map(segment => segment === item.name ? finalName : segment));
197
+ localStorage.setItem('navigationHistory', JSON.stringify(navigationHistory));
198
+ // console.log('Updated navigation history in localStorage after rename');
199
+ }
200
+ }
201
+ catch (error) {
202
+ console.error('Error updating navigation history:', error);
203
+ }
311
204
  }
312
- // Mock success response for all other cases
313
- return [2 /*return*/, {
314
- success: true
315
- }];
316
- }
317
- catch (error) {
318
- console.error('Error in mockRenameAPI:', error);
319
- return [2 /*return*/, {
320
- success: false,
321
- error: error instanceof Error ? error.message : 'Unknown error occurred'
322
- }];
205
+ return newPath;
323
206
  }
324
- return [2 /*return*/];
207
+ return path;
325
208
  });
326
- });
209
+ // Log the updates
210
+ // console.log('File system updated after rename:', {
211
+ // itemId,
212
+ // newName: finalName,
213
+ // success,
214
+ // time: updatedTime
215
+ // });
216
+ return success;
217
+ }
218
+ catch (error) {
219
+ console.error('Error renaming item:', error);
220
+ return false;
221
+ }
222
+ }
223
+ // Mock API function for rename
224
+ async function mockRenameAPI(itemId, newName) {
225
+ try {
226
+ // Check if the item exists in the file structure before proceeding
227
+ const item = findItemById(itemId);
228
+ if (!item) {
229
+ return {
230
+ success: false,
231
+ error: 'Item not found'
232
+ };
233
+ }
234
+ // Skip blob URL checks for files since they can cause ERR_METHOD_NOT_SUPPORTED
235
+ if (item.type === 'file' && item.url && item.url.startsWith('blob:')) {
236
+ // console.log('Skipping blob URL check for file:', item.name);
237
+ // Just return success for blob URLs
238
+ return {
239
+ success: true
240
+ };
241
+ }
242
+ // Mock success response for all other cases
243
+ return {
244
+ success: true
245
+ };
246
+ }
247
+ catch (error) {
248
+ console.error('Error in mockRenameAPI:', error);
249
+ return {
250
+ success: false,
251
+ error: error instanceof Error ? error.message : 'Unknown error occurred'
252
+ };
253
+ }
327
254
  }
328
255
  /**
329
256
  * Moves an item (file or folder) to a new location
330
257
  */
331
258
  export function moveItem(itemId, targetFolderId) {
332
- var success = false;
333
- var itemToMove = null;
334
- var updatedTime = new Date().toISOString();
335
- fileStore.update(function (store) {
336
- var _a;
337
- var removeItem = function (items) {
338
- var _a;
339
- for (var i = 0; i < items.length; i++) {
259
+ let success = false;
260
+ let itemToMove = null;
261
+ const updatedTime = new Date().toISOString();
262
+ fileStore.update(store => {
263
+ const removeItem = (items) => {
264
+ for (let i = 0; i < items.length; i++) {
340
265
  if (items[i].id === itemId) {
341
- itemToMove = __assign(__assign({}, items[i]), { modified: updatedTime // Update moved item's timestamp
342
- });
266
+ itemToMove = {
267
+ ...items[i],
268
+ modified: updatedTime // Update moved item's timestamp
269
+ };
343
270
  items.splice(i, 1);
344
271
  return true;
345
272
  }
346
273
  if (items[i].type === 'folder') {
347
- var children = (_a = items[i].children) !== null && _a !== void 0 ? _a : [];
274
+ const children = items[i].children ?? [];
348
275
  if (removeItem(children)) {
349
276
  // Update source folder's timestamp
350
- items[i] = __assign(__assign({}, items[i]), { children: children, modified: updatedTime });
277
+ items[i] = {
278
+ ...items[i],
279
+ children,
280
+ modified: updatedTime
281
+ };
351
282
  return true;
352
283
  }
353
284
  }
354
285
  }
355
286
  return false;
356
287
  };
357
- var rootChildren = (_a = store.root.children) !== null && _a !== void 0 ? _a : [];
288
+ const rootChildren = store.root.children ?? [];
358
289
  if (removeItem(rootChildren) && itemToMove) {
359
290
  store.root.children = rootChildren;
360
291
  // If targetFolderId is root, add to root
361
- var isTargetRoot = targetFolderId === '' ||
292
+ const isTargetRoot = targetFolderId === '' ||
362
293
  targetFolderId === 'root' ||
363
294
  Boolean(store.root && targetFolderId === store.root.id);
364
295
  if (isTargetRoot) {
@@ -368,12 +299,11 @@ export function moveItem(itemId, targetFolderId) {
368
299
  }
369
300
  else {
370
301
  // Add to new location and update target folder's timestamp
371
- var addToTarget_1 = function (items) {
372
- var _a, _b;
373
- for (var i = 0; i < items.length; i++) {
302
+ const addToTarget = (items) => {
303
+ for (let i = 0; i < items.length; i++) {
374
304
  if (items[i].id === targetFolderId) {
375
- var targetFolder = items[i];
376
- targetFolder.children = (_a = targetFolder.children) !== null && _a !== void 0 ? _a : [];
305
+ const targetFolder = items[i];
306
+ targetFolder.children = targetFolder.children ?? [];
377
307
  targetFolder.children.push(itemToMove);
378
308
  targetFolder.modified = updatedTime;
379
309
  // Sort children according to current criteria
@@ -382,23 +312,23 @@ export function moveItem(itemId, targetFolderId) {
382
312
  }
383
313
  if (items[i].type === 'folder') {
384
314
  // Ensure children is an array before passing it
385
- var children = (_b = items[i].children) !== null && _b !== void 0 ? _b : [];
386
- if (addToTarget_1(children)) {
315
+ const children = items[i].children ?? [];
316
+ if (addToTarget(children)) {
387
317
  return true;
388
318
  }
389
319
  }
390
320
  }
391
321
  return false;
392
322
  };
393
- success = addToTarget_1(rootChildren);
323
+ success = addToTarget(rootChildren);
394
324
  }
395
325
  }
396
326
  return store;
397
327
  });
398
328
  // Update folder counts after move
399
329
  if (success) {
400
- var store = get(fileStore);
401
- var currentFilter = get(fileFilter);
330
+ const store = get(fileStore);
331
+ const currentFilter = get(fileFilter);
402
332
  // Ensure we have a valid FileFilterType
403
333
  if (typeof currentFilter === 'string' && ['all', 'image', 'video', 'document'].includes(currentFilter)) {
404
334
  updateFolderCounts(store.root, currentFilter);
@@ -417,18 +347,16 @@ export function moveItem(itemId, targetFolderId) {
417
347
  export function moveItems(itemIds, targetFolderId) {
418
348
  if (itemIds.length === 0)
419
349
  return [];
420
- var updatedTime = new Date().toISOString();
421
- var idSet = new Set(itemIds);
422
- var collected = [];
423
- var movedIds = [];
424
- fileStore.update(function (store) {
425
- var _a;
426
- var _b;
427
- var removeCollected = function (items) {
428
- for (var i = items.length - 1; i >= 0; i--) {
429
- var entry = items[i];
350
+ const updatedTime = new Date().toISOString();
351
+ const idSet = new Set(itemIds);
352
+ const collected = [];
353
+ const movedIds = [];
354
+ fileStore.update((store) => {
355
+ const removeCollected = (items) => {
356
+ for (let i = items.length - 1; i >= 0; i--) {
357
+ const entry = items[i];
430
358
  if (idSet.has(entry.id)) {
431
- collected.push(__assign(__assign({}, entry), { modified: updatedTime }));
359
+ collected.push({ ...entry, modified: updatedTime });
432
360
  movedIds.push(entry.id);
433
361
  items.splice(i, 1);
434
362
  continue;
@@ -439,34 +367,32 @@ export function moveItems(itemIds, targetFolderId) {
439
367
  }
440
368
  }
441
369
  };
442
- var rootChildren = (_b = store.root.children) !== null && _b !== void 0 ? _b : [];
370
+ const rootChildren = store.root.children ?? [];
443
371
  removeCollected(rootChildren);
444
372
  store.root.children = rootChildren;
445
373
  if (collected.length === 0)
446
374
  return store;
447
- var isTargetRoot = targetFolderId === '' ||
375
+ const isTargetRoot = targetFolderId === '' ||
448
376
  targetFolderId === 'root' ||
449
377
  Boolean(store.root && targetFolderId === store.root.id);
450
378
  if (isTargetRoot) {
451
- (_a = store.root.children).push.apply(_a, collected);
379
+ store.root.children.push(...collected);
452
380
  store.root.modified = updatedTime;
453
381
  sortFolderContents(store.root.children);
454
382
  return store;
455
383
  }
456
- var addToTarget = function (items) {
457
- var _a;
458
- var _b, _c;
459
- for (var i = 0; i < items.length; i++) {
384
+ const addToTarget = (items) => {
385
+ for (let i = 0; i < items.length; i++) {
460
386
  if (items[i].id === targetFolderId && items[i].type === 'folder') {
461
- var targetFolder = items[i];
462
- targetFolder.children = (_b = targetFolder.children) !== null && _b !== void 0 ? _b : [];
463
- (_a = targetFolder.children).push.apply(_a, collected);
387
+ const targetFolder = items[i];
388
+ targetFolder.children = targetFolder.children ?? [];
389
+ targetFolder.children.push(...collected);
464
390
  targetFolder.modified = updatedTime;
465
391
  sortFolderContents(targetFolder.children);
466
392
  return true;
467
393
  }
468
394
  if (items[i].type === 'folder') {
469
- var children = (_c = items[i].children) !== null && _c !== void 0 ? _c : [];
395
+ const children = items[i].children ?? [];
470
396
  if (addToTarget(children))
471
397
  return true;
472
398
  }
@@ -477,9 +403,9 @@ export function moveItems(itemIds, targetFolderId) {
477
403
  return store;
478
404
  });
479
405
  if (movedIds.length > 0) {
480
- var store = get(fileStore);
481
- var currentFilter = get(fileFilter);
482
- var filterValue = typeof currentFilter === 'string' && ['all', 'image', 'video', 'document'].includes(currentFilter)
406
+ const store = get(fileStore);
407
+ const currentFilter = get(fileFilter);
408
+ const filterValue = typeof currentFilter === 'string' && ['all', 'image', 'video', 'document'].includes(currentFilter)
483
409
  ? currentFilter
484
410
  : 'all';
485
411
  updateFolderCounts(store.root, filterValue);
@@ -489,30 +415,20 @@ export function moveItems(itemIds, targetFolderId) {
489
415
  /**
490
416
  * Mock API function for delete
491
417
  */
492
- function mockDeleteAPI(itemId, thumbnailPaths, filePaths) {
493
- return __awaiter(this, void 0, Promise, function () {
494
- return __generator(this, function (_a) {
495
- switch (_a.label) {
496
- case 0:
497
- // Simulate network delay
498
- return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 1000); })];
499
- case 1:
500
- // Simulate network delay
501
- _a.sent();
502
- // In a real API, we would delete both the original files and their thumbnails
503
- if (thumbnailPaths) {
504
- // console.log('Would delete thumbnails at:', thumbnailPaths);
505
- }
506
- if (filePaths) {
507
- // console.log('Would delete files at:', filePaths);
508
- }
509
- // Mock success response
510
- return [2 /*return*/, {
511
- success: true
512
- }];
513
- }
514
- });
515
- });
418
+ async function mockDeleteAPI(itemId, thumbnailPaths, filePaths) {
419
+ // Simulate network delay
420
+ await new Promise(resolve => setTimeout(resolve, 1000));
421
+ // In a real API, we would delete both the original files and their thumbnails
422
+ if (thumbnailPaths) {
423
+ // console.log('Would delete thumbnails at:', thumbnailPaths);
424
+ }
425
+ if (filePaths) {
426
+ // console.log('Would delete files at:', filePaths);
427
+ }
428
+ // Mock success response
429
+ return {
430
+ success: true
431
+ };
516
432
  }
517
433
  /**
518
434
  * Gets thumbnail path for a file if it exists
@@ -520,7 +436,7 @@ function mockDeleteAPI(itemId, thumbnailPaths, filePaths) {
520
436
  function getThumbnailPath(item) {
521
437
  if (item.type !== 'file' || !item.url)
522
438
  return undefined;
523
- var fileType = getFileType(item.url);
439
+ const fileType = getFileType(item.url);
524
440
  if (fileType === 'video') {
525
441
  // For videos, the thumbnail is a PNG with the same base name
526
442
  return item.url.replace(/\.[^/.]+$/, '.png');
@@ -534,113 +450,95 @@ function getThumbnailPath(item) {
534
450
  /**
535
451
  * Deletes a file or folder (and its contents)
536
452
  */
537
- export function deleteItem(itemId) {
538
- return __awaiter(this, void 0, Promise, function () {
453
+ export async function deleteItem(itemId) {
454
+ let success = false;
455
+ let itemToDelete = null;
456
+ try {
457
+ // Find the item first to get its thumbnail path if needed
458
+ itemToDelete = findItemById(itemId);
459
+ if (!itemToDelete) {
460
+ throw new Error('Item not found');
461
+ }
462
+ // Get thumbnail paths for all files that will be deleted
463
+ const thumbnailsToDelete = new Set();
464
+ const filesToDelete = new Set();
539
465
  function collectPaths(item) {
540
466
  if (item.type === 'file') {
541
467
  if (item.url) {
542
- filesToDelete_1.add(item.url);
468
+ filesToDelete.add(item.url);
543
469
  }
544
- var thumbnailPath = getThumbnailPath(item);
470
+ const thumbnailPath = getThumbnailPath(item);
545
471
  if (thumbnailPath) {
546
- thumbnailsToDelete_1.add(thumbnailPath);
472
+ thumbnailsToDelete.add(thumbnailPath);
547
473
  }
548
474
  }
549
475
  if (item.type === 'folder' && item.children) {
550
- item.children.forEach(function (child) { return collectPaths(child); });
476
+ item.children.forEach(child => collectPaths(child));
477
+ }
478
+ }
479
+ collectPaths(itemToDelete);
480
+ const uploadConfig = getFileBrowserUploadConfig();
481
+ const removedUploadIds = collectFileIdsInSubtree(itemToDelete);
482
+ if (uploadConfig?.accessToken && uploadConfig?.apiBasePath) {
483
+ await deleteSubtreeUploadsOnApi(uploadConfig, itemToDelete);
484
+ }
485
+ else {
486
+ const response = await mockDeleteAPI(itemId, Array.from(thumbnailsToDelete).join(','), Array.from(filesToDelete).join(','));
487
+ if (!response.success) {
488
+ throw new Error(response.error || 'Failed to delete item on server');
551
489
  }
552
490
  }
553
- var success, itemToDelete, thumbnailsToDelete_1, filesToDelete_1, uploadConfig, removedUploadIds, response, fileIdsToRemove_1, error_2;
554
- return __generator(this, function (_a) {
555
- switch (_a.label) {
556
- case 0:
557
- success = false;
558
- itemToDelete = null;
559
- _a.label = 1;
560
- case 1:
561
- _a.trys.push([1, 8, , 9]);
562
- // Find the item first to get its thumbnail path if needed
563
- itemToDelete = findItemById(itemId);
564
- if (!itemToDelete) {
565
- throw new Error('Item not found');
491
+ fileStore.update(store => {
492
+ const deleteFromStructure = (items) => {
493
+ for (let i = 0; i < items.length; i++) {
494
+ if (items[i].id === itemId) {
495
+ itemToDelete = items[i];
496
+ items.splice(i, 1);
497
+ success = true;
498
+ return true;
566
499
  }
567
- thumbnailsToDelete_1 = new Set();
568
- filesToDelete_1 = new Set();
569
- collectPaths(itemToDelete);
570
- uploadConfig = getFileBrowserUploadConfig();
571
- removedUploadIds = collectFileIdsInSubtree(itemToDelete);
572
- if (!((uploadConfig === null || uploadConfig === void 0 ? void 0 : uploadConfig.accessToken) && (uploadConfig === null || uploadConfig === void 0 ? void 0 : uploadConfig.apiBasePath))) return [3 /*break*/, 3];
573
- return [4 /*yield*/, deleteSubtreeUploadsOnApi(uploadConfig, itemToDelete)];
574
- case 2:
575
- _a.sent();
576
- return [3 /*break*/, 5];
577
- case 3: return [4 /*yield*/, mockDeleteAPI(itemId, Array.from(thumbnailsToDelete_1).join(','), Array.from(filesToDelete_1).join(','))];
578
- case 4:
579
- response = _a.sent();
580
- if (!response.success) {
581
- throw new Error(response.error || 'Failed to delete item on server');
500
+ if (items[i].type === 'folder') {
501
+ const children = items[i].children ?? [];
502
+ if (deleteFromStructure(children)) {
503
+ items[i].children = children;
504
+ return true;
505
+ }
582
506
  }
583
- _a.label = 5;
584
- case 5:
585
- fileStore.update(function (store) {
586
- var _a;
587
- var deleteFromStructure = function (items) {
588
- var _a;
589
- for (var i = 0; i < items.length; i++) {
590
- if (items[i].id === itemId) {
591
- itemToDelete = items[i];
592
- items.splice(i, 1);
593
- success = true;
594
- return true;
595
- }
596
- if (items[i].type === 'folder') {
597
- var children = (_a = items[i].children) !== null && _a !== void 0 ? _a : [];
598
- if (deleteFromStructure(children)) {
599
- items[i].children = children;
600
- return true;
601
- }
602
- }
603
- }
604
- return false;
605
- };
606
- var rootChildren = (_a = store.root.children) !== null && _a !== void 0 ? _a : [];
607
- deleteFromStructure(rootChildren);
608
- store.root.children = rootChildren;
609
- return store;
610
- });
611
- if (!(success && itemToDelete)) return [3 /*break*/, 7];
612
- fileIdsToRemove_1 = new Set(removedUploadIds);
613
- selectedFiles.update(function (files) { return files.filter(function (file) { return !fileIdsToRemove_1.has(file.id); }); });
614
- if (!((uploadConfig === null || uploadConfig === void 0 ? void 0 : uploadConfig.accessToken) && fileIdsToRemove_1.size > 0)) return [3 /*break*/, 7];
615
- return [4 /*yield*/, removePersistedUploads(__spreadArray([], fileIdsToRemove_1, true))];
616
- case 6:
617
- _a.sent();
618
- _a.label = 7;
619
- case 7: return [2 /*return*/, success];
620
- case 8:
621
- error_2 = _a.sent();
622
- console.error('Error deleting item:', error_2);
623
- return [2 /*return*/, false];
624
- case 9: return [2 /*return*/];
625
- }
507
+ }
508
+ return false;
509
+ };
510
+ const rootChildren = store.root.children ?? [];
511
+ deleteFromStructure(rootChildren);
512
+ store.root.children = rootChildren;
513
+ return store;
626
514
  });
627
- });
515
+ if (success && itemToDelete) {
516
+ const fileIdsToRemove = new Set(removedUploadIds);
517
+ selectedFiles.update((files) => files.filter((file) => !fileIdsToRemove.has(file.id)));
518
+ if (uploadConfig?.accessToken && fileIdsToRemove.size > 0) {
519
+ await removePersistedUploads([...fileIdsToRemove]);
520
+ }
521
+ }
522
+ return success;
523
+ }
524
+ catch (error) {
525
+ console.error('Error deleting item:', error);
526
+ return false;
527
+ }
628
528
  }
629
529
  /**
630
530
  * Gets an item by its ID
631
531
  */
632
532
  export function findItemById(itemId) {
633
- var foundItem = null;
634
- var searchInStructure = function (items) {
635
- var _a;
636
- for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
637
- var item = items_1[_i];
533
+ let foundItem = null;
534
+ const searchInStructure = (items) => {
535
+ for (const item of items) {
638
536
  if (item.id === itemId) {
639
537
  foundItem = item;
640
538
  return true;
641
539
  }
642
540
  if (item.type === 'folder') {
643
- var children = (_a = item.children) !== null && _a !== void 0 ? _a : [];
541
+ const children = item.children ?? [];
644
542
  if (searchInStructure(children)) {
645
543
  return true;
646
544
  }
@@ -648,9 +546,8 @@ export function findItemById(itemId) {
648
546
  }
649
547
  return false;
650
548
  };
651
- fileStore.subscribe(function (store) {
652
- var _a;
653
- var rootChildren = (_a = store.root.children) !== null && _a !== void 0 ? _a : [];
549
+ fileStore.subscribe(store => {
550
+ const rootChildren = store.root.children ?? [];
654
551
  searchInStructure(rootChildren);
655
552
  })();
656
553
  return foundItem;
@@ -659,11 +556,9 @@ export function findItemById(itemId) {
659
556
  * Gets an item's name from its ID
660
557
  */
661
558
  export function getItemNameById(itemId) {
662
- var _a;
663
- var foundName = null;
664
- var searchInStructure = function (items) {
665
- for (var _i = 0, items_2 = items; _i < items_2.length; _i++) {
666
- var item = items_2[_i];
559
+ let foundName = null;
560
+ const searchInStructure = (items) => {
561
+ for (const item of items) {
667
562
  if (item.id === itemId) {
668
563
  foundName = item.name;
669
564
  return true;
@@ -677,9 +572,9 @@ export function getItemNameById(itemId) {
677
572
  return false;
678
573
  };
679
574
  // Get the current store value using get() helper
680
- var store = get(fileStore);
575
+ const store = get(fileStore);
681
576
  // Check if store is initialized and has children
682
- if ((_a = store === null || store === void 0 ? void 0 : store.root) === null || _a === void 0 ? void 0 : _a.children) {
577
+ if (store?.root?.children) {
683
578
  searchInStructure(store.root.children);
684
579
  }
685
580
  else {
@@ -690,18 +585,16 @@ export function getItemNameById(itemId) {
690
585
  /**
691
586
  * Gets the full path of names for a given path of IDs
692
587
  */
693
- export function getPathNamesFromIds(pathIds, isLoading) {
694
- var _a;
695
- if (isLoading === void 0) { isLoading = false; }
588
+ export function getPathNamesFromIds(pathIds, isLoading = false) {
696
589
  // If app is loading, return empty placeholders to prevent flicker
697
590
  if (isLoading) {
698
- return pathIds.map(function () { return ''; });
591
+ return pathIds.map(() => '');
699
592
  }
700
593
  // Get the current store value
701
- var store = get(fileStore);
594
+ const store = get(fileStore);
702
595
  // Check if the file store is properly initialized with data
703
- var hasInitializedStore = (_a = store === null || store === void 0 ? void 0 : store.root) === null || _a === void 0 ? void 0 : _a.children;
704
- var hasData = hasInitializedStore && Array.isArray(store.root.children) && store.root.children.length > 0;
596
+ const hasInitializedStore = store?.root?.children;
597
+ const hasData = hasInitializedStore && Array.isArray(store.root.children) && store.root.children.length > 0;
705
598
  if (!hasInitializedStore || !hasData) {
706
599
  // console.warn('File store not fully loaded when getting path names', {
707
600
  // hasInitializedStore,
@@ -709,13 +602,12 @@ export function getPathNamesFromIds(pathIds, isLoading) {
709
602
  // childrenCount: store?.root?.children?.length || 0
710
603
  // });
711
604
  // Return empty strings during loading to prevent flicker with temporary names
712
- return pathIds.map(function () { return ''; });
605
+ return pathIds.map(() => '');
713
606
  }
714
607
  // Build a map of all IDs to names for quick lookup
715
- var idToNameMap = new Map();
608
+ const idToNameMap = new Map();
716
609
  function buildIdMap(items) {
717
- for (var _i = 0, items_3 = items; _i < items_3.length; _i++) {
718
- var item = items_3[_i];
610
+ for (const item of items) {
719
611
  idToNameMap.set(item.id, item.name);
720
612
  if (item.type === 'folder' && item.children) {
721
613
  buildIdMap(item.children);
@@ -723,17 +615,17 @@ export function getPathNamesFromIds(pathIds, isLoading) {
723
615
  }
724
616
  }
725
617
  // Build the map once for all IDs - we've already checked that children exists and is an array
726
- var rootChildren = store.root.children;
618
+ const rootChildren = store.root.children;
727
619
  buildIdMap(rootChildren);
728
620
  // Root folder special case - always use "Root" for the first item if path starts at root
729
621
  if (store.root && store.root.id) {
730
622
  idToNameMap.set(store.root.id, 'Root');
731
623
  }
732
624
  // Map IDs to names using the lookup map
733
- return pathIds.map(function (id) {
734
- var name = idToNameMap.get(id);
625
+ return pathIds.map((id) => {
626
+ const name = idToNameMap.get(id);
735
627
  if (!name) {
736
- console.warn("No name found for ID: ".concat(id), {
628
+ console.warn(`No name found for ID: ${id}`, {
737
629
  availableIds: Array.from(idToNameMap.keys()),
738
630
  storeHasData: hasData
739
631
  });