Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/services/folders.spec.ts
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)
})
})
29 changes: 29 additions & 0 deletions src/services/folders.ts
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 })
}
52 changes: 52 additions & 0 deletions src/utils/freeFileName.spec.ts
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')
})
})
39 changes: 39 additions & 0 deletions src/utils/freeFileName.ts
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++) {

Copy link
Copy Markdown
Contributor

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.11 WebDAVMethodOptions), so an AbortController per dialog, aborted on a new click and when showCreateDialog goes false, stops the remaining requests. An aborted request should reject inside isTaken, which already ends the loop, so this file probably needs no change, and signal.aborted could replace the suggestionRequest counter and the !showCreateDialog check 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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added one AbortController per dialog. It is aborted on a new click, when showCreateDialog goes false, and on unmount, and its signal goes through nameExists to exists(). It replaces the suggestionRequest counter and the !showCreateDialog check. As you expected, freeFileName.ts is unchanged, because the aborted request rejects inside isTaken. On the cap, I kept returning the default.

const candidate = getUniqueName(defaultName, taken)
if (!await isTaken(candidate)) {
return candidate
}
taken.push(candidate)
}
return defaultName
}
Loading
Loading