diff --git a/src/services/folders.spec.ts b/src/services/folders.spec.ts new file mode 100644 index 00000000..af49e8e0 --- /dev/null +++ b/src/services/folders.spec.ts @@ -0,0 +1,60 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const existsMock = vi.fn() +const getClientMock = vi.fn(() => ({ exists: existsMock })) + +vi.mock('@nextcloud/files/dav', () => ({ + getClient: getClientMock, + getRootPath: vi.fn(() => '/files/alice'), +})) + +const { nameExists } = await import('./folders.ts') + +beforeEach(() => { + existsMock.mockReset() +}) + +describe('nameExists', () => { + it('checks the name in the root folder without a double slash', async () => { + existsMock.mockResolvedValue(true) + + await expect(nameExists('/', 'New document.docx')).resolves.toBe(true) + expect(existsMock).toHaveBeenCalledWith('/files/alice/New document.docx', { signal: undefined }) + }) + + it('checks the name in a nested folder', async () => { + existsMock.mockResolvedValue(false) + + await expect(nameExists('/Team folder/Reports', 'Report.odt')).resolves.toBe(false) + expect(existsMock).toHaveBeenCalledWith('/files/alice/Team folder/Reports/Report.odt', { signal: undefined }) + }) + + it('propagates a failed check to the caller', async () => { + existsMock.mockRejectedValue(new Error('network down')) + + await expect(nameExists('/', 'New document.docx')).rejects.toThrow('network down') + }) + + it('passes the abort signal on to the request', async () => { + existsMock.mockResolvedValue(false) + const controller = new AbortController() + + await nameExists('/', 'New document.docx', controller.signal) + + expect(existsMock).toHaveBeenCalledWith('/files/alice/New document.docx', { signal: controller.signal }) + }) + + it('creates the DAV client once and reuses it for every check', async () => { + // A fresh module, so the client cached by earlier tests does not count. + vi.resetModules() + getClientMock.mockClear() + const { nameExists: freshNameExists } = await import('./folders.ts') + existsMock.mockResolvedValue(false) + + await freshNameExists('/', 'New document.docx') + await freshNameExists('/', 'New document (1).docx') + await freshNameExists('/Documents', 'Report.odt') + + expect(getClientMock).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/services/folders.ts b/src/services/folders.ts new file mode 100644 index 00000000..8877ede8 --- /dev/null +++ b/src/services/folders.ts @@ -0,0 +1,29 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { getClient, getRootPath } from '@nextcloud/files/dav' + +// Folder paths here are relative to the user's Files root ("/", "/Documents"), +// the same form the templates/create endpoint takes. +function davPath(folder: string, name: string): string { + return getRootPath() + folder.replace(/\/$/, '') + '/' + name +} + +// getClient() builds a new client and subscribes it to request-token updates on +// every call, so one client is shared by all checks. +let client: ReturnType | undefined + +function davClient(): ReturnType { + client ??= getClient() + return client +} + +// Whether `name` is already taken in `folder`, by a file or a folder. One +// depth-0 PROPFIND; a missing entry is the 404 that exists() turns into false, +// any other failure is thrown. An aborted `signal` cancels the request, which +// then rejects. +export async function nameExists(folder: string, name: string, signal?: AbortSignal): Promise { + return davClient().exists(davPath(folder, name), { signal }) +} diff --git a/src/utils/freeFileName.spec.ts b/src/utils/freeFileName.spec.ts new file mode 100644 index 00000000..d1c2f0ce --- /dev/null +++ b/src/utils/freeFileName.spec.ts @@ -0,0 +1,52 @@ +import { describe, expect, it, vi } from 'vitest' +import { findFreeFileName, MAX_NAME_PROBES } from './freeFileName.ts' + +function takenNames(...names: string[]) { + return vi.fn(async (name: string) => names.includes(name)) +} + +describe('findFreeFileName', () => { + it('returns the default name when it is free, after a single check', async () => { + const isTaken = takenNames() + + await expect(findFreeFileName('New document.docx', isTaken)).resolves.toBe('New document.docx') + expect(isTaken).toHaveBeenCalledTimes(1) + }) + + it('numbers the name like the Files app when the default is taken', async () => { + const isTaken = takenNames('New document.docx') + + await expect(findFreeFileName('New document.docx', isTaken)).resolves.toBe('New document (1).docx') + }) + + it('skips every numbered copy that is taken, checking one candidate at a time', async () => { + const isTaken = takenNames('New document.docx', 'New document (1).docx', 'New document (2).docx') + + await expect(findFreeFileName('New document.docx', isTaken)).resolves.toBe('New document (3).docx') + expect(isTaken.mock.calls.map(([name]) => name)).toEqual([ + 'New document.docx', + 'New document (1).docx', + 'New document (2).docx', + 'New document (3).docx', + ]) + }) + + it('keeps dots in the base name and numbers before the extension', async () => { + const isTaken = takenNames('Q3.2026 report.odt') + + await expect(findFreeFileName('Q3.2026 report.odt', isTaken)).resolves.toBe('Q3.2026 report (1).odt') + }) + + it('gives up after the probe limit and returns the default name', async () => { + const isTaken = vi.fn(async () => true) + + await expect(findFreeFileName('New document.docx', isTaken)).resolves.toBe('New document.docx') + expect(isTaken).toHaveBeenCalledTimes(MAX_NAME_PROBES) + }) + + it('propagates a failed check to the caller', async () => { + const isTaken = vi.fn(async () => { throw new Error('network down') }) + + await expect(findFreeFileName('New document.docx', isTaken)).rejects.toThrow('network down') + }) +}) diff --git a/src/utils/freeFileName.ts b/src/utils/freeFileName.ts new file mode 100644 index 00000000..bb12be58 --- /dev/null +++ b/src/utils/freeFileName.ts @@ -0,0 +1,39 @@ +/** + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { getUniqueName } from '@nextcloud/files' + +// Upper bound on existence checks for one suggestion. Each check is one small +// request; past "(N)" taken copies the plain default is returned and the +// server's "already exists" error asks the user to rename. +export const MAX_NAME_PROBES = 20 + +/** + * Find the first of "Name.ext", "Name (1).ext", "Name (2).ext", … that is not + * taken, asking `isTaken` one candidate at a time. The candidates come from + * getUniqueName() so the numbering matches the Files app's "New" menu. + * + * Probing instead of listing the folder keeps the work bounded: the cost + * depends on how many copies of this name exist, not on the folder's size. + * + * @param defaultName Name to start from, e.g. "New document.docx" + * @param isTaken Resolves true when a name already exists in the target folder + * @param maxProbes Most candidates to check before falling back to defaultName + */ +export async function findFreeFileName( + defaultName: string, + isTaken: (name: string) => Promise, + maxProbes = MAX_NAME_PROBES, +): Promise { + const taken: string[] = [] + for (let probe = 0; probe < maxProbes; probe++) { + const candidate = getUniqueName(defaultName, taken) + if (!await isTaken(candidate)) { + return candidate + } + taken.push(candidate) + } + return defaultName +} diff --git a/src/views/OfficeOverview.spec.ts b/src/views/OfficeOverview.spec.ts index 0a655e63..04117d2c 100644 --- a/src/views/OfficeOverview.spec.ts +++ b/src/views/OfficeOverview.spec.ts @@ -11,12 +11,17 @@ const getTemplatesMock = vi.fn() const createFromTemplateMock = vi.fn() const getAllOfficeFilesMock = vi.fn() const invalidateOfficeFilesCacheMock = vi.fn() +const nameExistsMock = vi.fn() vi.mock('../services/templates.ts', () => ({ getTemplates: getTemplatesMock, createFromTemplate: createFromTemplateMock, })) +vi.mock('../services/folders.ts', () => ({ + nameExists: nameExistsMock, +})) + vi.mock('../services/officeFiles.ts', async (importOriginal) => { const actual = await importOriginal() return { @@ -127,6 +132,8 @@ beforeEach(() => { createFromTemplateMock.mockReset() getAllOfficeFilesMock.mockReset() invalidateOfficeFilesCacheMock.mockReset() + nameExistsMock.mockReset() + nameExistsMock.mockResolvedValue(false) localStorage.clear() // jsdom's real Location.href setter attempts actual navigation, logs @@ -595,6 +602,222 @@ describe('OfficeOverview > toggleViewMode', () => { }) }) +describe('OfficeOverview > suggested filename', () => { + async function mountWithCreators(...creators: ReturnType[]) { + getTemplatesMock.mockResolvedValue(creators) + getAllOfficeFilesMock.mockResolvedValue(officeFilesResult([])) + return mountOverview() + } + + // A text field with a real and a focus() spy, for the focus and + // selection checks; the default shallow stub renders neither. + const focusSpy = vi.fn() + const TEXT_FIELD_WITH_INPUT_STUB = { + name: 'NcTextField', + props: ['modelValue', 'label', 'error', 'helperText', 'disabled'], + methods: { focus: focusSpy }, + template: '
', + } + + async function mountWithInput(creator: ReturnType) { + getTemplatesMock.mockResolvedValue([creator]) + getAllOfficeFilesMock.mockResolvedValue(officeFilesResult([])) + return mountOverview({ NcTextField: TEXT_FIELD_WITH_INPUT_STUB }) + } + + // Answers the first check only when the test says so; later checks follow + // the mock's implementation. + function holdFirstCheck() { + let answer: (taken: boolean) => void = () => {} + nameExistsMock.mockReturnValueOnce(new Promise((resolve) => { answer = resolve })) + return (taken: boolean) => answer(taken) + } + + async function select(wrapper: Awaited>, creator: ReturnType) { + await wrapper.findComponent({ name: 'TemplateSection' }).vm.$emit('select', creator, null) + } + + function takenInRoot(...names: string[]) { + nameExistsMock.mockImplementation(async (folder: string, name: string) => folder === '/' && names.includes(name)) + } + + function fileName(wrapper: Awaited>) { + return wrapper.findComponent({ name: 'NcTextField' }).props('modelValue') + } + + it('suggests the plain default name when it is free in the root folder', async () => { + const creator = makeCreator() + const wrapper = await mountWithCreators(creator) + + await select(wrapper, creator) + await flushPromises() + + expect(fileName(wrapper)).toBe('Document.odt') + }) + + it('suggests a numbered name when the default is already taken in the root folder', async () => { + takenInRoot('Document.odt', 'Document (1).odt') + const creator = makeCreator() + const wrapper = await mountWithCreators(creator) + + await select(wrapper, creator) + await flushPromises() + + expect(fileName(wrapper)).toBe('Document (2).odt') + }) + + it('falls back to the plain default name when the check fails', async () => { + nameExistsMock.mockRejectedValue(new Error('network down')) + const creator = makeCreator() + const wrapper = await mountWithCreators(creator) + + await select(wrapper, creator) + await flushPromises() + + expect(fileName(wrapper)).toBe('Document.odt') + }) + + it('opens the dialog at once with the default name, before the check answers', async () => { + nameExistsMock.mockReturnValue(new Promise(() => {})) + const creator = makeCreator() + const wrapper = await mountWithCreators(creator) + + await select(wrapper, creator) + await flushPromises() + + expect(wrapper.findComponent({ name: 'NcDialog' }).props('open')).toBe(true) + expect(fileName(wrapper)).toBe('Document.odt') + }) + + it('ignores a late answer for an earlier click', async () => { + const document = makeCreator() + const spreadsheet = makeCreator({ label: 'Spreadsheet', extension: '.ods', mimetypes: ['application/vnd.oasis.opendocument.spreadsheet'] }) + let answerFirstCheck: (taken: boolean) => void = () => {} + nameExistsMock + .mockReturnValueOnce(new Promise((resolve) => { answerFirstCheck = resolve })) + .mockResolvedValue(false) + const wrapper = await mountWithCreators(document, spreadsheet) + + await select(wrapper, document) + await select(wrapper, spreadsheet) + await flushPromises() + answerFirstCheck(false) + await flushPromises() + + expect(wrapper.findComponent({ name: 'NcDialog' }).props('name')).toBe('Spreadsheet') + expect(fileName(wrapper)).toBe('Spreadsheet.ods') + expect((nameExistsMock.mock.calls[0][2] as AbortSignal).aborted).toBe(true) + }) + + it('keeps a name the user typed while the check was running', async () => { + takenInRoot('Document.odt') + let answerCheck: (taken: boolean) => void = () => {} + nameExistsMock.mockReturnValueOnce(new Promise((resolve) => { answerCheck = resolve })) + const creator = makeCreator() + const wrapper = await mountWithCreators(creator) + + await select(wrapper, creator) + await wrapper.findComponent({ name: 'NcTextField' }).vm.$emit('update:modelValue', 'Budget.odt') + answerCheck(true) + await flushPromises() + + expect(fileName(wrapper)).toBe('Budget.odt') + }) + + it('creates the free name when Create is pressed before the check answers', async () => { + takenInRoot('Document.odt') + const answerCheck = holdFirstCheck() + createFromTemplateMock.mockResolvedValue({ fileid: 7, basename: 'Document (1).odt', filename: '/Document (1).odt' }) + const creator = makeCreator() + const wrapper = await mountWithCreators(creator) + + await select(wrapper, creator) + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(createFromTemplateMock).not.toHaveBeenCalled() + expect(wrapper.findComponent({ name: 'NcTextField' }).props('disabled')).toBe(true) + + answerCheck(true) + await flushPromises() + + expect(createFromTemplateMock).toHaveBeenCalledWith('/Document (1).odt', '', 'user_system') + }) + + it('does not create a file when the dialog is closed while Create waits for the check', async () => { + nameExistsMock.mockImplementation((_folder: string, _name: string, signal: AbortSignal) => new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))) + })) + const creator = makeCreator() + const wrapper = await mountWithCreators(creator) + + await select(wrapper, creator) + await wrapper.find('form').trigger('submit') + await wrapper.findComponent({ name: 'NcDialog' }).vm.$emit('update:open', false) + await flushPromises() + + expect(createFromTemplateMock).not.toHaveBeenCalled() + expect(wrapper.findComponent({ name: 'NcDialog' }).exists()).toBe(false) + }) + + it('aborts the remaining checks when the dialog is closed', async () => { + nameExistsMock.mockReturnValue(new Promise(() => {})) + const creator = makeCreator() + const wrapper = await mountWithCreators(creator) + + await select(wrapper, creator) + const signal = nameExistsMock.mock.calls[0][2] as AbortSignal + expect(signal.aborted).toBe(false) + + await wrapper.findComponent({ name: 'NcDialog' }).vm.$emit('update:open', false) + await flushPromises() + + expect(signal.aborted).toBe(true) + }) + + it('leaves focus and selection alone when the answer arrives after the user left the field', async () => { + takenInRoot('Document.odt') + const answerCheck = holdFirstCheck() + const creator = makeCreator() + const wrapper = await mountWithInput(creator) + + await select(wrapper, creator) + await flushPromises() + const input = wrapper.find('input').element as HTMLInputElement + const selectSpy = vi.spyOn(input, 'setSelectionRange') + focusSpy.mockClear() + + // The wrapper is not attached to the document, so the input is not focused. + answerCheck(true) + await flushPromises() + + expect(fileName(wrapper)).toBe('Document (1).odt') + expect(focusSpy).not.toHaveBeenCalled() + expect(selectSpy).not.toHaveBeenCalled() + }) + + it('reselects the basename when the field still has focus as the answer arrives', async () => { + takenInRoot('Document.odt') + const answerCheck = holdFirstCheck() + const creator = makeCreator() + const wrapper = await mountWithInput(creator) + + await select(wrapper, creator) + await flushPromises() + const input = wrapper.find('input').element as HTMLInputElement + const selectSpy = vi.spyOn(input, 'setSelectionRange') + const activeElement = vi.spyOn(document, 'activeElement', 'get').mockReturnValue(input) + focusSpy.mockClear() + + answerCheck(true) + await flushPromises() + activeElement.mockRestore() + + expect(focusSpy).not.toHaveBeenCalled() + expect(selectSpy).toHaveBeenCalledWith(0, 'Document (1)'.length) + }) +}) + describe('OfficeOverview > doCreateFromTemplate', () => { async function mountWithDialogOpen() { const creator = makeCreator() diff --git a/src/views/OfficeOverview.vue b/src/views/OfficeOverview.vue index 38304615..149e279c 100644 --- a/src/views/OfficeOverview.vue +++ b/src/views/OfficeOverview.vue @@ -4,7 +4,7 @@ -->