feat: show sync status and Show in Explorer for synced files on the Files screen

This commit is contained in:
Linus Rath
2026-11-04 16:40:13 +01:00
parent 81a679a260
commit 18c42d2d79
5 changed files with 312 additions and 0 deletions
@@ -0,0 +1,202 @@
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FileBrowser } from '@/components/files/file-browser';
import { FileDetailsPanel } from '@/components/files/file-details-panel';
import { useFileStore, type FileResource } from '@/stores/file-store';
import { useFilesSyncStore } from '@/stores/files-sync-store';
import type { BulwarkDesktopBridge } from '@/lib/desktop/types';
import type { FilesSyncController, FilesSyncItemStatus } from '@/lib/files-sync/types';
import type { IJMAPClient } from '@/lib/jmap/client-interface';
// Files on this computer on the Files screen: "Show in Explorer" (Finder, file
// manager) for what a root covers, and the sync status on rows and in the
// details panel. The next-intl mock returns keys.
vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } }));
vi.mock('@/components/settings/share-collection-dialog', () => ({ ShareCollectionDialog: () => null }));
const NOTES = {
id: 'f-notes', name: 'notes.txt', serverName: 'notes.txt', isDirectory: false, contentType: 'text/plain',
contentLength: 10, lastModified: '2026-10-01T00:00:00Z', blobId: 'b-notes', parentId: null,
} as FileResource;
const PLANS = {
id: 'd-plans', name: 'Plans', serverName: 'Plans', isDirectory: true, contentType: '',
contentLength: 0, lastModified: '2026-10-01T00:00:00Z', blobId: null, parentId: null,
} as unknown as FileResource;
function controller(covered: string[]) {
return {
coverage: vi.fn((id: string) => (covered.includes(id) ? { rootId: 'r1', kind: 'folder' as const, path: id } : null)),
showInFolder: vi.fn(async () => true),
} as unknown as FilesSyncController & { coverage: ReturnType<typeof vi.fn>; showInFolder: ReturnType<typeof vi.fn> };
}
function setPlatform(platform: 'win32' | 'darwin' | 'linux') {
window.bulwarkDesktop = { version: 1, platform } as unknown as BulwarkDesktopBridge;
}
function renderBrowser(resources: FileResource[] = [NOTES, PLANS]) {
const client = { listAllFileNodesAcrossAccounts: vi.fn(async () => []) } as unknown as IJMAPClient;
act(() => {
useFileStore.setState({ client, sharedRoots: [], allFolders: [], currentParentId: null, pathStack: [{ id: null, name: '' }], hasListed: true });
});
const noop = vi.fn(async () => {});
render(
<FileBrowser
currentPath="/"
resources={resources}
isLoading={false}
error={null}
selectedResources={new Set()}
uploadProgress={null}
clipboard={null}
onCreateFolder={noop}
onUploadFiles={noop}
onUploadFolder={noop}
onCancelUpload={vi.fn()}
onDelete={noop}
onBatchDelete={noop}
onRename={noop}
onBatchDownload={noop}
onRefresh={noop}
onClearSelection={vi.fn()}
onCut={vi.fn()}
onCopy={vi.fn()}
onPaste={noop}
onMoveTo={noop}
onPreviewImage={vi.fn()}
onCreateFile={noop}
onDuplicate={noop}
getImageUrl={async () => ''}
favorites={[]}
recentFiles={[]}
onToggleFavorite={vi.fn()}
onOpenRecent={vi.fn()}
client={client}
ownAccountId="a"
onNavigate={vi.fn()}
onSetSelection={vi.fn()}
onToggleSelect={vi.fn()}
onPreviewFile={vi.fn()}
onDownload={noop}
onRenameNode={noop}
onDeleteNode={noop}
onDownloadNode={noop}
onRevealNode={noop}
onRemoveRecent={vi.fn()}
/>,
);
}
function moreButton(name: string) {
return screen.getAllByRole('button', { name: 'more_actions' }).find((b) => b.closest('[data-resource]')?.getAttribute('data-resource') === name)!;
}
afterEach(() => {
cleanup();
window.bulwarkDesktop = undefined;
useFilesSyncStore.getState().reset();
});
describe('Show in Explorer on the Files screen', () => {
it('is in the row menu of a covered file and folder only, and opens it there', () => {
setPlatform('win32');
const c = controller(['f-notes', 'd-plans']);
useFilesSyncStore.setState({ available: true, controller: c });
renderBrowser();
fireEvent.click(moreButton('notes.txt'));
const item = within(screen.getByRole('menu')).getByRole('menuitem', { name: 'show_in.explorer' });
fireEvent.click(item);
expect(c.showInFolder).toHaveBeenCalledWith('f-notes');
expect(screen.queryByRole('menu')).toBeNull();
fireEvent.click(moreButton('Plans'));
fireEvent.click(within(screen.getByRole('menu')).getByRole('menuitem', { name: 'show_in.explorer' }));
expect(c.showInFolder).toHaveBeenLastCalledWith('d-plans');
});
it('is not offered for what no root covers, nor outside the app', () => {
setPlatform('win32');
useFilesSyncStore.setState({ available: true, controller: controller(['d-plans']) });
renderBrowser();
fireEvent.click(moreButton('notes.txt'));
expect(within(screen.getByRole('menu')).queryByRole('menuitem', { name: 'show_in.explorer' })).toBeNull();
cleanup();
useFilesSyncStore.setState({ available: false, controller: controller(['f-notes']) });
renderBrowser();
fireEvent.click(moreButton('notes.txt'));
expect(within(screen.getByRole('menu')).queryByRole('menuitem', { name: /show_in/ })).toBeNull();
});
it.each([
['darwin', 'show_in.finder'],
['linux', 'show_in.file_manager'],
] as const)('is named for the platform: %s', (platform, label) => {
setPlatform(platform);
useFilesSyncStore.setState({ available: true, controller: controller(['f-notes']) });
renderBrowser([NOTES]);
fireEvent.click(moreButton('notes.txt'));
expect(within(screen.getByRole('menu')).getByRole('menuitem', { name: label })).toBeInTheDocument();
});
});
describe('sync status on the Files screen', () => {
it.each<FilesSyncItemStatus>(['synced', 'syncing', 'pending', 'error', 'online-only'])('names a %s row', (state) => {
useFilesSyncStore.setState({ available: true, controller: controller([]), items: { 'f-notes': state } });
renderBrowser([NOTES, PLANS]);
const row = document.querySelector('[data-resource="notes.txt"]') as HTMLElement;
expect(within(row).getByRole('img', { name: `item.${state}` })).toBeInTheDocument();
// Plans has no status: no badge.
const plans = document.querySelector('[data-resource="Plans"]') as HTMLElement;
expect(plans.querySelector('[data-files-sync-item]')).toBeNull();
});
it('shows nothing outside the app', () => {
useFilesSyncStore.setState({ available: false, items: { 'f-notes': 'synced' } });
renderBrowser([NOTES]);
expect(document.querySelector('[data-files-sync-item]')).toBeNull();
});
});
describe('details panel', () => {
function renderPanel() {
render(
<FileDetailsPanel
resource={NOTES}
selection={[NOTES]}
folderName="My files"
folderItems={[NOTES]}
path="/notes.txt"
isStarred={false}
canShare={false}
canPreview={false}
canEdit={false}
iconOptions={{ showIcons: true, coloredIcons: true, showThumbnails: false }}
getImageUrl={async () => ''}
onClose={vi.fn()}
onOpen={vi.fn()}
onEdit={vi.fn()}
onShare={vi.fn()}
onToggleStar={vi.fn()}
/>,
);
}
it('says the status and offers Show in Finder for a covered file', () => {
setPlatform('darwin');
const c = controller(['f-notes']);
useFilesSyncStore.setState({ available: true, controller: c, items: { 'f-notes': 'pending' } });
renderPanel();
expect(screen.getByText('item.label')).toBeInTheDocument();
expect(screen.getByText('item.pending')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'show_in.finder' }));
expect(c.showInFolder).toHaveBeenCalledWith('f-notes');
});
it('has neither for a file no root covers', () => {
setPlatform('win32');
useFilesSyncStore.setState({ available: true, controller: controller([]) });
renderPanel();
expect(screen.queryByText('item.label')).toBeNull();
expect(screen.queryByRole('button', { name: /show_in/ })).toBeNull();
});
});
+102
View File
@@ -0,0 +1,102 @@
"use client";
import { useTranslations } from "next-intl";
import { AlertCircle, CheckCircle2, Clock, Cloud, FolderOpen, RefreshCw, type AppIcon } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { ContextMenuItem } from "@/components/ui/context-menu";
import { getDesktopBridge } from "@/lib/desktop/bridge";
import { cn } from "@/lib/utils";
import type { FilesSyncItemStatus } from "@/lib/files-sync/types";
import { useFilesSyncStore } from "@/stores/files-sync-store";
import { toast } from "@/stores/toast-store";
import { showInKey } from "./files-sync-text";
/*
* Files on this computer, on the Files screen: "Show in Explorer" (Finder, file
* manager) on a file or folder a synced folder or the drive covers, and its sync
* status on rows and in the details panel. All of it reads stores/files-sync-store.ts
* and calls the engine's controller; nothing shows outside the desktop app.
*/
const ITEM_ICONS: Record<FilesSyncItemStatus, { icon: AppIcon; className: string }> = {
synced: { icon: CheckCircle2, className: "text-green-600 dark:text-green-400" },
syncing: { icon: RefreshCw, className: "text-primary animate-spin motion-reduce:animate-none" },
pending: { icon: Clock, className: "text-muted-foreground" },
error: { icon: AlertCircle, className: "text-destructive" },
"online-only": { icon: Cloud, className: "text-muted-foreground" },
};
/** The node's sync status, when the engine has one for it. */
function useItemStatus(nodeId: string): FilesSyncItemStatus | null {
return useFilesSyncStore((s) => (s.available ? s.items[nodeId] ?? null : null));
}
/** "Show in Explorer" for a node a root covers, or null. */
export function useShowInFolder(nodeId: string | null | undefined): { label: string; run: () => void } | null {
const t = useTranslations("files_sync");
const available = useFilesSyncStore((s) => s.available);
const controller = useFilesSyncStore((s) => s.controller);
// Coverage changes with the roots and what the engine knows of the tree.
useFilesSyncStore((s) => s.roots);
useFilesSyncStore((s) => s.items);
if (!available || !controller || !nodeId) return null;
if (!controller.coverage(nodeId)) return null;
return {
label: t(showInKey(getDesktopBridge()?.platform)),
run: () => {
void controller.showInFolder(nodeId).then(
(shown) => { if (!shown) toast.error(t("show_in.failed")); },
() => toast.error(t("show_in.failed")),
);
},
};
}
/** The menu entry of a row on the Files screen. */
export function ShowInFolderMenuItem({ nodeId, onRan }: { nodeId: string; onRan: () => void }) {
const showIn = useShowInFolder(nodeId);
if (!showIn) return null;
return <ContextMenuItem icon={FolderOpen} label={showIn.label} testId="files-sync-show-in" onClick={() => { onRan(); showIn.run(); }} />;
}
/** The same in the details panel's buttons. */
export function ShowInFolderButton({ nodeId }: { nodeId: string }) {
const showIn = useShowInFolder(nodeId);
if (!showIn) return null;
return (
<Button size="sm" variant="outline" className="h-8 gap-1.5" onClick={showIn.run} data-testid="files-sync-show-in">
<FolderOpen className="w-4 h-4" />{showIn.label}
</Button>
);
}
/** A small icon on a row, named for screen readers and on hover. */
export function FilesSyncBadge({ nodeId, className }: { nodeId: string; className?: string }) {
const t = useTranslations("files_sync");
const status = useItemStatus(nodeId);
if (!status) return null;
const { icon: Icon, className: iconClass } = ITEM_ICONS[status];
const label = t(`item.${status}`);
return (
<span role="img" aria-label={label} title={label} className="inline-flex shrink-0" data-files-sync-item={status}>
<Icon className={cn("w-3.5 h-3.5", iconClass, className)} aria-hidden="true" />
</span>
);
}
/** "On this computer: Synced", a row of the details panel's list. */
export function FilesSyncDetailsRow({ nodeId }: { nodeId: string }) {
const t = useTranslations("files_sync");
const status = useItemStatus(nodeId);
if (!status) return null;
const { icon: Icon, className: iconClass } = ITEM_ICONS[status];
return (
<div data-files-sync-item={status}>
<dt className="text-xs text-muted-foreground">{t("item.label")}</dt>
<dd className="flex items-center gap-1.5">
<Icon className={cn("w-3.5 h-3.5 shrink-0", iconClass)} aria-hidden="true" />
{t(`item.${status}`)}
</dd>
</div>
);
}
+2
View File
@@ -28,6 +28,7 @@ import { FilesSidebar, type CreateKind } from "@/components/files/files-sidebar"
import { FilesHeader, type Crumb, type SortDir, type SortKey, type ViewMode } from "@/components/files/files-header";
import { FileGridView, FileListView, type FileItemHandlers } from "@/components/files/file-views";
import { FileDetailsPanel } from "@/components/files/file-details-panel";
import { ShowInFolderMenuItem } from "@/components/files-sync/files-sync-item";
import { INTERNAL_DRAG_TYPE, anchorEvent, isInternalDrag, readDraggedNames } from "@/components/files/file-item-parts";
import { ResizeHandle } from "@/components/layout/resize-handle";
import { AppMain } from "@/components/layout/app-landmarks";
@@ -1012,6 +1013,7 @@ export function FileBrowser({
<ContextMenuItem icon={Download} label={t("download")} onClick={() => { closeMenu(); void onDownload(resource.name); }} />
)}
<ContextMenuItem icon={Info} label={t("details")} onClick={() => { closeMenu(); toggleDetails(true); }} />
<ShowInFolderMenuItem nodeId={resource.id} onRan={closeMenu} />
<ContextMenuSeparator />
<ContextMenuItem icon={Trash2} label={t("delete")} shortcut="Del" destructive onClick={() => { closeMenu(); deleteNames([resource.name]); }} />
<FilePluginMenuEntries
+3
View File
@@ -8,6 +8,7 @@ import { cn } from "@/lib/utils";
import type { FileResource } from "@/stores/file-store";
import type { FileResourceView } from "@/lib/plugin-types";
import { PluginSlot } from "@/components/plugins/plugin-slot";
import { FilesSyncDetailsRow, ShowInFolderButton } from "@/components/files-sync/files-sync-item";
import {
FileSize, ResourceIcon, Thumbnail, canShowThumbnail, formatFullDate, type IconOptions,
} from "@/components/files/file-item-parts";
@@ -157,6 +158,7 @@ export function FileDetailsPanel({
{isStarred ? t("unstar") : t("star")}
</Button>
)}
<ShowInFolderButton nodeId={resource.id} />
</div>
<dl className="space-y-3 text-sm">
<Row
@@ -167,6 +169,7 @@ export function FileDetailsPanel({
{resource.lastModified && <Row label={t("modified")} value={formatFullDate(resource.lastModified)} />}
<Row label={t("sharing")} value={sharing} />
<Row label={t("path")} value={path} mono />
<FilesSyncDetailsRow nodeId={resource.id} />
</dl>
{pluginProps && <PluginSlot name="file-preview-section" className="w-full" extraProps={pluginProps} />}
</div>,
+3
View File
@@ -10,6 +10,7 @@ import {
FileSize, MiddleCutName, ResourceIcon, ShareBadge, Thumbnail, canShowThumbnail, formatFullDate, formatShortDate,
type IconOptions,
} from "@/components/files/file-item-parts";
import { FilesSyncBadge } from "@/components/files-sync/files-sync-item";
import type { SortDir, SortKey } from "@/components/files/files-header";
import { TOUCH_HIT_AREA } from "@/components/ui/button";
import { FILE_LIST_COLUMNS } from "./file-list-layout";
@@ -274,6 +275,7 @@ function FileListRow({ resource, isSelected, isFocused, isTabStop, isDropTarget,
</span>
{isStarred && <Star className="w-3.5 h-3.5 shrink-0 text-amber-400 fill-amber-400" aria-label={t("favorites")} />}
<ShareBadge resource={resource} t={t} />
<FilesSyncBadge nodeId={resource.id} />
</div>
{touch && (
<div className="text-xs text-muted-foreground truncate">
@@ -487,6 +489,7 @@ function FileTile({ resource, isSelected, isFocused, isTabStop, isCut, selecting
{!resource.isSymlink && <><FileSize bytes={resource.contentLength} /> · </>}{formatShortDate(resource.lastModified)}
</span>
<ShareBadge resource={resource} t={t} className="w-3 h-3" />
<FilesSyncBadge nodeId={resource.id} className="w-3 h-3" />
</div>
</div>
<IconButton