From 6289baf764baf984f890ebf2ea1b000cbd931586 Mon Sep 17 00:00:00 2001 From: Sebastian Ecker Date: Thu, 29 Oct 2026 20:17:52 +0100 Subject: [PATCH 1/2] fix(overview): suggest a filename that is not taken yet The create dialog always pre-filled the creator's default name, e.g. "New document.docx". Files are created in the user's root folder, so once that file exists every further attempt fails with "File already exists" and the user has to rename by hand. Suggest the first free one of "New document.docx", "New document (1).docx", ... instead, numbered by getUniqueName() like the Files app's "New" menu. Each candidate is checked with one depth-0 PROPFIND, capped at 20, so the work does not grow with the size of the root folder. The dialog still opens at once with the plain default and the free name replaces it when the checks are done, unless the user has typed a name, opened another creator meanwhile or already started creating. If a check fails, the plain default stays; the server still rejects a taken name. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Signed-off-by: Sebastian Ecker --- src/services/folders.spec.ts | 36 +++++++++++ src/services/folders.ts | 19 ++++++ src/utils/freeFileName.spec.ts | 52 +++++++++++++++ src/utils/freeFileName.ts | 39 ++++++++++++ src/views/OfficeOverview.spec.ts | 105 +++++++++++++++++++++++++++++++ src/views/OfficeOverview.vue | 54 +++++++++++++--- 6 files changed, 297 insertions(+), 8 deletions(-) create mode 100644 src/services/folders.spec.ts create mode 100644 src/services/folders.ts create mode 100644 src/utils/freeFileName.spec.ts create mode 100644 src/utils/freeFileName.ts diff --git a/src/services/folders.spec.ts b/src/services/folders.spec.ts new file mode 100644 index 00000000..5e718dca --- /dev/null +++ b/src/services/folders.spec.ts @@ -0,0 +1,36 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const existsMock = vi.fn() + +vi.mock('@nextcloud/files/dav', () => ({ + getClient: vi.fn(() => ({ exists: existsMock })), + 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') + }) + + 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') + }) + + 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') + }) +}) diff --git a/src/services/folders.ts b/src/services/folders.ts new file mode 100644 index 00000000..9caf9798 --- /dev/null +++ b/src/services/folders.ts @@ -0,0 +1,19 @@ +/** + * 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 +} + +// 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. +export async function nameExists(folder: string, name: string): Promise { + return getClient().exists(davPath(folder, name)) +} 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..5a9b2dd8 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,104 @@ describe('OfficeOverview > toggleViewMode', () => { }) }) +describe('OfficeOverview > suggested filename', () => { + async function mountWithCreators(...creators: ReturnType[]) { + getTemplatesMock.mockResolvedValue(creators) + getAllOfficeFilesMock.mockResolvedValue(officeFilesResult([])) + return mountOverview() + } + + 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') + }) + + 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') + }) +}) + describe('OfficeOverview > doCreateFromTemplate', () => { async function mountWithDialogOpen() { const creator = makeCreator() diff --git a/src/views/OfficeOverview.vue b/src/views/OfficeOverview.vue index 38304615..3b4dc308 100644 --- a/src/views/OfficeOverview.vue +++ b/src/views/OfficeOverview.vue @@ -36,10 +36,12 @@ import FilePreview from '../components/FilePreview.vue' import ShareIndicator from '../components/ShareIndicator.vue' import TemplateSection from '../components/TemplateSection.vue' import { getAllOfficeFiles, invalidateOfficeFilesCache, MAX_DISPLAY_FILES } from '../services/officeFiles.ts' +import { nameExists } from '../services/folders.ts' import { getTemplates, createFromTemplate } from '../services/templates.ts' import { getOverviewGridView, setOverviewGridView } from '../services/config.ts' import { categoryId, categoryName, categoryMimes, creatorById, allOfficeMimes } from '../utils/fileCategories.ts' import { previewAspectRatio } from '../utils/creatorTheme.ts' +import { findFreeFileName } from '../utils/freeFileName.ts' import { validateFilename } from '../utils/validateFilename.ts' import { filterFiles } from '../utils/fileFilters.ts' import { isShared } from '../utils/fileSharing.ts' @@ -69,6 +71,10 @@ const pendingTemplate = ref(null) const creating = ref(false) const createError = ref('') const createInput = ref | null>(null) +// The name the dialog last suggested; a name the user typed is never replaced. +const suggestedName = ref('') +// Bumped per opened dialog, so a slow suggestion for an earlier click is dropped. +let suggestionRequest = 0 const routeCreatorId = computed(() => { const param = route.params.creatorId @@ -190,12 +196,20 @@ function openInFiles() { } } -function onTemplateSelect(creator: TemplateCreator, template: TemplateFile | null) { - pendingCreator.value = creator - pendingTemplate.value = template - newFileName.value = creator.label + creator.extension - createError.value = '' - showCreateDialog.value = true +// Files are created in the root folder, so suggest a name that is still free +// there ("New document (1).docx"), as the Files app's own "New" menu does. If a +// check fails, fall back to the plain default; the server still rejects a name +// that is taken. +async function suggestFreeName(defaultName: string): Promise { + try { + return await findFreeFileName(defaultName, name => nameExists('/', name)) + } catch { + return defaultName + } +} + +// setSelectionRange pre-selects the basename (without extension) for quick editing. +function focusFileNameInput(extension: string) { nextTick(() => { const component = createInput.value as { focus?: () => void; $el?: HTMLElement } | null if (typeof component?.focus === 'function') { @@ -203,12 +217,36 @@ function onTemplateSelect(creator: TemplateCreator, template: TemplateFile | nul } else { component?.$el?.querySelector('input')?.focus() } - // setSelectionRange pre-selects the basename (without extension) for quick editing. component?.$el?.querySelector('input') - ?.setSelectionRange(0, newFileName.value.length - creator.extension.length) + ?.setSelectionRange(0, newFileName.value.length - extension.length) }) } +// The dialog opens at once with the plain default; the free name follows when +// the existence checks are done, so a slow connection never delays the dialog. +async function onTemplateSelect(creator: TemplateCreator, template: TemplateFile | null) { + const request = ++suggestionRequest + const defaultName = creator.label + creator.extension + pendingCreator.value = creator + pendingTemplate.value = template + suggestedName.value = defaultName + newFileName.value = defaultName + createError.value = '' + showCreateDialog.value = true + focusFileNameInput(creator.extension) + + const freeName = await suggestFreeName(defaultName) + // A later click, a closed dialog, a create already under way or a name the + // user typed all win over this answer. + if (request !== suggestionRequest || !showCreateDialog.value || creating.value + || newFileName.value !== suggestedName.value) { + return + } + suggestedName.value = freeName + newFileName.value = freeName + focusFileNameInput(creator.extension) +} + async function doCreateFromTemplate() { if (creating.value) return const validationError = validateFilename(newFileName.value) From 4ef25a9dff9b1a4ae0b187d11b8b355bbdefc52a Mon Sep 17 00:00:00 2001 From: seecker-ionos Date: Wed, 11 Nov 2026 22:14:02 +0100 Subject: [PATCH 2/2] fix(overview): wait for the free name before creating, abort stale checks Pressing Enter right after the create dialog opens could beat the existence checks, so the plain default, which is already taken, was sent and the server answered "already exists". Creating now marks the dialog busy first, waits for a pending suggestion while the field still holds the suggested name, and only then validates and sends. A late answer is no longer dropped because creating has started; if the dialog is closed while waiting, nothing is created. The checks share one AbortController per dialog, aborted when another creator is picked, the dialog closes or the view unmounts, so the remaining requests stop instead of running to the end. This replaces the request counter. A late answer only reselects the basename while the input still has focus, so it no longer pulls focus back from the Create button or elsewhere. nameExists() reuses one lazily created DAV client: getClient() builds a new client and subscribes it to request-token updates on every call. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Signed-off-by: seecker-ionos --- src/services/folders.spec.ts | 30 +++++++- src/services/folders.ts | 16 ++++- src/views/OfficeOverview.spec.ts | 118 +++++++++++++++++++++++++++++++ src/views/OfficeOverview.vue | 102 ++++++++++++++++++-------- 4 files changed, 230 insertions(+), 36 deletions(-) diff --git a/src/services/folders.spec.ts b/src/services/folders.spec.ts index 5e718dca..af49e8e0 100644 --- a/src/services/folders.spec.ts +++ b/src/services/folders.spec.ts @@ -1,9 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const existsMock = vi.fn() +const getClientMock = vi.fn(() => ({ exists: existsMock })) vi.mock('@nextcloud/files/dav', () => ({ - getClient: vi.fn(() => ({ exists: existsMock })), + getClient: getClientMock, getRootPath: vi.fn(() => '/files/alice'), })) @@ -18,14 +19,14 @@ describe('nameExists', () => { existsMock.mockResolvedValue(true) await expect(nameExists('/', 'New document.docx')).resolves.toBe(true) - expect(existsMock).toHaveBeenCalledWith('/files/alice/New document.docx') + 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') + expect(existsMock).toHaveBeenCalledWith('/files/alice/Team folder/Reports/Report.odt', { signal: undefined }) }) it('propagates a failed check to the caller', async () => { @@ -33,4 +34,27 @@ describe('nameExists', () => { 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 index 9caf9798..8877ede8 100644 --- a/src/services/folders.ts +++ b/src/services/folders.ts @@ -11,9 +11,19 @@ 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. -export async function nameExists(folder: string, name: string): Promise { - return getClient().exists(davPath(folder, name)) +// 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/views/OfficeOverview.spec.ts b/src/views/OfficeOverview.spec.ts index 5a9b2dd8..04117d2c 100644 --- a/src/views/OfficeOverview.spec.ts +++ b/src/views/OfficeOverview.spec.ts @@ -609,6 +609,30 @@ describe('OfficeOverview > suggested filename', () => { 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) } @@ -682,6 +706,7 @@ describe('OfficeOverview > suggested filename', () => { 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 () => { @@ -698,6 +723,99 @@ describe('OfficeOverview > suggested filename', () => { 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', () => { diff --git a/src/views/OfficeOverview.vue b/src/views/OfficeOverview.vue index 3b4dc308..149e279c 100644 --- a/src/views/OfficeOverview.vue +++ b/src/views/OfficeOverview.vue @@ -4,7 +4,7 @@ -->