diff --git a/app/(main)/[locale]/layout.tsx b/app/(main)/[locale]/layout.tsx index d5823c0c4..188b27f20 100644 --- a/app/(main)/[locale]/layout.tsx +++ b/app/(main)/[locale]/layout.tsx @@ -5,6 +5,7 @@ import { addPlainLanguage } from "@/i18n/plain-language"; import { ThemeProvider } from "@/components/providers/theme-provider"; import { CalendarAlertProvider } from "@/components/providers/calendar-alert-provider"; import { PushBindingsHost } from "@/components/providers/push-bindings-host"; +import { FilesSyncPrompts } from "@/components/files-sync/files-sync-prompts"; import { EmbeddedBridgeProvider } from "@/components/providers/embedded-bridge-provider"; import { RateLimitToastProvider } from "@/components/providers/rate-limit-toast-provider"; import { TourProvider } from "@/components/tour/tour-provider"; @@ -34,6 +35,7 @@ import { NotificationActionsHost } from "@/components/providers/notification-act import { DesktopOsHost } from "@/components/desktop/desktop-os-host"; import { FileDropHost } from "@/components/file-drop/file-drop-host"; import { EditedFilesHost } from "@/components/desktop/edited-files-host"; +import { FilesSyncHost } from "@/components/providers/files-sync-host"; import { DevicePolicyHost } from "@/components/device/device-policy-host"; import { PushNotificationPrompt } from "@/components/push-notification-prompt"; import { AccountArchiveRestorePrompt } from "@/components/account-archive-prompt"; @@ -97,8 +99,10 @@ export default async function LocaleLayout({ {!IS_LITE && } + {!IS_LITE && } {!IS_LITE && } + {!IS_LITE && } {!IS_LITE && } {!IS_LITE && } diff --git a/app/boot-skeleton.css b/app/boot-skeleton.css index dc27f65a3..f2d87e532 100644 --- a/app/boot-skeleton.css +++ b/app/boot-skeleton.css @@ -223,6 +223,7 @@ [data-boot-settings-tab="calendar"] [data-sk-settings-tab="calendar"], [data-boot-settings-tab="contacts"] [data-sk-settings-tab="contacts"], [data-boot-settings-tab="files"] [data-sk-settings-tab="files"], + [data-boot-settings-tab="files_sync"] [data-sk-settings-tab="files_sync"], [data-boot-settings-tab="addons"] [data-sk-settings-tab="addons"], [data-boot-settings-tab="offline"] [data-sk-settings-tab="offline"], [data-boot-settings-tab="privacy"] [data-sk-settings-tab="privacy"], @@ -242,6 +243,7 @@ @custom-variant boot-no-settings-addons (&:where([data-boot-settings-tabs]:not([data-boot-settings-tabs~="addons"]) *)); @custom-variant boot-no-settings-offline (&:where([data-boot-settings-tabs]:not([data-boot-settings-tabs~="offline"]) *)); @custom-variant boot-settings-recovery (&:where([data-boot-settings-tabs~="recovery"] *)); +@custom-variant boot-settings-files-sync (&:where([data-boot-settings-tabs~="files_sync"] *)); /* Settings pages with one section have no section jump row (SectionNav). */ @custom-variant boot-settings-one-section (&:where([data-boot-settings-tab="security"] *, [data-boot-settings-tab="filters"] *, [data-boot-settings-tab="vacation"] *, [data-boot-settings-tab="recovery"] *, [data-boot-settings-tab="addons"] *)); diff --git a/components/boot-skeleton/settings-skeleton.tsx b/components/boot-skeleton/settings-skeleton.tsx index c49515063..82477c6bb 100644 --- a/components/boot-skeleton/settings-skeleton.tsx +++ b/components/boot-skeleton/settings-skeleton.tsx @@ -27,6 +27,8 @@ const OPTIONAL: Partial> = { calendar: "boot-no-calendar:hidden boot-no-settings-calendar:hidden", contacts: "boot-no-settings-contacts:hidden", files: "boot-no-files:hidden boot-no-settings-files:hidden", + // Desktop app only, while the files sync runs. + files_sync: "hidden boot-settings-files-sync:flex", addons: "boot-no-settings-addons:hidden", // Not in the static Lite build. offline: "boot-no-settings-offline:hidden", diff --git a/components/files-sync/__tests__/files-sync-files-screen.test.tsx b/components/files-sync/__tests__/files-sync-files-screen.test.tsx new file mode 100644 index 000000000..b4fa1fe2d --- /dev/null +++ b/components/files-sync/__tests__/files-sync-files-screen.test.tsx @@ -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; showInFolder: ReturnType }; +} + +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( + ''} + 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(['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( + ''} + 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(); + }); +}); diff --git a/components/files-sync/__tests__/files-sync-prompts.test.tsx b/components/files-sync/__tests__/files-sync-prompts.test.tsx new file mode 100644 index 000000000..b453cf873 --- /dev/null +++ b/components/files-sync/__tests__/files-sync-prompts.test.tsx @@ -0,0 +1,90 @@ +import { act, fireEvent, render, screen, within } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { NextIntlClientProvider } from 'next-intl'; +import en from '@/locales/en/common.json'; +import type { FilesRoot } from '@/lib/desktop/types'; +import type { FilesSyncController } from '@/lib/files-sync/types'; + +// The mass-delete question asked wherever the user is (FilesSyncPrompts, mounted +// with the app-wide hosts), and kept away while the settings page asks it itself. + +vi.unmock('next-intl'); + +const { useFilesSyncStore } = await import('@/stores/files-sync-store'); +const { FilesSyncPrompts, useInlineMassDeleteQuestions } = await import('../files-sync-prompts'); + +const ROOT: FilesRoot = { + id: 'r1', kind: 'folder', account: 'acc', path: 'C:\\Users\\ann\\Projects', remoteId: 'n1', remoteLabel: 'Work / Projects', paused: false, createdAt: 1, +}; + +function setup(count = 80, side: 'local' | 'remote' = 'local') { + const controller = { confirmMassDelete: vi.fn(async () => {}) } as unknown as FilesSyncController & { confirmMassDelete: ReturnType }; + useFilesSyncStore.setState({ + available: true, + account: 'acc', + controller, + roots: [ROOT], + status: { r1: { rootId: 'r1', state: 'confirm-delete', pending: 0, done: 0, lastSyncedAt: null, massDelete: { count, side } } }, + }); + return controller; +} + +const wrap = (node: React.ReactNode) => {node}; + +afterEach(() => useFilesSyncStore.getState().reset()); + +describe('mass-delete prompt, app-wide', () => { + it('asks with the count and the side, and deletes on yes', () => { + const controller = setup(80, 'local'); + render(wrap()); + const dialog = screen.getByRole('alertdialog', { name: 'Delete 80 items?' }); + expect(dialog).toHaveTextContent('80 items were deleted from Projects on this computer. Delete them in Files too?'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Delete them' })); + expect(controller.confirmMassDelete).toHaveBeenCalledWith('r1', true); + }); + + it('brings them back on no, naming the Files folder when they went there', () => { + const controller = setup(51, 'remote'); + render(wrap()); + const dialog = screen.getByRole('alertdialog'); + expect(dialog).toHaveTextContent('51 items were deleted from Work / Projects in Files. Delete them on this computer too?'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Bring them back' })); + expect(controller.confirmMassDelete).toHaveBeenCalledWith('r1', false); + }); + + it('goes away on "Decide later" without answering, and comes back for a new question', () => { + const controller = setup(80); + render(wrap()); + fireEvent.click(screen.getByRole('button', { name: 'Decide later' })); + expect(screen.queryByRole('alertdialog')).toBeNull(); + expect(controller.confirmMassDelete).not.toHaveBeenCalled(); + act(() => useFilesSyncStore.setState({ + status: { r1: { rootId: 'r1', state: 'confirm-delete', pending: 0, done: 0, lastSyncedAt: null, massDelete: { count: 95, side: 'local' } } }, + })); + expect(screen.getByRole('alertdialog', { name: 'Delete 95 items?' })).toBeInTheDocument(); + }); + + it('asks nothing when no folder waits for an answer, or outside the app', () => { + setup(); + act(() => useFilesSyncStore.setState({ status: { r1: { rootId: 'r1', state: 'paused', pending: 0, done: 0, lastSyncedAt: null } } })); + const { unmount } = render(wrap()); + expect(screen.queryByRole('alertdialog')).toBeNull(); + unmount(); + setup(); + act(() => useFilesSyncStore.setState({ available: false })); + render(wrap()); + expect(screen.queryByRole('alertdialog')).toBeNull(); + }); + + it('stays away while the settings page asks in its rows', () => { + setup(); + function Page() { + useInlineMassDeleteQuestions(); + return null; + } + const { rerender } = render(wrap(<>)); + expect(screen.queryByRole('alertdialog')).toBeNull(); + rerender(wrap()); + expect(screen.getByRole('alertdialog')).toBeInTheDocument(); + }); +}); diff --git a/components/files-sync/files-sync-item.tsx b/components/files-sync/files-sync-item.tsx new file mode 100644 index 000000000..08661901e --- /dev/null +++ b/components/files-sync/files-sync-item.tsx @@ -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 = { + 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 { 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 ( + + ); +} + +/** 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 ( + + + ); +} + +/** "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 ( +
+
{t("item.label")}
+
+
+
+ ); +} diff --git a/components/files-sync/files-sync-prompts.tsx b/components/files-sync/files-sync-prompts.tsx new file mode 100644 index 000000000..fdf938506 --- /dev/null +++ b/components/files-sync/files-sync-prompts.tsx @@ -0,0 +1,156 @@ +"use client"; + +import { useEffect, useState, useSyncExternalStore } from "react"; +import { useTranslations } from "next-intl"; +import { AlertTriangle } from "@/components/icons"; +import { Button } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { useFilesSyncStore } from "@/stores/files-sync-store"; +import type { FilesRoot } from "@/lib/desktop/types"; +import type { FilesSyncRootStatus } from "@/lib/files-sync/types"; +import { rootName } from "./files-sync-text"; + +/* + * The mass-delete question (FILES-SYNC-BRIEF: more than 50 items or more than half a + * pair at once pauses the pair and asks). The settings page asks it in the folder's + * row; everywhere else FilesSyncPrompts asks it in a dialog, so the user sees it + * wherever they are. + */ + +let inlineHosts = 0; +const inlineListeners = new Set<() => void>(); +const subscribeInline = (listener: () => void) => { + inlineListeners.add(listener); + return () => { inlineListeners.delete(listener); }; +}; +const inlineShown = () => inlineHosts > 0; + +/** The settings page asks in its rows while it's open: the dialog stays away meanwhile. */ +export function useInlineMassDeleteQuestions(): void { + useEffect(() => { + inlineHosts += 1; + inlineListeners.forEach((listener) => listener()); + return () => { + inlineHosts -= 1; + inlineListeners.forEach((listener) => listener()); + }; + }, []); +} + +/** The question's text, for a root in `confirm-delete`. */ +export function useMassDeleteText(root: FilesRoot, massDelete: NonNullable): string { + const t = useTranslations("files_sync"); + // The side the items went from: this computer's folder, or the Files folder. + return massDelete.side === "local" + ? t("mass_delete.local", { count: massDelete.count, folder: rootName(root, t("drive.root_name")) }) + : t("mass_delete.remote", { count: massDelete.count, folder: root.remoteLabel || t("drive.root_name") }); +} + +interface AnswerButtonsProps { + rootId: string; + count: number; + /** After an answer went out. */ + onAnswered?: () => void; +} + +/** "Delete them" and "Bring them back", straight to the engine. */ +export function MassDeleteAnswers({ rootId, count, onAnswered }: AnswerButtonsProps) { + const t = useTranslations("files_sync"); + const controller = useFilesSyncStore((s) => s.controller); + const [busy, setBusy] = useState(false); + const answer = (allow: boolean) => { + if (!controller) return; + setBusy(true); + void controller.confirmMassDelete(rootId, allow).catch(() => {}).finally(() => { + setBusy(false); + onAnswered?.(); + }); + }; + return ( + <> + + + + ); +} + +/** The question inside a folder's row on the settings page. */ +export function MassDeleteQuestion({ root, status }: { root: FilesRoot; status: FilesSyncRootStatus }) { + const massDelete = status.massDelete ?? { count: 0, side: "local" as const }; + const text = useMassDeleteText(root, massDelete); + return ( +
+

+

+
+ +
+
+ ); +} + +function PromptDialog({ root, status, onLater }: { root: FilesRoot; status: FilesSyncRootStatus; onLater: () => void }) { + const t = useTranslations("files_sync"); + const massDelete = status.massDelete!; + const text = useMassDeleteText(root, massDelete); + return ( + +