From 6da656cd6747bceffbbd55ac4102e2585551a01f Mon Sep 17 00:00:00 2001 From: Panagiotis Papadopoulos Date: Fri, 3 Jan 2025 12:50:17 +0100 Subject: [PATCH] refactor(formatDownloadTitle): simplify function I've kept the "extension determination process" in a nested function, that reuses the formatDownloadTitle arguments, however it could also be refactored into an own util function later, if it is ever required. The for loop got replaced by the built functions in `mimeType` --- src/services/utils.ts | 50 +++++++++++++++---------------------------- 1 file changed, 17 insertions(+), 33 deletions(-) diff --git a/src/services/utils.ts b/src/services/utils.ts index ddb51609d..854953f75 100644 --- a/src/services/utils.ts +++ b/src/services/utils.ts @@ -178,45 +178,29 @@ export function replaceAll(string: string, replaceWhat: string, replaceWith: str } export function formatDownloadTitle(fileName: string, type: string | null, mime: string) { - if (!fileName) { - fileName = "untitled"; - } - - fileName = sanitize(fileName); - - if (type === 'text') { - return `${fileName}.html`; - } else if (type && ['relationMap', 'canvas', 'search'].includes(type)) { - return `${fileName}.json`; - } else { - if (!mime) { - return fileName; - } + const fileNameBase = (!fileName) ? "untitled" : sanitize(fileName); - mime = mime.toLowerCase(); - const filenameLc = fileName.toLowerCase(); - const extensions = mimeTypes.extensions[mime]; + const getExtension = () => { + if (type === "text") return ".html"; + if (type === "relationMap" || type === "canvas" || type === "search") return ".json"; + if (!mime) return ""; - if (!extensions || extensions.length === 0) { - return fileName; - } + const mimeLc = mime.toLowerCase(); - for (const ext of extensions) { - if (filenameLc.endsWith(`.${ext}`)) { - return fileName; - } - } + // better to just return the current name without a fake extension + // it's possible that the title still preserves the correct extension anyways + if (mimeLc === 'application/octet-stream') return ""; - if (mime === 'application/octet-stream') { - // we didn't find any good guess for this one, it will be better to just return - // the current name without a fake extension. It's possible that the title still preserves the correct - // extension too + // if fileName has an extension matching the mime already - reuse it + const mimeTypeFromFileName = mimeTypes.lookup(fileName); + if (mimeTypeFromFileName === mimeLc) return ""; - return fileName; - } + // as last resort try to get extension from mimeType + const extensions = mimeTypes.extension(mime); + return extensions ? `.${extensions}` : ""; + }; - return `${fileName}.${extensions[0]}`; - } + return `${fileNameBase}${getExtension()}`; } export function removeTextFileExtension(filePath: string) {