1
0
mirror of https://github.com/BoostIo/Boostnote synced 2025-12-15 18:56:22 +00:00

drag and drop image from browser

This commit is contained in:
Baptiste Augrain
2018-11-25 15:56:11 +01:00
parent a6eddb5798
commit 2908884202

View File

@@ -18,7 +18,14 @@ const PATH_SEPARATORS = escapeStringRegexp(path.posix.sep) + escapeStringRegexp(
* @returns {Promise<Image>} Image element created
*/
function getImage (file) {
return new Promise((resolve) => {
if (_.isString(file)) {
return new Promise(resolve => {
const img = new Image()
img.onload = () => resolve(img)
img.src = file
})
} else {
return new Promise(resolve => {
const reader = new FileReader()
const img = new Image()
img.onload = () => resolve(img)
@@ -27,6 +34,7 @@ function getImage (file) {
}
reader.readAsDataURL(file)
})
}
}
/**
@@ -253,6 +261,7 @@ function generateAttachmentMarkdown (fileName, path, showPreview) {
* @param {Event} dropEvent DropEvent
*/
function handleAttachmentDrop (codeEditor, storageKey, noteKey, dropEvent) {
if (dropEvent.dataTransfer.files.length > 0) {
const file = dropEvent.dataTransfer.files[0]
const filePath = file.path
const originalFileName = path.basename(filePath)
@@ -260,6 +269,7 @@ function handleAttachmentDrop (codeEditor, storageKey, noteKey, dropEvent) {
const isImage = fileType.startsWith('image')
let promise
if (isImage) {
console.log(file)
promise = fixRotate(file).then(base64data => {
return copyAttachment({type: 'base64', data: base64data, sourceFilePath: filePath}, storageKey, noteKey)
})
@@ -270,6 +280,38 @@ function handleAttachmentDrop (codeEditor, storageKey, noteKey, dropEvent) {
const imageMd = generateAttachmentMarkdown(originalFileName, path.join(STORAGE_FOLDER_PLACEHOLDER, noteKey, fileName), isImage)
codeEditor.insertAttachmentMd(imageMd)
})
} else {
for (let i = 0; i < dropEvent.dataTransfer.items.length; i++) {
const item = dropEvent.dataTransfer.items[i]
if (item.type === 'text/html') {
const html = dropEvent.dataTransfer.getData('text/html')
const match = /<img[^>]*src="([^"]+)"/.exec(html)
if (match) {
const imageURL = match[1]
getImage(imageURL)
.then(image => {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
canvas.width = image.width
canvas.height = image.height
context.drawImage(image, 0, 0)
return copyAttachment({type: 'base64', data: canvas.toDataURL(), sourceFilePath: imageURL}, storageKey, noteKey)
})
.then(fileName => {
const imageMd = generateAttachmentMarkdown(imageURL, path.join(STORAGE_FOLDER_PLACEHOLDER, noteKey, fileName), true)
codeEditor.insertAttachmentMd(imageMd)
})
break
}
}
}
}
}
/**