You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

copycontent.js 2.0KB

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