-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: saving images from the clipboard use hooks
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import { useEffect } from 'react'; | ||
import { RendererMessenger } from 'src/Messaging'; | ||
import { AppToaster } from '../components/Toaster'; | ||
import UiStore from '../stores/UiStore'; | ||
|
||
const DEFAULT_FILE_NAME = 'image.png'; | ||
|
||
export function useClipboardImporter(uiStore: UiStore) { | ||
const pasteHandle = (e: ClipboardEvent) => { | ||
const { items, files } = e.clipboardData!; | ||
|
||
let fileName = `allusion_${Date.now()}`; | ||
const type = items[0].type; | ||
if (!type.match(/image/)) { | ||
return; | ||
} | ||
|
||
const blob = items[0].getAsFile(); | ||
if (!blob) { | ||
return; | ||
} | ||
const file = files[0]; | ||
if (file && file.type.includes('image')) { | ||
fileName = file.name == DEFAULT_FILE_NAME ? `allusion_${file.lastModified}.png` : file.name; | ||
} | ||
|
||
const reader = new FileReader(); | ||
const directory = uiStore.importDirectory; | ||
if (!directory) { | ||
AppToaster.show({ | ||
message: 'Please choose a location. Settings>BackgroundProcesses>Browse', | ||
timeout: 5000, | ||
}); | ||
return; | ||
} | ||
reader.addEventListener('loadend', async function (e) { | ||
const imgBase64 = e.target!.result!.toString(); | ||
if (!fileName.includes('.')) { | ||
let ext = imgBase64.split(';')[0].split('/')[1]; | ||
if (ext == 'jpeg') { | ||
ext = 'jpg'; | ||
} | ||
fileName = `${fileName}.${ext}`; | ||
} | ||
await RendererMessenger.storeFile({ | ||
directory, | ||
filenameWithExt: fileName, | ||
imgBase64, | ||
}); | ||
}); | ||
reader.readAsDataURL(blob); | ||
}; | ||
|
||
return useEffect(() => { | ||
document.body.addEventListener('paste', pasteHandle); | ||
return () => document.body.removeEventListener('paste', pasteHandle); | ||
}, [pasteHandle]); | ||
} |