Repository navigation
fix(overview): suggest a filename that is not taken yet #210
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
seecker-ionos
wants to merge
2
commits into
nextcloud:main
Choose a base branch
from
seecker-ionos:fix/unique-new-file-name
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<typeof getClient> | undefined | ||
|
|
||
| function davClient(): ReturnType<typeof getClient> { | ||
| 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<boolean> { | ||
| return davClient().exists(davPath(folder, name), { signal }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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') | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<boolean>, | ||
| maxProbes = MAX_NAME_PROBES, | ||
| ): Promise<string> { | ||
| 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 | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Closing the dialog or clicking another template doesn't stop this loop; the result is only discarded at the end.
exists()accepts{ signal }(webdav 5.11WebDAVMethodOptions), so anAbortControllerper dialog, aborted on a new click and whenshowCreateDialoggoes false, stops the remaining requests. An aborted request should reject insideisTaken, which already ends the loop, so this file probably needs no change, andsignal.abortedcould replace thesuggestionRequestcounter and the!showCreateDialogcheck in the view.Non-blocking: at the cap, returning the default (known to be taken) vs the next unprobed candidate is a toss-up either way.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added one
AbortControllerper dialog. It is aborted on a new click, whenshowCreateDialoggoes false, and on unmount, and its signal goes throughnameExiststoexists(). It replaces thesuggestionRequestcounter and the!showCreateDialogcheck. As you expected,freeFileName.tsis unchanged, because the aborted request rejects insideisTaken. On the cap, I kept returning the default.