Add isomorphic basename utility
This commit is contained in:
parent
5588ec34fb
commit
5dbf0027bd
2 changed files with 31 additions and 1 deletions
29
packages/editor-ext/src/lib/markdown/utils/basename.ts
Normal file
29
packages/editor-ext/src/lib/markdown/utils/basename.ts
Normal file
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import * as _TurndownService from '@joplin/turndown';
|
import * as _TurndownService from '@joplin/turndown';
|
||||||
import * as TurndownPluginGfm from '@joplin/turndown-plugin-gfm';
|
import * as TurndownPluginGfm from '@joplin/turndown-plugin-gfm';
|
||||||
|
import { getBasename } from './basename';
|
||||||
|
|
||||||
// CJS/ESM interop: .default exists in Vite, not in NestJS
|
// CJS/ESM interop: .default exists in Vite, not in NestJS
|
||||||
const TurndownService = (_TurndownService as any).default || _TurndownService;
|
const TurndownService = (_TurndownService as any).default || _TurndownService;
|
||||||
|
|
@ -160,7 +161,7 @@ function video(turndownService: _TurndownService) {
|
||||||
},
|
},
|
||||||
replacement: function (_content: string, node: HTMLInputElement) {
|
replacement: function (_content: string, node: HTMLInputElement) {
|
||||||
const src = node.getAttribute('src') || '';
|
const src = node.getAttribute('src') || '';
|
||||||
const name = src.split('/').pop() || src;
|
const name = getBasename(src) || src;
|
||||||
return '[' + name + '](' + src + ')';
|
return '[' + name + '](' + src + ')';
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue