mirror of
https://github.com/pipipi-pikachu/PPTist.git
synced 2025-04-15 02:20:00 +08:00
feat: 支持粘贴SVG代码为图片
This commit is contained in:
parent
e277a6abac
commit
dffb6235c4
@ -1,5 +1,6 @@
|
||||
import { pasteCustomClipboardString } from '@/utils/clipboard'
|
||||
import { parseText2Paragraphs } from '@/utils/textParser'
|
||||
import { getImageDataURL, isSVGString, svg2File } from '@/utils/image'
|
||||
import useCreateElement from '@/hooks/useCreateElement'
|
||||
import useAddSlidesOrElements from '@/hooks/useAddSlidesOrElements'
|
||||
|
||||
@ -9,7 +10,7 @@ interface PasteTextClipboardDataOptions {
|
||||
}
|
||||
|
||||
export default () => {
|
||||
const { createTextElement } = useCreateElement()
|
||||
const { createTextElement, createImageElement } = useCreateElement()
|
||||
const { addElementsFromData, addSlidesFromData } = useAddSlidesOrElements()
|
||||
|
||||
/**
|
||||
@ -46,8 +47,17 @@ export default () => {
|
||||
|
||||
// 普通文本
|
||||
else if (!onlyElements && !onlySlide) {
|
||||
const string = parseText2Paragraphs(clipboardData)
|
||||
createTextElementFromClipboard(string)
|
||||
// 尝试检查是否为SVG代码
|
||||
const isSVG = isSVGString(clipboardData)
|
||||
if (isSVG) {
|
||||
const file = svg2File(clipboardData)
|
||||
getImageDataURL(file).then(dataURL => createImageElement(dataURL))
|
||||
}
|
||||
// 普通文字
|
||||
else {
|
||||
const string = parseText2Paragraphs(clipboardData)
|
||||
createTextElementFromClipboard(string)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -45,4 +45,31 @@ export const getImageDataURL = (file: File): Promise<string> => {
|
||||
})
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为SVG代码字符串
|
||||
* @param text 待验证文本
|
||||
*/
|
||||
export const isSVGString = (text: string): boolean => {
|
||||
const svgRegex = /<svg[\s\S]*?>[\s\S]*?<\/svg>/i
|
||||
if (!svgRegex.test(text)) return false
|
||||
|
||||
try {
|
||||
const parser = new DOMParser()
|
||||
const doc = parser.parseFromString(text, 'image/svg+xml')
|
||||
return doc.documentElement.nodeName === 'svg'
|
||||
}
|
||||
catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG代码转文件
|
||||
* @param svg SVG代码
|
||||
*/
|
||||
export const svg2File = (svg: string): File => {
|
||||
const blob = new Blob([svg], { type: 'image/svg+xml' })
|
||||
return new File([blob], `${Date.now()}.svg`, { type: 'image/svg+xml' })
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user