diff --git a/packages/editor-ext/src/lib/markdown/utils/basename.ts b/packages/editor-ext/src/lib/markdown/utils/basename.ts new file mode 100644 index 00000000..503de941 --- /dev/null +++ b/packages/editor-ext/src/lib/markdown/utils/basename.ts @@ -0,0 +1,29 @@ +/** + * Flexible `basename` implementation for node and the browser + * @see https://stackoverflow.com/a/59907288/2228771 + */ +export function getBasename(path: string) { + // make sure the basename is not empty, if string ends with separator + let end = path.length - 1; + while (path[end] === '/' || path[end] === '\\') { + --end; + } + + // support mixing of Win + Unix path separators + const i1 = path.lastIndexOf('/', end); + const i2 = path.lastIndexOf('\\', end); + + let start: number; + if (i1 === -1) { + if (i2 === -1) { + // no separator in the whole thing + return path; + } + start = i2; + } else if (i2 === -1) { + start = i1; + } else { + start = Math.max(i1, i2); + } + return path.substring(start + 1, end + 1); +} diff --git a/packages/editor-ext/src/lib/markdown/utils/turndown.utils.ts b/packages/editor-ext/src/lib/markdown/utils/turndown.utils.ts index 0f84aa40..71a2b512 100644 --- a/packages/editor-ext/src/lib/markdown/utils/turndown.utils.ts +++ b/packages/editor-ext/src/lib/markdown/utils/turndown.utils.ts @@ -1,5 +1,6 @@ import * as _TurndownService from '@joplin/turndown'; import * as TurndownPluginGfm from '@joplin/turndown-plugin-gfm'; +import { getBasename } from './basename'; // CJS/ESM interop: .default exists in Vite, not in NestJS const TurndownService = (_TurndownService as any).default || _TurndownService; @@ -160,7 +161,7 @@ function video(turndownService: _TurndownService) { }, replacement: function (_content: string, node: HTMLInputElement) { const src = node.getAttribute('src') || ''; - const name = src.split('/').pop() || src; + const name = getBasename(src) || src; return '[' + name + '](' + src + ')'; }, });