gitea源码

copycontent.ts 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import {clippie} from 'clippie';
  2. import {showTemporaryTooltip} from '../modules/tippy.ts';
  3. import {convertImage} from '../utils.ts';
  4. import {GET} from '../modules/fetch.ts';
  5. import {registerGlobalEventFunc} from '../modules/observer.ts';
  6. const {i18n} = window.config;
  7. export function initCopyContent() {
  8. registerGlobalEventFunc('click', 'onCopyContentButtonClick', async (btn: HTMLElement) => {
  9. if (btn.classList.contains('disabled') || btn.classList.contains('is-loading')) return;
  10. const rawFileLink = btn.getAttribute('data-raw-file-link');
  11. let content, isRasterImage = false;
  12. // when "data-raw-link" is present, we perform a fetch. this is either because
  13. // the text to copy is not in the DOM, or it is an image that should be
  14. // fetched to copy in full resolution
  15. if (rawFileLink) {
  16. btn.classList.add('is-loading', 'loading-icon-2px');
  17. try {
  18. const res = await GET(rawFileLink, {credentials: 'include', redirect: 'follow'});
  19. const contentType = res.headers.get('content-type');
  20. if (contentType.startsWith('image/') && !contentType.startsWith('image/svg')) {
  21. isRasterImage = true;
  22. content = await res.blob();
  23. } else {
  24. content = await res.text();
  25. }
  26. } catch {
  27. return showTemporaryTooltip(btn, i18n.copy_error);
  28. } finally {
  29. btn.classList.remove('is-loading', 'loading-icon-2px');
  30. }
  31. } else { // text, read from DOM
  32. const lineEls = document.querySelectorAll('.file-view .lines-code');
  33. content = Array.from(lineEls, (el) => el.textContent).join('');
  34. }
  35. // try copy original first, if that fails, and it's an image, convert it to png
  36. const success = await clippie(content);
  37. if (success) {
  38. showTemporaryTooltip(btn, i18n.copy_success);
  39. } else {
  40. if (isRasterImage) {
  41. const success = await clippie(await convertImage(content as Blob, 'image/png'));
  42. showTemporaryTooltip(btn, success ? i18n.copy_success : i18n.copy_error);
  43. } else {
  44. showTemporaryTooltip(btn, i18n.copy_error);
  45. }
  46. }
  47. });
  48. }