Skip to content

Commit 271a5b3

Browse files
committed
Handle dragging uri-list into MDX files
A mime type of `uri-list` is for example files dragged from the VSCode tree view. Images are turnes into Markdown images. These are detected based on a hardcoded list of file extensions. Other URIs are inserted as-is. If the dragged URI uses the same scheme as the document it was dragged in, a relative path is inserted. Otherwise the full URI is used. Closes #322
1 parent 9075070 commit 271a5b3

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

packages/vscode-mdx/src/document-drop-edit-provider.js

+54
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,30 @@
11
/**
2+
* @typedef {import('mdast').RootContent} RootContent
23
* @typedef {import('vscode').DocumentDropEditProvider} DocumentDropEditProvider
34
* @typedef {import('vscode').DataTransferItem} DataTransferItem
45
*/
56

7+
import path from 'node:path'
68
import {Uri, WorkspaceEdit} from 'vscode'
79
import {toMarkdown} from 'mdast-util-to-markdown'
810

11+
// https://github.com/microsoft/vscode/blob/1.83.1/extensions/markdown-language-features/src/languageFeatures/copyFiles/shared.ts#L29-L41
12+
const imageExtensions = new Set([
13+
'.bmp',
14+
'.gif',
15+
'.ico',
16+
'.jpe',
17+
'.jpeg',
18+
'.jpg',
19+
'.png',
20+
'.psd',
21+
'.svg',
22+
'.tga',
23+
'.tif',
24+
'.tiff',
25+
'.webp'
26+
])
27+
928
/**
1029
* @type {DocumentDropEditProvider}
1130
*/
@@ -14,12 +33,20 @@ export const documentDropEditProvider = {
1433
/** @type {DataTransferItem | undefined} */
1534
let textItem
1635

36+
/** @type {DataTransferItem | undefined} */
37+
let uriListItem
38+
1739
for (const [mime, item] of dataTransfer) {
1840
if (mime === 'text/plain') {
1941
textItem = item
2042
continue
2143
}
2244

45+
if (mime === 'text/uri-list') {
46+
uriListItem = item
47+
continue
48+
}
49+
2350
if (!mime.startsWith('image/')) {
2451
continue
2552
}
@@ -41,6 +68,33 @@ export const documentDropEditProvider = {
4168
}
4269
}
4370

71+
if (uriListItem) {
72+
const value = await uriListItem.asString()
73+
const uris = value.split(/\r?\n/)
74+
/** @type {string[]} */
75+
const content = []
76+
77+
for (const line of uris) {
78+
const uri = Uri.parse(line)
79+
const value =
80+
uri.scheme === document.uri.scheme
81+
? path.posix.relative(document.uri.path, uri.path)
82+
: line
83+
84+
content.push(
85+
toMarkdown(
86+
imageExtensions.has(path.posix.extname(uri.path))
87+
? {type: 'image', url: value}
88+
: {type: 'text', value}
89+
).trim()
90+
)
91+
}
92+
93+
return {
94+
insertText: content.join(' ')
95+
}
96+
}
97+
4498
if (textItem) {
4599
const string = await textItem.asString()
46100
return {insertText: string}

0 commit comments

Comments
 (0)