1
0
mirror of https://github.com/BoostIo/Boostnote synced 2025-12-13 17:56:25 +00:00

Merge pull request #1989 from kawmra/create-image-tag-when-pasting-image-url

Create a image tag when pasting image url
This commit is contained in:
Junyoung Choi (Sai)
2018-06-08 14:50:09 +09:00
committed by GitHub

View File

@@ -406,25 +406,58 @@ export default class CodeEditor extends React.Component {
const taggedUrl = `<${pastedTxt}>` const taggedUrl = `<${pastedTxt}>`
editor.replaceSelection(taggedUrl) editor.replaceSelection(taggedUrl)
fetch(pastedTxt, { const isImageReponse = (response) => {
method: 'get' return response.headers.has('content-type') &&
}).then((response) => { response.headers.get('content-type').match(/^image\/.+$/)
return this.decodeResponse(response) }
}).then((response) => { const replaceTaggedUrl = (replacement) => {
const parsedResponse = (new window.DOMParser()).parseFromString(response, 'text/html')
const value = editor.getValue() const value = editor.getValue()
const cursor = editor.getCursor() const cursor = editor.getCursor()
const LinkWithTitle = `[${parsedResponse.title}](${pastedTxt})` const newValue = value.replace(taggedUrl, replacement)
const newValue = value.replace(taggedUrl, LinkWithTitle)
const newCursor = Object.assign({}, cursor, { ch: cursor.ch + newValue.length - value.length }) const newCursor = Object.assign({}, cursor, { ch: cursor.ch + newValue.length - value.length })
editor.setValue(newValue) editor.setValue(newValue)
editor.setCursor(newCursor) editor.setCursor(newCursor)
}
fetch(pastedTxt, {
method: 'get'
}).then((response) => {
if (isImageReponse(response)) {
return this.mapImageResponse(response, pastedTxt)
} else {
return this.mapNormalResponse(response, pastedTxt)
}
}).then((replacement) => {
replaceTaggedUrl(replacement)
}).catch((e) => { }).catch((e) => {
const value = editor.getValue() replaceTaggedUrl(pastedTxt)
const newValue = value.replace(taggedUrl, pastedTxt) })
const cursor = editor.getCursor() }
editor.setValue(newValue)
editor.setCursor(cursor) mapNormalResponse (response, pastedTxt) {
return this.decodeResponse(response).then((body) => {
return new Promise((resolve, reject) => {
try {
const parsedBody = (new window.DOMParser()).parseFromString(body, 'text/html')
const linkWithTitle = `[${parsedBody.title}](${pastedTxt})`
resolve(linkWithTitle)
} catch (e) {
reject(e)
}
})
})
}
mapImageResponse (response, pastedTxt) {
return new Promise((resolve, reject) => {
try {
const url = response.url
const name = url.substring(url.lastIndexOf('/') + 1)
const imageLinkWithName = `![${name}](${pastedTxt})`
resolve(imageLinkWithName)
} catch (e) {
reject(e)
}
}) })
} }