From 40fa1d37bc9cec9ccbf097493f966280764573e4 Mon Sep 17 00:00:00 2001 From: bymyself Date: Wed, 19 Feb 2025 08:27:58 -0700 Subject: [PATCH] Fix pasting image that was copied from browser (#2630) --- src/stores/imagePreviewStore.ts | 5 ++--- src/utils/formatUtil.ts | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/stores/imagePreviewStore.ts b/src/stores/imagePreviewStore.ts index 5a1a5185f..449c9fbc4 100644 --- a/src/stores/imagePreviewStore.ts +++ b/src/stores/imagePreviewStore.ts @@ -3,15 +3,14 @@ import { defineStore } from 'pinia' import { api } from '@/scripts/api' import { ExecutedWsMessage, ResultItem } from '@/types/apiTypes' +import { parseFilePath } from '@/utils/formatUtil' const toOutputs = ( filenames: string[], type: string ): ExecutedWsMessage['output'] => { return { - images: filenames.map((image) => { - return { filename: image, subfolder: '', type } - }) + images: filenames.map((image) => ({ type, ...parseFilePath(image) })) } } diff --git a/src/utils/formatUtil.ts b/src/utils/formatUtil.ts index bf4e2093c..fe7cc81ad 100644 --- a/src/utils/formatUtil.ts +++ b/src/utils/formatUtil.ts @@ -232,3 +232,41 @@ export function createAnnotatedPath( return `${createPath(item, subfolder)}${createAnnotation(rootFolder)}` return `${createPath(item.filename ?? '', item.subfolder)}${createAnnotation(item.type)}` } + +/** + * Parses a filepath into its filename and subfolder components. + * + * @example + * parseFilePath('folder/file.txt') // → { filename: 'file.txt', subfolder: 'folder' } + * parseFilePath('/folder/file.txt') // → { filename: 'file.txt', subfolder: 'folder' } + * parseFilePath('file.txt') // → { filename: 'file.txt', subfolder: '' } + * parseFilePath('folder//file.txt') // → { filename: 'file.txt', subfolder: 'folder' } + * + * @param filepath The filepath to parse + * @returns Object containing filename and subfolder + */ +export function parseFilePath(filepath: string): { + filename: string + subfolder: string +} { + if (!filepath?.trim()) return { filename: '', subfolder: '' } + + const normalizedPath = filepath + .replace(/[\\/]+/g, '/') // Normalize path separators + .replace(/^\//, '') // Remove leading slash + .replace(/\/$/, '') // Remove trailing slash + + const lastSlashIndex = normalizedPath.lastIndexOf('/') + + if (lastSlashIndex === -1) { + return { + filename: normalizedPath, + subfolder: '' + } + } + + return { + filename: normalizedPath.slice(lastSlashIndex + 1), + subfolder: normalizedPath.slice(0, lastSlashIndex) + } +}