@widgetic/file-browser 0.5.43 → 0.5.44

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.
@@ -771,7 +771,8 @@
771
771
  const token = session?.accessToken || session?.access_token;
772
772
  if (token) {
773
773
  // Scope Dexie only — do not invent an empty apiBasePath upload config.
774
- const { setCacheOwner } = await import('@widgetic/cache-layer');
774
+ const { ensureCacheOwnerFromSessionHint, setCacheOwner } = await import('@widgetic/cache-layer');
775
+ ensureCacheOwnerFromSessionHint();
775
776
  const payloadPart = token.split('.')[1];
776
777
  if (payloadPart) {
777
778
  const normalized = payloadPart.replace(/-/g, '+').replace(/_/g, '/');
@@ -808,6 +809,13 @@
808
809
 
809
810
  if (widgeticLibraryMode || !useDemoContent) {
810
811
  let files = await loadUserUploads();
812
+ const cachedCount = files.length;
813
+ if (cachedCount > 0) {
814
+ data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
815
+ basePath = '';
816
+ isLoading = false;
817
+ isVirtualListInitialized = true;
818
+ }
811
819
  if (uploadConfig?.accessToken && uploadConfig?.apiBasePath) {
812
820
  try {
813
821
  const remoteFiles = await fetchUserUploadsFromApi(uploadConfig, {
@@ -818,15 +826,22 @@
818
826
  apiHydrationSucceeded: true,
819
827
  });
820
828
  await replacePersistedUploads(files);
829
+ data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
830
+ basePath = '';
821
831
  if (showLogs) {
822
832
  // console.log('[FileBrowser] Hydrated uploads from API:', remoteFiles.length);
823
833
  }
824
834
  } catch (hydrateError) {
825
835
  console.warn('[FileBrowser] Upload hydration failed, using local cache:', hydrateError);
836
+ if (!data) {
837
+ data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
838
+ basePath = '';
839
+ }
826
840
  }
841
+ } else if (!data) {
842
+ data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
843
+ basePath = '';
827
844
  }
828
- data = await createUserUploadsFileSystemRoot(files, $t('library.defaultLabel'));
829
- basePath = '';
830
845
  if (showLogs) {
831
846
  // console.log('[FileBrowser] Widgetic library mode — user uploads only');
832
847
  }
@@ -1679,7 +1694,7 @@
1679
1694
  });
1680
1695
 
1681
1696
  showToast('success', initialToastMessage, {
1682
- description: $t('toast.inBackground'),
1697
+ description: libraryMode ? $t('toast.inBackground') : undefined,
1683
1698
  });
1684
1699
 
1685
1700
  // Process deletions in the background
@@ -1782,23 +1797,7 @@
1782
1797
  return Boolean(uploadConfig?.accessToken && uploadConfig?.apiBasePath) || !useDemoContent;
1783
1798
  }
1784
1799
 
1785
- // The built-in "My uploads" folder is named in the visitor's language, and follows a change of language.
1786
- function nameBuiltInFolder(folderName: string) {
1787
- fileStore.update((store) => {
1788
- const builtInFolder = store.root?.children?.find((child) => child.type === 'folder' && child.id === 'folder_my_uploads');
1789
- if (!store.root || !builtInFolder || builtInFolder.name === folderName) return store;
1790
- return {
1791
- ...store,
1792
- root: {
1793
- ...store.root,
1794
- children: (store.root.children ?? []).map((child) => (child === builtInFolder ? { ...child, name: folderName } : child)),
1795
- },
1796
- };
1797
- });
1798
- }
1799
- $: if (!libraryMode) nameBuiltInFolder($t('library.defaultLabel'));
1800
-
1801
- // Saves the whole root of the Widgetic library (the built-in Uploads folder, the folders next to it and the files loose
1800
+ // Saves the whole root of the Widgetic library (user folders and loose files at the root), so an upload, a new folder,
1802
1801
  // at the root), so an upload, a new folder, a rename or a move keeps its place after a reload.
1803
1802
  function persistMyUploadsTree() {
1804
1803
  if (libraryMode) return;
@@ -194,14 +194,15 @@
194
194
 
195
195
  function handleSelect(event: Event) {
196
196
  event.stopPropagation();
197
- if (!isMissing && allowSelecting) {
197
+ if (allowSelecting) {
198
198
  dispatch('select');
199
199
  }
200
200
  }
201
201
 
202
202
  /** Pointer on the tile (not the preview button or item menu): same as the preview button — select in selection mode, else open preview. */
203
203
  function handleTileClick(event: MouseEvent) {
204
- if (thumbnailOnly || isMissing || isFromMenuOrThumbControl(event)) return;
204
+ if (thumbnailOnly || isFromMenuOrThumbControl(event)) return;
205
+ if (isMissing && !allowSelecting) return;
205
206
  event.preventDefault();
206
207
  if (allowSelecting) {
207
208
  handleSelect(event);
@@ -228,14 +229,14 @@
228
229
  $: tileShellClass = [
229
230
  'flex w-full items-center gap-3 rounded-xl border border-border bg-background p-2 transition-colors duration-fast',
230
231
  thumbnailOnly ? 'h-auto w-auto border-0 bg-transparent p-0' : 'h-16',
231
- !thumbnailOnly && allowSelecting && !isMissing && !effectiveIsMobile && !isSelected
232
- ? 'hover:bg-accent group-data-[drag-hover=true]/file-tile:bg-accent has-[[data-state=open]]:bg-accent'
232
+ !thumbnailOnly && !effectiveIsMobile && !isSelected
233
+ ? 'hover:bg-brand-subtle group-data-[drag-hover=true]/file-tile:bg-brand-subtle has-[[data-state=open]]:bg-accent'
233
234
  : '',
234
- !thumbnailOnly && allowSelecting && !isMissing && !effectiveIsMobile && isSelected
235
+ !thumbnailOnly && !effectiveIsMobile && isSelected
235
236
  ? 'group-data-[drag-hover=true]/file-tile:bg-brand-subtle'
236
237
  : '',
237
238
  !thumbnailOnly && isSelected ? 'border-brand bg-brand-subtle ring-1 ring-inset ring-brand' : '',
238
- !thumbnailOnly && !isMissing ? 'cursor-pointer' : ''
239
+ !thumbnailOnly && (!isMissing || allowSelecting) ? 'cursor-pointer' : ''
239
240
  ]
240
241
  .filter(Boolean)
241
242
  .join(' ');
@@ -258,7 +259,7 @@
258
259
  <!-- Whole tile activates like the preview thumb; preview button remains the keyboard focus target. -->
259
260
  <div
260
261
  class={tileShellClass}
261
- onclick={!thumbnailOnly && !isMissing ? handleTileClick : undefined}
262
+ onclick={!thumbnailOnly ? handleTileClick : undefined}
262
263
  role="presentation"
263
264
  >
264
265
  <!-- 48×48 preview thumb (Figma File Thumb Large) -->
@@ -75,7 +75,7 @@
75
75
  >
76
76
  <!-- Tile activation mirrors the folder thumb; keyboard users use the existing open-folder control. -->
77
77
  <div
78
- class="flex h-16 w-full cursor-pointer items-center gap-3 rounded-xl border border-border bg-background p-2 transition-all duration-fast hover:bg-accent has-[[data-state=open]]:bg-accent group-data-[folder-drop-hover=true]:bg-accent group-data-[folder-drop-hover=true]:ring-2 group-data-[folder-drop-hover=true]:ring-brand"
78
+ class="flex h-16 w-full cursor-pointer items-center gap-3 rounded-xl border border-border bg-background p-2 transition-all duration-fast hover:bg-brand-subtle has-[[data-state=open]]:bg-accent group-data-[folder-drop-hover=true]:bg-brand-subtle group-data-[folder-drop-hover=true]:ring-2 group-data-[folder-drop-hover=true]:ring-brand"
79
79
  onclick={handleTileClick}
80
80
  role="presentation"
81
81
  >
@@ -193,7 +193,7 @@ export declare const FILE_BROWSER_MESSAGES: {
193
193
  readonly 'toast.delete.doneFolder': "Deleted folder \"{name}\"";
194
194
  readonly 'toast.delete.doneFile': "Deleted \"{name}\"";
195
195
  readonly 'toast.delete.doneMany': "{count, plural, one {Deleted # item} other {Deleted # items}}";
196
- readonly 'toast.delete.doneFolderDetail': "Folder and its contents were deleted successfully";
196
+ readonly 'toast.delete.doneFolderDetail': "Folder and its files were removed from your library";
197
197
  readonly 'toast.delete.doneFileDetail': "Item was deleted successfully";
198
198
  readonly 'toast.delete.doneManyDetail': "{count, plural, one {# item was deleted successfully} other {# items were deleted successfully}}";
199
199
  readonly 'toast.delete.doneNames': "Deleted: {names}";
@@ -202,7 +202,7 @@ export const FILE_BROWSER_MESSAGES = {
202
202
  'toast.delete.doneFolder': 'Deleted folder "{name}"',
203
203
  'toast.delete.doneFile': 'Deleted "{name}"',
204
204
  'toast.delete.doneMany': '{count, plural, one {Deleted # item} other {Deleted # items}}',
205
- 'toast.delete.doneFolderDetail': 'Folder and its contents were deleted successfully',
205
+ 'toast.delete.doneFolderDetail': 'Folder and its files were removed from your library',
206
206
  'toast.delete.doneFileDetail': 'Item was deleted successfully',
207
207
  'toast.delete.doneManyDetail': '{count, plural, one {# item was deleted successfully} other {# items were deleted successfully}}',
208
208
  'toast.delete.doneNames': 'Deleted: {names}',
@@ -1,10 +1,13 @@
1
1
  import { fileStore, sortCriteria, sortDirection, selectedFiles, currentFolder, fileFilter } from '../stores/fileStore';
2
2
  import { persistHistory } from '../stores/navigationStore';
3
+ import { getFileBrowserUploadConfig } from '../stores/uploadApiStore';
3
4
  import { get } from 'svelte/store';
4
5
  import { updateFolderCounts } from '../stores/folderCountStore';
5
6
  import { getFileType } from './fileUtils';
6
7
  import { getRenamedFileName } from './fileNames';
7
8
  import { ENDPOINTS } from './apiConfig';
9
+ import { collectFileIdsInSubtree, deleteSubtreeUploadsOnApi } from './widgeticDelete';
10
+ import { removePersistedUploads } from './userUploadsStorage';
8
11
  // Add helper function for sorting folder contents
9
12
  function sortFolderContents(items) {
10
13
  const currentSortCriteria = get(sortCriteria);
@@ -475,10 +478,16 @@ export async function deleteItem(itemId) {
475
478
  }
476
479
  }
477
480
  collectPaths(itemToDelete);
478
- // First call mock API
479
- const response = await mockDeleteAPI(itemId, Array.from(thumbnailsToDelete).join(','), Array.from(filesToDelete).join(','));
480
- if (!response.success) {
481
- throw new Error(response.error || 'Failed to delete item on server');
481
+ const uploadConfig = getFileBrowserUploadConfig();
482
+ const removedUploadIds = collectFileIdsInSubtree(itemToDelete);
483
+ if (uploadConfig?.accessToken && uploadConfig?.apiBasePath) {
484
+ await deleteSubtreeUploadsOnApi(uploadConfig, itemToDelete);
485
+ }
486
+ else {
487
+ const response = await mockDeleteAPI(itemId, Array.from(thumbnailsToDelete).join(','), Array.from(filesToDelete).join(','));
488
+ if (!response.success) {
489
+ throw new Error(response.error || 'Failed to delete item on server');
490
+ }
482
491
  }
483
492
  fileStore.update(store => {
484
493
  const deleteFromStructure = (items) => {
@@ -504,21 +513,12 @@ export async function deleteItem(itemId) {
504
513
  store.root.children = rootChildren;
505
514
  return store;
506
515
  });
507
- // If item was deleted successfully, remove it from selections
508
516
  if (success && itemToDelete) {
509
- // If it's a folder, get all file IDs within it to remove from selections
510
- const fileIdsToRemove = new Set();
511
- function collectFileIds(item) {
512
- if (item.type === 'file') {
513
- fileIdsToRemove.add(item.id);
514
- }
515
- else if (item.type === 'folder' && item.children) {
516
- item.children.forEach(child => collectFileIds(child));
517
- }
517
+ const fileIdsToRemove = new Set(removedUploadIds);
518
+ selectedFiles.update((files) => files.filter((file) => !fileIdsToRemove.has(file.id)));
519
+ if (uploadConfig?.accessToken && fileIdsToRemove.size > 0) {
520
+ await removePersistedUploads([...fileIdsToRemove]);
518
521
  }
519
- collectFileIds(itemToDelete);
520
- // Update selected files store
521
- selectedFiles.update(files => files.filter(file => !fileIdsToRemove.has(file.id)));
522
522
  }
523
523
  return success;
524
524
  }
@@ -2,6 +2,7 @@
2
2
  * Pure helpers for the Widgetic library-mode tree: persistence covers the whole root and API hydration merges by id.
3
3
  */
4
4
  import type { FileSystemItem } from '../types';
5
+ export declare const BUILTIN_UPLOADS_ID = "folder_my_uploads";
5
6
  /** Deep clone with Date revival for `modified` fields (JSON persistence). */
6
7
  export declare function reviveFileSystemDates(items: FileSystemItem[]): FileSystemItem[];
7
8
  export declare function findItemByIdInTree(root: FileSystemItem, id: string): FileSystemItem | null;
@@ -19,7 +20,11 @@ export declare function mergeApiFilesIntoSavedTree(rootChildren: FileSystemItem[
19
20
  /** Saved tree held only files with no folder wrapper (pre–whole-tree persistence). */
20
21
  export declare function isLegacyUploadsOnlyChildren(children: FileSystemItem[]): boolean;
21
22
  /**
22
- * One-step legacy migration: old persist stored only My Uploads' children under key `current`.
23
- * Wraps them inside `folder_my_uploads` at the root.
23
+ * One-step legacy migration: old persist stored only upload files under key `current` with no folder wrapper.
24
+ * They become loose files at the root — there is no built-in Uploads folder anymore.
24
25
  */
25
- export declare function migrateLegacyUploadsOnlyChildren(legacyChildren: FileSystemItem[], myUploadsName: string): FileSystemItem[];
26
+ export declare function migrateLegacyUploadsOnlyChildren(legacyChildren: FileSystemItem[], _myUploadsName: string): FileSystemItem[];
27
+ /**
28
+ * Unwraps the legacy built-in `folder_my_uploads` (and any nested uploads shells) so children live at the root.
29
+ */
30
+ export declare function flattenLegacyBuiltinUploads(children: FileSystemItem[]): FileSystemItem[];
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Pure helpers for the Widgetic library-mode tree: persistence covers the whole root and API hydration merges by id.
3
3
  */
4
- const BUILTIN_UPLOADS_ID = 'folder_my_uploads';
4
+ export const BUILTIN_UPLOADS_ID = 'folder_my_uploads';
5
5
  function sortFolderContentsLikeGrid(items, sort) {
6
6
  items.sort((a, b) => {
7
7
  if (a.type === 'folder' && b.type !== 'folder')
@@ -142,16 +142,30 @@ export function isLegacyUploadsOnlyChildren(children) {
142
142
  return children.every((c) => c.type === 'file');
143
143
  }
144
144
  /**
145
- * One-step legacy migration: old persist stored only My Uploads' children under key `current`.
146
- * Wraps them inside `folder_my_uploads` at the root.
145
+ * One-step legacy migration: old persist stored only upload files under key `current` with no folder wrapper.
146
+ * They become loose files at the root — there is no built-in Uploads folder anymore.
147
147
  */
148
- export function migrateLegacyUploadsOnlyChildren(legacyChildren, myUploadsName) {
149
- const uploadsFolder = {
150
- id: BUILTIN_UPLOADS_ID,
151
- name: myUploadsName,
152
- type: 'folder',
153
- children: dedupeTreeIds(reviveFileSystemDates(legacyChildren)),
154
- modified: new Date().toISOString()
155
- };
156
- return [uploadsFolder];
148
+ export function migrateLegacyUploadsOnlyChildren(legacyChildren, _myUploadsName) {
149
+ return dedupeTreeIds(reviveFileSystemDates(legacyChildren));
150
+ }
151
+ /**
152
+ * Unwraps the legacy built-in `folder_my_uploads` (and any nested uploads shells) so children live at the root.
153
+ */
154
+ export function flattenLegacyBuiltinUploads(children) {
155
+ const out = [];
156
+ for (const child of dedupeTreeIds(reviveFileSystemDates(children))) {
157
+ if (child.type === 'folder' && child.id === BUILTIN_UPLOADS_ID) {
158
+ if (child.children?.length) {
159
+ out.push(...flattenLegacyBuiltinUploads(child.children));
160
+ }
161
+ continue;
162
+ }
163
+ if (child.type === 'folder' && child.children?.length) {
164
+ out.push({ ...child, children: flattenLegacyBuiltinUploads(child.children) });
165
+ }
166
+ else {
167
+ out.push(child);
168
+ }
169
+ }
170
+ return out;
157
171
  }
@@ -1,5 +1,5 @@
1
- import { isLegacyUploadsOnlyChildren, mergeApiFilesIntoSavedTree, migrateLegacyUploadsOnlyChildren } from './libraryTree';
2
- import { CACHE_POLICIES, getCacheOwner, readEntity, writeEntity } from '@widgetic/cache-layer';
1
+ import { flattenLegacyBuiltinUploads, isLegacyUploadsOnlyChildren, mergeApiFilesIntoSavedTree, migrateLegacyUploadsOnlyChildren } from './libraryTree';
2
+ import { CACHE_POLICIES, ensureCacheOwnerFromSessionHint, getCacheOwner, readEntity, writeEntity } from '@widgetic/cache-layer';
3
3
  // Legacy localStorage keys, read once for migration then superseded by L1.
4
4
  const LEGACY_STORAGE_KEY = 'widgetic-file-browser-uploads';
5
5
  const LEGACY_LIBRARY_TREE_KEY = 'widgetic-file-browser-library-tree';
@@ -13,6 +13,7 @@ function entityKey() {
13
13
  return 'current';
14
14
  }
15
15
  function ownerIdOrNull() {
16
+ ensureCacheOwnerFromSessionHint();
16
17
  return getCacheOwner();
17
18
  }
18
19
  /**
@@ -203,12 +204,9 @@ export async function createUserUploadsFileSystemRoot(files, myUploadsName = 'Up
203
204
  const savedRaw = await loadLibraryTreeChildren();
204
205
  let savedChildren = null;
205
206
  if (savedRaw && savedRaw.length > 0) {
206
- const hasBuiltInUploads = savedRaw.some((c) => c.id === 'folder_my_uploads' && c.type === 'folder');
207
- savedChildren = hasBuiltInUploads
208
- ? savedRaw
209
- : isLegacyUploadsOnlyChildren(savedRaw)
210
- ? migrateLegacyUploadsOnlyChildren(savedRaw, myUploadsName)
211
- : savedRaw;
207
+ savedChildren = isLegacyUploadsOnlyChildren(savedRaw)
208
+ ? migrateLegacyUploadsOnlyChildren(savedRaw, myUploadsName)
209
+ : flattenLegacyBuiltinUploads(savedRaw);
212
210
  }
213
211
  const children = mergeApiFilesIntoSavedTree(savedChildren, files, myUploadsName);
214
212
  return {
@@ -0,0 +1,14 @@
1
+ import type { FileBrowserUploadConfig } from '../stores/uploadApiStore';
2
+ import type { FileSystemItem } from '../types';
3
+ /**
4
+ * Soft-deletes one upload row via DELETE /v1/uploads/:id.
5
+ */
6
+ export declare function deleteUploadFromWidgeticApi(config: FileBrowserUploadConfig, uploadId: string, options?: {
7
+ signal?: AbortSignal;
8
+ }): Promise<void>;
9
+ /** Every file id in a folder subtree (depth-first). */
10
+ export declare function collectFileIdsInSubtree(item: FileSystemItem): string[];
11
+ /** Deletes each upload in a folder tree via the Widgetic API, then returns all file ids removed. */
12
+ export declare function deleteSubtreeUploadsOnApi(config: FileBrowserUploadConfig, item: FileSystemItem, options?: {
13
+ signal?: AbortSignal;
14
+ }): Promise<string[]>;
@@ -0,0 +1,52 @@
1
+ import { MediaLibraryError, codeForHttpStatus } from '../mediaLibrary/errors';
2
+ function authHeaders(token) {
3
+ return { Authorization: `Bearer ${token.replace(/^Bearer\s+/i, '')}` };
4
+ }
5
+ /**
6
+ * Soft-deletes one upload row via DELETE /v1/uploads/:id.
7
+ */
8
+ export async function deleteUploadFromWidgeticApi(config, uploadId, options = {}) {
9
+ const basePath = config.apiBasePath.replace(/\/+$/, '');
10
+ const response = await fetch(`${basePath}/uploads/${encodeURIComponent(uploadId)}`, {
11
+ method: 'DELETE',
12
+ headers: authHeaders(config.accessToken),
13
+ signal: options.signal,
14
+ });
15
+ if (response.status === 404)
16
+ return;
17
+ if (!response.ok) {
18
+ let detail = `Delete upload failed (${response.status})`;
19
+ try {
20
+ const errJson = await response.json();
21
+ detail = errJson?.message || errJson?.error?.message || detail;
22
+ }
23
+ catch {
24
+ /* ignore */
25
+ }
26
+ throw new MediaLibraryError(codeForHttpStatus(response.status), detail, { status: response.status });
27
+ }
28
+ }
29
+ /** Every file id in a folder subtree (depth-first). */
30
+ export function collectFileIdsInSubtree(item) {
31
+ const ids = [];
32
+ function walk(node) {
33
+ if (node.type === 'file') {
34
+ ids.push(node.id);
35
+ return;
36
+ }
37
+ if (node.type === 'folder' && node.children) {
38
+ for (const child of node.children)
39
+ walk(child);
40
+ }
41
+ }
42
+ walk(item);
43
+ return ids;
44
+ }
45
+ /** Deletes each upload in a folder tree via the Widgetic API, then returns all file ids removed. */
46
+ export async function deleteSubtreeUploadsOnApi(config, item, options = {}) {
47
+ const fileIds = collectFileIdsInSubtree(item);
48
+ for (const id of fileIds) {
49
+ await deleteUploadFromWidgeticApi(config, id, options);
50
+ }
51
+ return fileIds;
52
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/file-browser",
3
- "version": "0.5.43",
3
+ "version": "0.5.44",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "repository": {