aboutsummaryrefslogtreecommitdiffstats
path: root/web_src/js/utils.js
diff options
context:
space:
mode:
authorsilverwind <me@silverwind.io>2022-11-21 10:59:42 +0100
committerGitHub <noreply@github.com>2022-11-21 17:59:42 +0800
commitc2fb27beb4a0f9a9ad1478937439bcf4c43aff4a (patch)
tree0f690c4aeecb6caa0a8cb24623141f3e569b8e72 /web_src/js/utils.js
parente4eaa68a2b2355c7333406fdcbb8b118677b95df (diff)
downloadgitea-c2fb27beb4a0f9a9ad1478937439bcf4c43aff4a.tar.gz
gitea-c2fb27beb4a0f9a9ad1478937439bcf4c43aff4a.zip
Improvements for Content Copy (#21842)
It now supports copying Markdown, SVG and Images (not in Firefox currently because of lacking [`ClipboardItem`](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem) support, but can be enabled in `about:config` and works). It will fetch the data if in a rendered view or when it's an image. Followup to https://github.com/go-gitea/gitea/pull/21629.
Diffstat (limited to 'web_src/js/utils.js')
-rw-r--r--web_src/js/utils.js48
1 files changed, 48 insertions, 0 deletions
diff --git a/web_src/js/utils.js b/web_src/js/utils.js
index 9b8bf925a9..62ee11c2eb 100644
--- a/web_src/js/utils.js
+++ b/web_src/js/utils.js
@@ -85,3 +85,51 @@ export function translateMonth(month) {
export function translateDay(day) {
return new Date(Date.UTC(2022, 7, day)).toLocaleString(getCurrentLocale(), {weekday: 'short'});
}
+
+// convert a Blob to a DataURI
+export function blobToDataURI(blob) {
+ return new Promise((resolve, reject) => {
+ try {
+ const reader = new FileReader();
+ reader.addEventListener('load', (e) => {
+ resolve(e.target.result);
+ });
+ reader.addEventListener('error', () => {
+ reject(new Error('FileReader failed'));
+ });
+ reader.readAsDataURL(blob);
+ } catch (err) {
+ reject(err);
+ }
+ });
+}
+
+// convert image Blob to another mime-type format.
+export function convertImage(blob, mime) {
+ return new Promise(async (resolve, reject) => {
+ try {
+ const img = new Image();
+ const canvas = document.createElement('canvas');
+ img.addEventListener('load', () => {
+ try {
+ canvas.width = img.naturalWidth;
+ canvas.height = img.naturalHeight;
+ const context = canvas.getContext('2d');
+ context.drawImage(img, 0, 0);
+ canvas.toBlob((blob) => {
+ if (!(blob instanceof Blob)) return reject(new Error('imageBlobToPng failed'));
+ resolve(blob);
+ }, mime);
+ } catch (err) {
+ reject(err);
+ }
+ });
+ img.addEventListener('error', () => {
+ reject(new Error('imageBlobToPng failed'));
+ });
+ img.src = await blobToDataURI(blob);
+ } catch (err) {
+ reject(err);
+ }
+ });
+}