From 5bfd50bf4ca0d590156eed6be9cde2df64cc504d Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:38:56 +0100 Subject: [PATCH 1/4] feat: attach recently used files from the Attach menu in the desktop app --- .../__tests__/composer-attach-recent.test.tsx | 401 ++++++++++++++++++ components/email/email-composer.tsx | 33 +- .../email/recent-files-menu-section.tsx | 88 ++++ desktop-policies/Bulwark.admx | 6 + desktop-policies/de-DE/Bulwark.adml | 2 + desktop-policies/en-US/Bulwark.adml | 2 + .../org.bulwarkmail.desktop.mobileconfig | 2 + desktop-policies/policies.json | 1 + lib/desktop/__tests__/policy-schema.test.ts | 9 +- lib/desktop/__tests__/recent-files.test.ts | 87 ++++ lib/desktop/policy-schema.ts | 16 + lib/desktop/recent-files.ts | 80 ++++ lib/desktop/types.ts | 35 ++ locales/ar/common.json | 8 + locales/ca/common.json | 8 + locales/cs/common.json | 8 + locales/da/common.json | 8 + locales/de/common.json | 8 + locales/en/common.json | 8 + locales/es/common.json | 8 + locales/et/common.json | 8 + locales/fa/common.json | 8 + locales/fr/common.json | 8 + locales/he/common.json | 8 + locales/hu/common.json | 8 + locales/it/common.json | 8 + locales/ja/common.json | 8 + locales/ko/common.json | 8 + locales/lv/common.json | 8 + locales/mn/common.json | 8 + locales/nb/common.json | 8 + locales/nl/common.json | 8 + locales/pl/common.json | 8 + locales/pt/common.json | 8 + locales/ro/common.json | 8 + locales/ru/common.json | 8 + locales/sk/common.json | 8 + locales/th/common.json | 8 + locales/tr/common.json | 8 + locales/uk/common.json | 8 + locales/vi/common.json | 8 + locales/zh-TW/common.json | 8 + locales/zh/common.json | 8 + 43 files changed, 997 insertions(+), 5 deletions(-) create mode 100644 components/email/__tests__/composer-attach-recent.test.tsx create mode 100644 components/email/recent-files-menu-section.tsx create mode 100644 lib/desktop/__tests__/recent-files.test.ts create mode 100644 lib/desktop/recent-files.ts diff --git a/components/email/__tests__/composer-attach-recent.test.tsx b/components/email/__tests__/composer-attach-recent.test.tsx new file mode 100644 index 000000000..0c5d37c9a --- /dev/null +++ b/components/email/__tests__/composer-attach-recent.test.tsx @@ -0,0 +1,401 @@ +import { render, screen, fireEvent, act, waitFor, within } from '@testing-library/react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import React from 'react'; +import { EmailComposer } from '../email-composer'; +import { useAuthStore } from '@/stores/auth-store'; +import { DEFAULT_POLICY_SNAPSHOT, type PolicySnapshot } from '@/lib/desktop/policy-schema'; +import type { BulwarkDesktopBridge, DesktopRecentFile } from '@/lib/desktop/types'; + +// Recent files in the Attach menu, in the desktop app: the shell's side is +// repos/desktop's test/recent-files.spec.ts; here the bridge is a stub. + +const hoisted = vi.hoisted(() => ({ + picked: [] as unknown[], + beforeAttachmentUpload: vi.fn(async (_info: { name: string }) => true), + toastError: vi.fn(), +})); + +vi.mock('@/components/files/file-picker-dialog', () => ({ + FilePickerDialog: ({ onPick }: { onPick: (nodes: unknown[]) => void }) => + React.createElement( + 'button', + { type: 'button', 'data-testid': 'fake-file-picker', onClick: () => onPick(hoisted.picked) }, + 'pick', + ), +})); + +// ─── Heavy component mocks (mirrors composer-plugin-attachment-source.test.tsx) ─ + +vi.mock('@/components/email/rich-text-editor', () => ({ + RichTextEditor: () => React.createElement('div', { 'data-testid': 'rich-text-editor' }), +})); +vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); + +vi.mock('@/components/identity/sub-address-helper', () => ({ SubAddressHelper: () => null })); +vi.mock('@/components/templates/template-picker', () => ({ TemplatePicker: () => null })); +vi.mock('@/components/templates/template-form', () => ({ TemplateForm: () => null })); +vi.mock('@/components/files/file-preview-modal', () => ({ FilePreviewModal: () => null })); +vi.mock('@/hooks/use-focus-trap', () => ({ + useFocusTrap: () => ({ current: null }), +})); +vi.mock('@/hooks/use-pro-multi-account-identities', () => ({ + useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }), + stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }), +})); + +// ─── Store mocks ────────────────────────────────────────────────────────────── + +vi.mock('@/stores/auth-store', () => { + const state = { + client: null, + identities: [], + primaryIdentity: null, + isAuthenticated: false, + isDemoMode: false, + activeAccountId: null, + connectionLost: false, + getClientForAccount: () => undefined, + getAllConnectedClients: () => new Map(), + syncIdentities: () => {}, + refreshIdentities: async () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useAuthStore: hook }; +}); + +vi.mock('@/stores/identity-store', () => { + const state = { + identities: [{ id: 'id-me', email: 'me@example.com', name: 'Me' }], + defaultIdentityId: 'id-me', + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useIdentityStore: hook }; +}); + +vi.mock('@/stores/account-store', () => { + const state = { accounts: [], getAccountById: () => undefined }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useAccountStore: hook }; +}); + +vi.mock('@/stores/email-store', () => { + const state = { + draftSaveEnabled: false, + sendRawEmail: async () => ({ sent: true }), + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useEmailStore: hook }; +}); + +vi.mock('@/stores/settings-store', () => { + const state = { + timeFormat: '24h', + plainTextMode: false, + subAddressDelimiter: '+', + autoSelectReplyIdentity: true, + attachmentReminderEnabled: false, + attachmentReminderKeywords: [], + emptySubjectWarningEnabled: true, + sendDelaySeconds: 0, + signaturePosition: 'above_quote', + signatureSeparatorEnabled: false, + requestReadReceiptDefault: false, + addTrustedSender: () => {}, + trustedSendersAddressBook: null, + updateSetting: () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useSettingsStore: hook }; +}); + +vi.mock('@/stores/contact-store', () => { + const state = { + contacts: [], + getAutocomplete: async () => [], + addToTrustedSendersBook: async () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useContactStore: hook }; +}); + +vi.mock('@/stores/template-store', () => { + const state = { templates: [], addTemplate: async () => {} }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useTemplateStore: hook }; +}); + +// ─── Misc dependency mocks ──────────────────────────────────────────────────── + +vi.mock('@/stores/toast-store', () => ({ + toast: { info: () => {}, error: hoisted.toastError, success: () => {} }, +})); + +vi.mock('@/lib/plugin-hooks', () => ({ + identityHooks: { + onSignatureRender: { size: 0, transform: async (value: unknown) => value }, + onIdentitySelect: { size: 0, emit: async () => {} }, + }, + templateHooks: { + onTemplateRender: { size: 0, transform: async (value: unknown) => value }, + onTemplateApply: { size: 0, emit: async () => {} }, + }, + emailHooks: { + onComposerOpen: { call: async () => [] }, + onRecipientChange: { call: async () => [] }, + getRecipientSuggestions: { call: async () => [] }, + onRecipientChipsChange: { transform: async (chips: unknown) => chips }, + onDraftChange: { emit: () => {} }, + onBeforeDraftAutoSave: { transform: async (draft: unknown) => draft }, + onBeforeEmailSend: { intercept: async () => true, interceptOutcome: async () => 'allowed' }, + onBeforeAttachmentUpload: { intercept: hoisted.beforeAttachmentUpload }, + onComposeSend: { takeOver: async () => 'default' }, + onTransformOutgoingEmail: { transform: async (email: unknown) => email }, + }, + contactHooks: { + search: { call: async () => [] }, + onProvideRecipientSuggestions: { transform: async (initial: unknown) => initial }, + }, +})); + +vi.mock('@/lib/email-sanitization', () => ({ + sanitizeSignatureHtml: (v: string) => v, + sanitizeEmailHtml: (v: string) => v, + parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'), +})); + +vi.mock('@/lib/email-threading', () => ({ + computeReplyThreadingHeaders: () => ({ inReplyTo: [], references: [] }), +})); +vi.mock('@/lib/signature-utils', () => ({ + appendPlainTextSignature: (body: string) => body, + getPlainTextSignature: () => '', + plainTextBodyHasSignature: () => false, + plainTextBodyWithoutSignature: (body: string) => body, +})); +vi.mock('@/lib/sub-addressing', () => ({ generateSubAddress: () => '' })); +vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } })); +vi.mock('@/components/email/quoted-html', () => ({ + buildQuotedHtmlBlock: () => '', + serializeEditorContent: () => '', +})); +vi.mock('@/lib/template-utils', () => ({ substitutePlaceholders: (s: string) => s })); + +// ─── Tests ──────────────────────────────────────────────────────────────────── + +const NOW = Date.now(); +const RECENT: DesktopRecentFile[] = [ + { id: 'id-report', name: 'Quarterly report.docx', folder: '\\\\files\\team\\Reports', path: '\\\\files\\team\\Reports\\Quarterly report.docx', usedAt: NOW - 5 * 60_000, icon: 'data:image/png;base64,iVBORw0KGgo=' }, + { id: 'id-budget', name: 'Budget 2027.xlsx', folder: 'C:\\Users\\me\\Documents', path: 'C:\\Users\\me\\Documents\\Budget 2027.xlsx', usedAt: NOW - 3 * 60 * 60_000 }, +]; + +interface DesktopOptions { + files?: DesktopRecentFile[]; + policyOff?: boolean; + /** The shell's native menus: the Attach menu must stay HTML all the same. */ + popup?: ReturnType; +} + +function desktop({ files = RECENT, policyOff = false, popup }: DesktopOptions = {}) { + const snapshot: PolicySnapshot = { + ...DEFAULT_POLICY_SNAPSHOT, + ...(policyOff ? { RecentFilesInAttach: { value: false, source: 'forced-machine', locked: true } } : {}), + } as PolicySnapshot; + const list = vi.fn(async () => ({ ok: true as const, files })); + const attach = vi.fn(async (id: string) => { + const file = files.find((f) => f.id === id); + return file + ? { ok: true as const, file: { name: file.name, data: new TextEncoder().encode(`bytes of ${file.name}`) } } + : { ok: false as const, reason: 'unknown' as const }; + }); + window.bulwarkDesktop = { + version: 1, + platform: 'win32', + policy: { get: () => snapshot, onChange: () => () => {} }, + recentFiles: { list, attach }, + ...(popup ? { menu: { popup, setState: () => {}, onCommand: () => () => {} } } : {}), + } as unknown as BulwarkDesktopBridge; + return { list, attach }; +} + +function client(overrides: Record = {}) { + return { + createDraft: vi.fn().mockResolvedValue('draft-1'), + getEmail: vi.fn(), + hasDelayedSend: () => false, + getMaxDelayedSend: () => 0, + // No Files, no plugins: in a browser, Attach is a plain button. + supportsFiles: () => false, + getMaxSizeAttachmentsPerEmail: () => 0, + getMaxSizeUpload: () => 0, + uploadBlob: vi.fn(() => new Promise(() => {})), + ...overrides, + }; +} + +const rows = () => screen.queryAllByTestId('composer-recent-file'); + +async function openMenu() { + fireEvent.click(screen.getByTestId('composer-attach-menu')); + await act(async () => {}); +} + +describe('recent files in the Attach menu', () => { + afterEach(() => { + window.bulwarkDesktop = undefined; + useAuthStore.setState({ client: null }); + vi.clearAllMocks(); + hoisted.beforeAttachmentUpload.mockImplementation(async () => true); + }); + + it('in a browser the paperclip is the plain button it was', () => { + useAuthStore.setState({ client: client() as never }); + render(); + expect(screen.queryByTestId('composer-attach-menu')).toBeNull(); + expect(screen.getByRole('button', { name: 'attach' })).toBeInTheDocument(); + }); + + it('in the desktop app the paperclip opens a menu: recent files first, then the file dialog', async () => { + const { list } = desktop(); + useAuthStore.setState({ client: client() as never }); + render(); + expect(list).not.toHaveBeenCalled(); + await openMenu(); + expect(list).toHaveBeenCalledTimes(1); + + const menu = screen.getByRole('menu'); + const items = within(menu).getAllByRole('menuitem'); + expect(items.map((item) => item.getAttribute('data-testid'))).toEqual(['composer-recent-file', 'composer-recent-file', 'composer-attach-from-device']); + expect(within(menu).getByText('heading')).toBeInTheDocument(); + expect(items[2]).toHaveTextContent('browse'); + + const [report, budget] = rows(); + expect(report).toHaveTextContent('Quarterly report.docx'); + expect(report).toHaveTextContent('\\\\files\\team\\Reports'); + expect(report).toHaveTextContent('5 minutes ago'); + expect(report).toHaveAttribute('title', '\\\\files\\team\\Reports\\Quarterly report.docx'); + expect(report.querySelector('img')).toHaveAttribute('src', RECENT[0].icon); + // No icon from the shell: the app's own for the type. + expect(budget.querySelector('img')).toBeNull(); + expect(budget.querySelector('svg')).not.toBeNull(); + expect(budget).toHaveTextContent('3 hours ago'); + }); + + it('one click attaches that file through the composer\'s own checks and closes the menu', async () => { + const { attach } = desktop(); + useAuthStore.setState({ client: client() as never }); + render(); + await openMenu(); + fireEvent.click(rows()[1]); + expect(screen.queryByRole('menu')).toBeNull(); + expect(attach).toHaveBeenCalledWith('id-budget'); + expect(await screen.findByText('Budget 2027.xlsx')).toBeInTheDocument(); + expect(hoisted.beforeAttachmentUpload).toHaveBeenCalledWith(expect.objectContaining({ name: 'Budget 2027.xlsx', size: 'bytes of Budget 2027.xlsx'.length })); + }); + + it('a plugin can refuse it, as it can a file from the dialog', async () => { + hoisted.beforeAttachmentUpload.mockImplementation(async (info) => info.name !== 'Budget 2027.xlsx'); + desktop(); + useAuthStore.setState({ client: client() as never }); + render(); + await openMenu(); + fireEvent.click(rows()[1]); + await act(async () => {}); + expect(hoisted.beforeAttachmentUpload).toHaveBeenCalled(); + expect(screen.queryByText('Budget 2027.xlsx')).toBeNull(); + }); + + it('the server\'s size limit applies too', async () => { + desktop(); + useAuthStore.setState({ client: client({ getMaxSizeUpload: () => 5 }) as never }); + render(); + await openMenu(); + fireEvent.click(rows()[0]); + await act(async () => {}); + expect(hoisted.toastError).toHaveBeenCalledWith('attachment_too_large'); + expect(screen.queryByText('Quarterly report.docx')).toBeNull(); + }); + + it('says so when the file is gone or too large for the app', async () => { + const { attach } = desktop(); + useAuthStore.setState({ client: client() as never }); + render(); + attach.mockResolvedValueOnce({ ok: false, reason: 'missing' } as never); + await openMenu(); + fireEvent.click(rows()[0]); + await act(async () => {}); + expect(hoisted.toastError).toHaveBeenLastCalledWith('missing'); + + attach.mockResolvedValueOnce({ ok: false, reason: 'too-large' } as never); + await openMenu(); + fireEvent.click(rows()[0]); + await act(async () => {}); + expect(hoisted.toastError).toHaveBeenLastCalledWith('too_large'); + }); + + it('with nothing recent the menu has only its other entries', async () => { + desktop({ files: [] }); + useAuthStore.setState({ client: client() as never }); + render(); + await openMenu(); + const menu = screen.getByRole('menu'); + expect(within(menu).queryByText('heading')).toBeNull(); + expect(within(menu).queryByRole('separator')).toBeNull(); + expect(within(menu).getAllByRole('menuitem').map((item) => item.getAttribute('data-testid'))).toEqual(['composer-attach-from-device']); + }); + + it('with the policy off there\'s no list, and Attach is what it was', async () => { + const { list } = desktop({ policyOff: true }); + useAuthStore.setState({ client: client() as never }); + render(); + expect(screen.queryByTestId('composer-attach-menu')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'attach' })); + await act(async () => {}); + expect(list).not.toHaveBeenCalled(); + }); + + it('keys: the first file has the focus, arrows move, Escape closes', async () => { + desktop(); + useAuthStore.setState({ client: client() as never }); + render(); + await openMenu(); + await waitFor(() => expect(document.activeElement).toBe(rows()[0])); + fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' }); + expect(document.activeElement).toBe(rows()[1]); + fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' }); + expect(document.activeElement).toHaveAttribute('data-testid', 'composer-attach-from-device'); + fireEvent.keyDown(document.activeElement!, { key: 'Escape' }); + expect(screen.queryByRole('menu')).toBeNull(); + }); + + it('stays an HTML menu where the shell would draw it natively', async () => { + const popup = vi.fn(async () => null); + desktop({ popup }); + useAuthStore.setState({ client: client() as never }); + render(); + await openMenu(); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 300)); }); + expect(popup).not.toHaveBeenCalled(); + expect(rows()).toHaveLength(2); + }); +}); diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx index a1384e37c..a36e5133f 100644 --- a/components/email/email-composer.tsx +++ b/components/email/email-composer.tsx @@ -188,7 +188,11 @@ import { fileStorage } from "@/lib/plugin-storage"; import { usePolicyStore } from "@/stores/policy-store"; import { isAppLockedNow } from "@/lib/app-lock/state"; import { registerComposeFlush, registerComposeSnapshot } from "@/lib/compose-flush-registry"; -import { getDesktopBridge } from "@/lib/desktop/bridge"; +import { getDesktopBridge, isDesktopApp } from "@/lib/desktop/bridge"; +import { useDesktopPolicy } from "@/lib/desktop/policy"; +import { readRecentFile, RECENT_FILE_MAX_BYTES, recentFilesOffered } from "@/lib/desktop/recent-files"; +import type { DesktopRecentFile } from "@/lib/desktop/types"; +import { RecentFilesMenuSection } from "@/components/email/recent-files-menu-section"; import { useDesktopCommands } from "@/lib/desktop/commands"; import { noteComposerLanguage } from "@/lib/desktop/languages"; import { noteOpenDraft } from "@/lib/desktop/window-restore"; @@ -650,6 +654,7 @@ export function EmailComposer({ const tEdit = useTranslations('desktopEdit'); const tOfflineDrafts = useTranslations('offlineDrafts'); const tOffline = useTranslations('offline'); + const tRecent = useTranslations('desktopAttachRecent'); const tOfflineNotes = useTranslations('offlineConflicts'); const tSendGuards = useTranslations('send_guards'); const tWords = useTranslations('compose_words'); @@ -2778,6 +2783,21 @@ export function EmailComposer({ void addFiles(initialFiles, { handedIn: true }); }, [client, initialFiles, addFiles]); + // The Attach menu's recent files, in the desktop app (lib/desktop/recent-files.ts). The + // shell reads the file; from there it's a file like one from the file dialog. + const desktopPolicy = useDesktopPolicy(); + const recentOffered = recentFilesOffered(desktopPolicy); + const attachRecentFile = useCallback(async (file: DesktopRecentFile) => { + const result = await readRecentFile(file.id); + if (result.ok) { + await addFiles([result.file]); + return; + } + if (result.reason === 'missing') toast.error(tRecent('missing', { name: file.name })); + else if (result.reason === 'too-large') toast.error(tRecent('too_large', { name: file.name, max: formatFileSize(RECENT_FILE_MAX_BYTES) })); + else if (result.reason === 'failed') toast.error(tRecent('failed', { name: file.name })); + }, [addFiles, tRecent]); + const handleFileSelect = async (event: React.ChangeEvent) => { if (!event.target.files) return; await addFiles(Array.from(event.target.files)); @@ -5890,14 +5910,19 @@ export function EmailComposer({ className="hidden" accept="*/*" /> - {(filesEnabled && composerClient?.supportsFiles?.()) || hasAttachMenuActions ? ( + {recentOffered || (filesEnabled && composerClient?.supportsFiles?.()) || hasAttachMenuActions ? ( {(close) => <> + {/* As Outlook's: the recent files first, one click attaches one and closes. */} + {recentOffered && ( + { close(); void attachRecentFile(file); }} /> + )} { close(); fileInputRef.current?.click(); }} + testId="composer-attach-from-device" > - {t('attach_from_device')} + {isDesktopApp() ? tRecent('browse') : t('attach_from_device')} {filesEnabled && composerClient?.supportsFiles?.() && ( { close(); setFilesPicker({ client: composerClient, accountId: composerAccountId }); }} testId="composer-attach-from-files" > - {t('attach_from_files')} + {isDesktopApp() ? tRecent('from_files') : t('attach_from_files')} )} diff --git a/components/email/recent-files-menu-section.tsx b/components/email/recent-files-menu-section.tsx new file mode 100644 index 000000000..075a88167 --- /dev/null +++ b/components/email/recent-files-menu-section.tsx @@ -0,0 +1,88 @@ +"use client"; + +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { useLocale, useTranslations } from "next-intl"; +import { CONTEXT_MENU_ITEM_CLASS, menuLevelItems } from "@/components/ui/context-menu"; +import { attachmentIcon } from "@/components/email/attachment-chips"; +import { listRecentFiles, recentWhen } from "@/lib/desktop/recent-files"; +import type { DesktopRecentFile } from "@/lib/desktop/types"; +import { cn } from "@/lib/utils"; + +/** Only an icon the shell made: a PNG as a data: URL. */ +const ICON_URL = /^data:image\/png;base64,[A-Za-z0-9+/=]+$/; + +/** + * The top of the composer's Attach menu in the desktop app: the files the OS says were + * used last, as Outlook lists them. Mounted when the menu opens, from that click, which is + * what the shell asks for. Until the list is there, and when it's empty, it takes no room. + * It stays an HTML menu (data-native-menu): a native one can't show the icons and folders. + */ +export function RecentFilesMenuSection({ onPick }: { onPick: (file: DesktopRecentFile) => void }) { + const t = useTranslations("desktopAttachRecent"); + const locale = useLocale(); + const [files, setFiles] = useState(null); + // One request per opening, also when a strict-mode remount runs the effect twice. + const request = useRef | null>(null); + const rootRef = useRef(null); + + useEffect(() => { + let cancelled = false; + request.current ??= listRecentFiles(); + void request.current.then((list) => { + if (!cancelled) setFiles(list); + }); + return () => { + cancelled = true; + }; + }, []); + + // The menu put the focus on its first entry before the list came. If it's still + // there, the first file takes it: the list is what comes first. + useLayoutEffect(() => { + const root = rootRef.current; + const menu = root?.closest('[role="menu"]'); + if (!root || !menu || !files?.length) return; + const active = document.activeElement; + const others = menuLevelItems(menu).filter((item) => !root.contains(item)); + if (active && active === others[0]) root.querySelector('[role="menuitem"]')?.focus({ preventScroll: true }); + }, [files]); + + const now = Date.now(); + return ( +