@widgetic/file-browser 0.5.44 → 0.5.46

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 (32) hide show
  1. package/dist/components/FolderTree.svelte.d.ts +2 -1
  2. package/dist/components/core/Dropzone.svelte +15 -28
  3. package/dist/components/core/FileBrowser.svelte +86 -110
  4. package/dist/components/core/Header.svelte +30 -39
  5. package/dist/components/core/RecentFiles.svelte +7 -37
  6. package/dist/components/core/RecentFiles.svelte.d.ts +1 -0
  7. package/dist/components/core/SearchDropdown.svelte +88 -26
  8. package/dist/components/core/SearchDropdown.svelte.d.ts +2 -0
  9. package/dist/components/core/UploadPanel.svelte +19 -24
  10. package/dist/components/items/FileItem.svelte +2 -2
  11. package/dist/components/items/FolderItem.svelte +1 -1
  12. package/dist/components/previews/FilePreview.svelte +44 -64
  13. package/dist/components/previews/PreviewHeaderBar.svelte +1 -1
  14. package/dist/components/ui/DragSelect.svelte +1 -1
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.js +2 -1
  17. package/dist/stores/fileStore.d.ts +2 -2
  18. package/dist/types.d.ts +2 -0
  19. package/dist/utils/brandKitLibraryTree.d.ts +23 -0
  20. package/dist/utils/brandKitLibraryTree.js +135 -0
  21. package/dist/utils/fileGoneProbe.d.ts +21 -0
  22. package/dist/utils/fileGoneProbe.js +37 -0
  23. package/dist/utils/gridLayout.d.ts +14 -1
  24. package/dist/utils/gridLayout.js +27 -2
  25. package/dist/utils/libraryTree.js +13 -2
  26. package/dist/utils/previewListNavigation.d.ts +10 -0
  27. package/dist/utils/previewListNavigation.js +39 -0
  28. package/dist/utils/recentFilesLimit.js +2 -5
  29. package/dist/utils/searchDropdownPhase.d.ts +17 -0
  30. package/dist/utils/searchDropdownPhase.js +23 -0
  31. package/dist/utils/widgeticUpload.js +2 -0
  32. package/package.json +1 -1
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Places brand-kit upload ids into the Widgetic library tree with stable folder names.
3
+ */
4
+ import { dedupeTreeIds, findItemByIdInTree } from './libraryTree';
5
+ export const BRAND_KIT_ROOT_NAME = 'Brand kit';
6
+ export const BRAND_KIT_FONTS_FOLDER = 'Fonts';
7
+ export const BRAND_KIT_LOGOS_FOLDER = 'Logos';
8
+ function folderIdFor(path) {
9
+ return `fld_brand_${path.map((p) => p.toLowerCase().replace(/\s+/g, '_')).join('/')}`;
10
+ }
11
+ function cloneChildren(children) {
12
+ return children.map((item) => ({
13
+ ...item,
14
+ children: item.children ? cloneChildren(item.children) : undefined
15
+ }));
16
+ }
17
+ function namesInFolder(children) {
18
+ const out = new Set();
19
+ for (const item of children) {
20
+ if (item.type === 'file')
21
+ out.add(item.name.toLowerCase());
22
+ }
23
+ return out;
24
+ }
25
+ /** `name (2).ext` when another file in the folder already uses `name.ext`. */
26
+ export function resolveCollisionFileName(desiredName, takenLower) {
27
+ if (!takenLower.has(desiredName.toLowerCase()))
28
+ return desiredName;
29
+ const match = /^(.+?)(\.[^.]+)?$/.exec(desiredName);
30
+ const stem = match?.[1] ?? desiredName;
31
+ const ext = match?.[2] ?? '';
32
+ let n = 2;
33
+ for (;;) {
34
+ const candidate = `${stem} (${n})${ext}`;
35
+ if (!takenLower.has(candidate.toLowerCase()))
36
+ return candidate;
37
+ n += 1;
38
+ }
39
+ }
40
+ function findChildFolder(children, name) {
41
+ const lower = name.toLowerCase();
42
+ for (const child of children) {
43
+ if (child.type === 'folder' && child.name.toLowerCase() === lower)
44
+ return child;
45
+ }
46
+ return null;
47
+ }
48
+ function ensureFolderPath(rootChildren, path) {
49
+ const next = dedupeTreeIds(cloneChildren(rootChildren));
50
+ let children = next;
51
+ for (let i = 0; i < path.length; i++) {
52
+ const segment = path[i];
53
+ let folder = findChildFolder(children, segment);
54
+ if (!folder) {
55
+ folder = {
56
+ id: folderIdFor(path.slice(0, i + 1)),
57
+ name: segment,
58
+ type: 'folder',
59
+ children: []
60
+ };
61
+ children.push(folder);
62
+ }
63
+ if (!folder.children)
64
+ folder.children = [];
65
+ children = folder.children;
66
+ }
67
+ return next;
68
+ }
69
+ function removeFileById(items, id) {
70
+ const out = [];
71
+ for (const item of items) {
72
+ if (item.type === 'file' && item.id === id)
73
+ continue;
74
+ if (item.type === 'folder' && item.children?.length) {
75
+ out.push({ ...item, children: removeFileById(item.children, id) });
76
+ }
77
+ else {
78
+ out.push(item);
79
+ }
80
+ }
81
+ return out;
82
+ }
83
+ function folderChildrenAtPath(rootChildren, path) {
84
+ let children = rootChildren;
85
+ for (const segment of path) {
86
+ const folder = findChildFolder(children, segment);
87
+ if (!folder)
88
+ return null;
89
+ if (!folder.children)
90
+ folder.children = [];
91
+ children = folder.children;
92
+ }
93
+ return children;
94
+ }
95
+ export function fontFamilyFolderPath(family) {
96
+ return [BRAND_KIT_ROOT_NAME, BRAND_KIT_FONTS_FOLDER, family];
97
+ }
98
+ export function brandLogoFolderPath() {
99
+ return [BRAND_KIT_ROOT_NAME, BRAND_KIT_LOGOS_FOLDER];
100
+ }
101
+ /**
102
+ * Moves or inserts a file into the tree under `folderPath`, setting `name` to `displayName` (collision suffix applied).
103
+ */
104
+ export function placeBrandKitFileInTree(rootChildren, input) {
105
+ let tree = ensureFolderPath(rootChildren ?? [], input.folderPath);
106
+ tree = removeFileById(tree, input.uploadId);
107
+ const targetChildren = folderChildrenAtPath(tree, input.folderPath);
108
+ if (!targetChildren)
109
+ return tree;
110
+ const taken = namesInFolder(targetChildren);
111
+ const name = resolveCollisionFileName(input.displayName, taken);
112
+ const file = {
113
+ id: input.uploadId,
114
+ name,
115
+ type: 'file',
116
+ modified: input.file?.modified ?? new Date(),
117
+ size: input.file?.size,
118
+ url: input.file?.url,
119
+ mimeType: input.file?.mimeType
120
+ };
121
+ targetChildren.push(file);
122
+ return dedupeTreeIds(tree);
123
+ }
124
+ /** Removes a file id wherever it sits in the tree (optimistic delete). */
125
+ export function removeBrandKitFileFromTree(rootChildren, uploadId) {
126
+ if (!rootChildren?.length)
127
+ return [];
128
+ return dedupeTreeIds(removeFileById(rootChildren, uploadId));
129
+ }
130
+ export function treeContainsUploadId(rootChildren, uploadId) {
131
+ if (!rootChildren?.length)
132
+ return false;
133
+ const root = { id: 'root', name: 'Root', type: 'folder', children: rootChildren };
134
+ return Boolean(findItemByIdInTree(root, uploadId));
135
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Decides whether a file is really gone from its address, before the browser removes it from the list.
3
+ *
4
+ * Why this exists: the preview of a font used to ask `fetch(url, { method: 'HEAD' })` whether the file was still there, and treated any
5
+ * failure as "gone". The CDN answers HEAD without CORS headers (and its CORS rule allows GET only), so from the site the browser
6
+ * blocked every HEAD, the check read "gone", and the file was evicted from the list and from the saved copy: the font and its Recent
7
+ * card disappeared the moment it was clicked, and came back after a refresh (the API still had it).
8
+ *
9
+ * The rule now: only an answer from the server that says the file is not there (404 or 410) means gone. A request the browser
10
+ * blocked, a network error or any other status says nothing about the file, so the file stays and its preview shows the error state.
11
+ * The request is a GET for the first byte (CORS is allowed for GET) so it works across origins.
12
+ */
13
+ type FetchLike = (input: string, init?: RequestInit) => Promise<Pick<Response, 'status'>>;
14
+ /**
15
+ * `true` only when the server answered that the file does not exist; `false` for every other outcome (found, blocked, offline).
16
+ *
17
+ * @param fileUrl - The address of the file.
18
+ * @param fetchImplementation - `fetch`, replaceable in tests.
19
+ */
20
+ export declare function isFileGone(fileUrl: string | undefined, fetchImplementation?: FetchLike): Promise<boolean>;
21
+ export {};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Decides whether a file is really gone from its address, before the browser removes it from the list.
3
+ *
4
+ * Why this exists: the preview of a font used to ask `fetch(url, { method: 'HEAD' })` whether the file was still there, and treated any
5
+ * failure as "gone". The CDN answers HEAD without CORS headers (and its CORS rule allows GET only), so from the site the browser
6
+ * blocked every HEAD, the check read "gone", and the file was evicted from the list and from the saved copy: the font and its Recent
7
+ * card disappeared the moment it was clicked, and came back after a refresh (the API still had it).
8
+ *
9
+ * The rule now: only an answer from the server that says the file is not there (404 or 410) means gone. A request the browser
10
+ * blocked, a network error or any other status says nothing about the file, so the file stays and its preview shows the error state.
11
+ * The request is a GET for the first byte (CORS is allowed for GET) so it works across origins.
12
+ */
13
+ /** Status codes that say the file is no longer at its address. */
14
+ const GONE_STATUS_CODES = new Set([404, 410]);
15
+ /**
16
+ * `true` only when the server answered that the file does not exist; `false` for every other outcome (found, blocked, offline).
17
+ *
18
+ * @param fileUrl - The address of the file.
19
+ * @param fetchImplementation - `fetch`, replaceable in tests.
20
+ */
21
+ export async function isFileGone(fileUrl, fetchImplementation = (input, init) => fetch(input, init)) {
22
+ // Without an address there is nothing to ask: the file is not proven gone, and nothing is removed because of it.
23
+ if (!fileUrl)
24
+ return false;
25
+ try {
26
+ const response = await fetchImplementation(fileUrl, {
27
+ method: 'GET',
28
+ headers: { Range: 'bytes=0-0' }
29
+ });
30
+ return GONE_STATUS_CODES.has(response.status);
31
+ }
32
+ catch (error) {
33
+ // A blocked or failed request is not proof: keep the file.
34
+ console.warn('[fileGoneProbe] Could not ask whether the file still exists; keeping it:', fileUrl, error);
35
+ return false;
36
+ }
37
+ }
@@ -1,2 +1,15 @@
1
- /** Grid column count from the file browser container width (Figma File Browser grid). */
1
+ /**
2
+ * Grid column count from the file browser panel width (Figma File Tile ~264px, 16px gap).
3
+ * At 1152px panel width → 4 columns; scales up to 6 on very wide panels.
4
+ */
5
+ export declare const GRID_TILE_MIN_WIDTH_PX = 264;
6
+ export declare const GRID_GAP_PX = 16;
7
+ export declare const GRID_MAX_COLUMNS = 6;
8
+ /** Same rhythm for the recent-files strip (Figma 24px gap, ~3 cards at 1152px). */
9
+ export declare const RECENT_TILE_MIN_WIDTH_PX = 352;
10
+ export declare const RECENT_GAP_PX = 24;
11
+ export declare const RECENT_MAX_COLUMNS = 5;
12
+ /** Main folder/file grid. */
2
13
  export declare function gridColumnsForWidth(width: number): number;
14
+ /** Recent files row — fewer columns at the same width (wider cards). */
15
+ export declare function recentGridColumnsForWidth(width: number): number;
@@ -1,4 +1,21 @@
1
- /** Grid column count from the file browser container width (Figma File Browser grid). */
1
+ /**
2
+ * Grid column count from the file browser panel width (Figma File Tile ~264px, 16px gap).
3
+ * At 1152px panel width → 4 columns; scales up to 6 on very wide panels.
4
+ */
5
+ export const GRID_TILE_MIN_WIDTH_PX = 264;
6
+ export const GRID_GAP_PX = 16;
7
+ export const GRID_MAX_COLUMNS = 6;
8
+ /** Same rhythm for the recent-files strip (Figma 24px gap, ~3 cards at 1152px). */
9
+ export const RECENT_TILE_MIN_WIDTH_PX = 352;
10
+ export const RECENT_GAP_PX = 24;
11
+ export const RECENT_MAX_COLUMNS = 5;
12
+ function columnsForWidth(width, minTile, gap, maxColumns) {
13
+ if (width < 420)
14
+ return 1;
15
+ const columns = Math.floor((width + gap) / (minTile + gap));
16
+ return Math.min(maxColumns, Math.max(1, columns));
17
+ }
18
+ /** Main folder/file grid. */
2
19
  export function gridColumnsForWidth(width) {
3
20
  if (width < 420)
4
21
  return 1;
@@ -6,5 +23,13 @@ export function gridColumnsForWidth(width) {
6
23
  return 2;
7
24
  if (width < 1000)
8
25
  return 3;
9
- return 4;
26
+ return columnsForWidth(width, GRID_TILE_MIN_WIDTH_PX, GRID_GAP_PX, GRID_MAX_COLUMNS);
27
+ }
28
+ /** Recent files row — fewer columns at the same width (wider cards). */
29
+ export function recentGridColumnsForWidth(width) {
30
+ if (width < 700)
31
+ return 2;
32
+ if (width < 1000)
33
+ return 3;
34
+ return columnsForWidth(width, RECENT_TILE_MIN_WIDTH_PX, RECENT_GAP_PX, RECENT_MAX_COLUMNS);
10
35
  }
@@ -1,6 +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
+ import { placeBrandKitFileInTree } from './brandKitLibraryTree.js';
4
5
  export const BUILTIN_UPLOADS_ID = 'folder_my_uploads';
5
6
  function sortFolderContentsLikeGrid(items, sort) {
6
7
  items.sort((a, b) => {
@@ -98,8 +99,9 @@ export function mergeApiFilesIntoSavedTree(rootChildren, apiFiles, _myUploadsNam
98
99
  for (let i = 0; i < items.length; i++) {
99
100
  const it = items[i];
100
101
  if (it.type === 'file' && it.id === id) {
101
- // The server owns the file (url, size, thumbnail), the visitor owns its name: a rename stays after a reload
102
- items[i] = { ...file, name: it.name, modified: ensureDate(file.modified) };
102
+ // Brand-kit uploads keep the server file name; other files keep a visitor rename.
103
+ const name = file.libraryFolderPath ? file.name : it.name;
104
+ items[i] = { ...file, name, modified: ensureDate(file.modified) };
103
105
  return true;
104
106
  }
105
107
  if (it.type === 'folder' && it.children?.length) {
@@ -125,6 +127,15 @@ export function mergeApiFilesIntoSavedTree(rootChildren, apiFiles, _myUploadsNam
125
127
  if (findItemByIdInTree(rootFolder, file.id)) {
126
128
  replaceFileById(rootFolder.children, file.id, normalized);
127
129
  }
130
+ else if (file.libraryFolderPath) {
131
+ const placed = placeBrandKitFileInTree(rootFolder.children, {
132
+ uploadId: file.id,
133
+ displayName: file.name,
134
+ folderPath: file.libraryFolderPath.split('/').filter(Boolean),
135
+ file: normalized
136
+ });
137
+ rootFolder.children = placed;
138
+ }
128
139
  else if (!rootFolder.children.some((c) => c.type === 'file' && c.id === file.id)) {
129
140
  rootFolder.children.push(normalized);
130
141
  sortFolderContentsLikeGrid(rootFolder.children, {
@@ -0,0 +1,10 @@
1
+ import type { FileSystemItem } from '../types';
2
+ /** Previewable items in display order (folders omitted). */
3
+ export declare function previewNavigationFiles(items: FileSystemItem[]): FileSystemItem[];
4
+ export declare function previewNavigationIndex(list: FileSystemItem[], fileId: string): number;
5
+ /**
6
+ * Next file in the preview list, wrapping at both ends. Skips missing ids when provided.
7
+ * Returns null when there is no navigable file (empty list or every peer missing).
8
+ */
9
+ export declare function stepPreviewNavigation(list: FileSystemItem[], currentId: string, direction: 'next' | 'prev', missingIds?: ReadonlySet<string>): FileSystemItem | null;
10
+ export declare function hasPreviewNavigation(list: FileSystemItem[], missingIds?: ReadonlySet<string>): boolean;
@@ -0,0 +1,39 @@
1
+ /** Previewable items in display order (folders omitted). */
2
+ export function previewNavigationFiles(items) {
3
+ return items.filter((item) => item.type === 'file');
4
+ }
5
+ export function previewNavigationIndex(list, fileId) {
6
+ return list.findIndex((item) => item.id === fileId);
7
+ }
8
+ /**
9
+ * Next file in the preview list, wrapping at both ends. Skips missing ids when provided.
10
+ * Returns null when there is no navigable file (empty list or every peer missing).
11
+ */
12
+ export function stepPreviewNavigation(list, currentId, direction, missingIds = new Set()) {
13
+ const files = previewNavigationFiles(list);
14
+ if (files.length <= 1)
15
+ return null;
16
+ let index = previewNavigationIndex(files, currentId);
17
+ if (index < 0)
18
+ index = 0;
19
+ const total = files.length;
20
+ for (let step = 0; step < total; step++) {
21
+ if (direction === 'next') {
22
+ index = (index + 1) % total;
23
+ }
24
+ else {
25
+ index = index > 0 ? index - 1 : total - 1;
26
+ }
27
+ const candidate = files[index];
28
+ if (candidate.id !== currentId && !missingIds.has(candidate.id)) {
29
+ return candidate;
30
+ }
31
+ }
32
+ // Wrapped full cycle with only the current file available
33
+ const current = files.find((f) => f.id === currentId);
34
+ return current && !missingIds.has(current.id) ? current : null;
35
+ }
36
+ export function hasPreviewNavigation(list, missingIds = new Set()) {
37
+ const files = previewNavigationFiles(list).filter((f) => !missingIds.has(f.id));
38
+ return files.length > 1;
39
+ }
@@ -1,3 +1,4 @@
1
+ import { recentGridColumnsForWidth } from './gridLayout';
1
2
  /** Breakpoints shared by the main grid and the Recent strip (Figma desktop / tablet). */
2
3
  export const RECENT_FILES_DESKTOP_BREAKPOINT = 1156;
3
4
  export const RECENT_FILES_TABLET_BREAKPOINT = 744;
@@ -6,12 +7,8 @@ export const RECENT_FILES_TABLET_BREAKPOINT = 744;
6
7
  * One rule for FileBrowser and RecentFiles so the strip matches `getRecentFiles()`.
7
8
  */
8
9
  export function recentFilesLimitForWidth(containerWidth) {
9
- if (containerWidth > RECENT_FILES_DESKTOP_BREAKPOINT) {
10
- const gridColumns = Math.min(6, Math.floor(containerWidth / 300));
11
- return gridColumns * 2;
12
- }
13
10
  if (containerWidth > RECENT_FILES_TABLET_BREAKPOINT) {
14
- return 6;
11
+ return recentGridColumnsForWidth(containerWidth) * 2;
15
12
  }
16
13
  return 4;
17
14
  }
@@ -0,0 +1,17 @@
1
+ export type SearchDropdownPhase = 'idle' | 'loading' | 'results' | 'empty';
2
+ export type SearchDropdownPhaseInput = {
3
+ panelOpen: boolean;
4
+ trimmedTerm: string;
5
+ /** The term the debounced search last finished for (empty until first completion). */
6
+ settledTerm: string;
7
+ /** True while a debounced search is in flight for trimmedTerm. */
8
+ queryInFlight: boolean;
9
+ resultCount: number;
10
+ };
11
+ /**
12
+ * When the panel is open with text: never show the empty card while the query for the current text is pending.
13
+ * `empty` only after the settled term matches the typed term and the result list is empty.
14
+ */
15
+ export declare function resolveSearchDropdownPhase(input: SearchDropdownPhaseInput): SearchDropdownPhase;
16
+ export declare function shouldShowSearchEmptyState(phase: SearchDropdownPhase): boolean;
17
+ export declare function shouldShowSearchResultsList(phase: SearchDropdownPhase, resultCount: number): boolean;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * When the panel is open with text: never show the empty card while the query for the current text is pending.
3
+ * `empty` only after the settled term matches the typed term and the result list is empty.
4
+ */
5
+ export function resolveSearchDropdownPhase(input) {
6
+ const { panelOpen, trimmedTerm, settledTerm, queryInFlight, resultCount } = input;
7
+ if (!panelOpen || !trimmedTerm)
8
+ return 'idle';
9
+ if (queryInFlight || settledTerm !== trimmedTerm) {
10
+ if (resultCount > 0)
11
+ return 'results';
12
+ return 'loading';
13
+ }
14
+ if (resultCount > 0)
15
+ return 'results';
16
+ return 'empty';
17
+ }
18
+ export function shouldShowSearchEmptyState(phase) {
19
+ return phase === 'empty';
20
+ }
21
+ export function shouldShowSearchResultsList(phase, resultCount) {
22
+ return resultCount > 0 && (phase === 'results' || phase === 'loading');
23
+ }
@@ -58,6 +58,7 @@ export async function fetchUserUploadsFromApi(config, options = {}) {
58
58
  const fileName = (row.file_name || row.fileName || 'upload');
59
59
  const url = row.url;
60
60
  const mime = inferImageMime((row.mime_type || row.mimeType || ''), fileName, url);
61
+ const libraryFolderPath = (row.library_folder_path ?? row.libraryFolderPath ?? null);
61
62
  return {
62
63
  id: row.id,
63
64
  name: fileName,
@@ -67,6 +68,7 @@ export async function fetchUserUploadsFromApi(config, options = {}) {
67
68
  url,
68
69
  thumbnail: mime.startsWith('image/') ? url : undefined,
69
70
  mimeType: mime || undefined,
71
+ ...(libraryFolderPath ? { libraryFolderPath } : {}),
70
72
  };
71
73
  });
72
74
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/file-browser",
3
- "version": "0.5.44",
3
+ "version": "0.5.46",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "repository": {