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.
This commit is contained in:
parent
e4eaa68a2b
commit
c2fb27beb4
12 changed files with 144 additions and 29 deletions
|
@ -2,11 +2,16 @@ import {showTemporaryTooltip} from '../modules/tippy.js';
|
|||
|
||||
const {copy_success, copy_error} = window.config.i18n;
|
||||
|
||||
export async function copyToClipboard(text) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch {
|
||||
return fallbackCopyToClipboard(text);
|
||||
export async function copyToClipboard(content) {
|
||||
if (content instanceof Blob) {
|
||||
const item = new window.ClipboardItem({[content.type]: content});
|
||||
await navigator.clipboard.write([item]);
|
||||
} else { // text
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
} catch {
|
||||
return fallbackCopyToClipboard(content);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
|
59
web_src/js/features/copycontent.js
Normal file
59
web_src/js/features/copycontent.js
Normal file
|
@ -0,0 +1,59 @@
|
|||
import {copyToClipboard} from './clipboard.js';
|
||||
import {showTemporaryTooltip} from '../modules/tippy.js';
|
||||
import {convertImage} from '../utils.js';
|
||||
const {i18n} = window.config;
|
||||
|
||||
async function doCopy(content, btn) {
|
||||
const success = await copyToClipboard(content);
|
||||
showTemporaryTooltip(btn, success ? i18n.copy_success : i18n.copy_error);
|
||||
}
|
||||
|
||||
export function initCopyContent() {
|
||||
const btn = document.getElementById('copy-content');
|
||||
if (!btn || btn.classList.contains('disabled')) return;
|
||||
|
||||
btn.addEventListener('click', async () => {
|
||||
if (btn.classList.contains('is-loading')) return;
|
||||
let content, isImage;
|
||||
const link = btn.getAttribute('data-link');
|
||||
|
||||
// when data-link is present, we perform a fetch. this is either because
|
||||
// the text to copy is not in the DOM or it is an image which should be
|
||||
// fetched to copy in full resolution
|
||||
if (link) {
|
||||
btn.classList.add('is-loading');
|
||||
try {
|
||||
const res = await fetch(link, {credentials: 'include', redirect: 'follow'});
|
||||
const contentType = res.headers.get('content-type');
|
||||
|
||||
if (contentType.startsWith('image/') && !contentType.startsWith('image/svg')) {
|
||||
isImage = true;
|
||||
content = await res.blob();
|
||||
} else {
|
||||
content = await res.text();
|
||||
}
|
||||
} catch {
|
||||
return showTemporaryTooltip(btn, i18n.copy_error);
|
||||
} finally {
|
||||
btn.classList.remove('is-loading');
|
||||
}
|
||||
} else { // text, read from DOM
|
||||
const lineEls = document.querySelectorAll('.file-view .lines-code');
|
||||
content = Array.from(lineEls).map((el) => el.textContent).join('');
|
||||
}
|
||||
|
||||
try {
|
||||
await doCopy(content, btn);
|
||||
} catch {
|
||||
if (isImage) { // convert image to png as last-resort as some browser only support png copy
|
||||
try {
|
||||
await doCopy(await convertImage(content, 'image/png'), btn);
|
||||
} catch {
|
||||
showTemporaryTooltip(btn, i18n.copy_error);
|
||||
}
|
||||
} else {
|
||||
showTemporaryTooltip(btn, i18n.copy_error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
|
@ -1,10 +1,9 @@
|
|||
import $ from 'jquery';
|
||||
import {svg} from '../svg.js';
|
||||
import {invertFileFolding} from './file-fold.js';
|
||||
import {createTippy, showTemporaryTooltip} from '../modules/tippy.js';
|
||||
import {createTippy} from '../modules/tippy.js';
|
||||
import {copyToClipboard} from './clipboard.js';
|
||||
|
||||
const {i18n} = window.config;
|
||||
export const singleAnchorRegex = /^#(L|n)([1-9][0-9]*)$/;
|
||||
export const rangeAnchorRegex = /^#(L[1-9][0-9]*)-(L[1-9][0-9]*)$/;
|
||||
|
||||
|
@ -114,18 +113,6 @@ function showLineButton() {
|
|||
});
|
||||
}
|
||||
|
||||
function initCopyFileContent() {
|
||||
// get raw text for copy content button, at the moment, only one button (and one related file content) is supported.
|
||||
const copyFileContent = document.querySelector('#copy-file-content');
|
||||
if (!copyFileContent) return;
|
||||
|
||||
copyFileContent.addEventListener('click', async () => {
|
||||
const text = Array.from(document.querySelectorAll('.file-view .lines-code')).map((el) => el.textContent).join('');
|
||||
const success = await copyToClipboard(text);
|
||||
showTemporaryTooltip(copyFileContent, success ? i18n.copy_success : i18n.copy_error);
|
||||
});
|
||||
}
|
||||
|
||||
export function initRepoCodeView() {
|
||||
if ($('.code-view .lines-num').length > 0) {
|
||||
$(document).on('click', '.lines-num span', function (e) {
|
||||
|
@ -205,5 +192,4 @@ export function initRepoCodeView() {
|
|||
if (!success) return;
|
||||
document.querySelector('.code-line-button')?._tippy?.hide();
|
||||
});
|
||||
initCopyFileContent();
|
||||
}
|
||||
|
|
|
@ -89,6 +89,7 @@ import {initRepoWikiForm} from './features/repo-wiki.js';
|
|||
import {initRepoCommentForm, initRepository} from './features/repo-legacy.js';
|
||||
import {initFormattingReplacements} from './features/formatting.js';
|
||||
import {initMcaptcha} from './features/mcaptcha.js';
|
||||
import {initCopyContent} from './features/copycontent.js';
|
||||
|
||||
// Run time-critical code as soon as possible. This is safe to do because this
|
||||
// script appears at the end of <body> and rendered HTML is accessible at that point.
|
||||
|
@ -136,6 +137,7 @@ $(document).ready(() => {
|
|||
initStopwatch();
|
||||
initTableSort();
|
||||
initFindFileInRepo();
|
||||
initCopyContent();
|
||||
|
||||
initAdminCommon();
|
||||
initAdminEmails();
|
||||
|
|
|
@ -27,6 +27,7 @@ export function createTippy(target, opts = {}) {
|
|||
export function initTooltip(el, props = {}) {
|
||||
const content = el.getAttribute('data-content') || props.content;
|
||||
if (!content) return null;
|
||||
if (!el.hasAttribute('aria-label')) el.setAttribute('aria-label', content);
|
||||
return createTippy(el, {
|
||||
content,
|
||||
delay: 100,
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import {expect, test} from 'vitest';
|
||||
import {
|
||||
basename, extname, isObject, uniq, stripTags, joinPaths, parseIssueHref,
|
||||
prettyNumber, parseUrl, translateMonth, translateDay
|
||||
prettyNumber, parseUrl, translateMonth, translateDay, blobToDataURI,
|
||||
} from './utils.js';
|
||||
|
||||
test('basename', () => {
|
||||
|
@ -131,3 +131,8 @@ test('translateDay', () => {
|
|||
expect(translateDay(5)).toEqual('pt.');
|
||||
document.documentElement.lang = originalLang;
|
||||
});
|
||||
|
||||
test('blobToDataURI', async () => {
|
||||
const blob = new Blob([JSON.stringify({test: true})], {type: 'application/json'});
|
||||
expect(await blobToDataURI(blob)).toEqual('data:application/json;base64,eyJ0ZXN0Ijp0cnVlfQ==');
|
||||
});
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue