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.

utils.js 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import {encode, decode} from 'uint8-to-base64';
  2. // transform /path/to/file.ext to file.ext
  3. export function basename(path = '') {
  4. const lastSlashIndex = path.lastIndexOf('/');
  5. return lastSlashIndex < 0 ? path : path.substring(lastSlashIndex + 1);
  6. }
  7. // transform /path/to/file.ext to .ext
  8. export function extname(path = '') {
  9. const lastPointIndex = path.lastIndexOf('.');
  10. return lastPointIndex < 0 ? '' : path.substring(lastPointIndex);
  11. }
  12. // test whether a variable is an object
  13. export function isObject(obj) {
  14. return Object.prototype.toString.call(obj) === '[object Object]';
  15. }
  16. // returns whether a dark theme is enabled
  17. export function isDarkTheme() {
  18. const style = window.getComputedStyle(document.documentElement);
  19. return style.getPropertyValue('--is-dark-theme').trim().toLowerCase() === 'true';
  20. }
  21. // strip <tags> from a string
  22. export function stripTags(text) {
  23. return text.replace(/<[^>]*>?/g, '');
  24. }
  25. export function parseIssueHref(href) {
  26. const path = (href || '').replace(/[#?].*$/, '');
  27. const [_, owner, repo, type, index] = /([^/]+)\/([^/]+)\/(issues|pulls)\/([0-9]+)/.exec(path) || [];
  28. return {owner, repo, type, index};
  29. }
  30. // parse a URL, either relative '/path' or absolute 'https://localhost/path'
  31. export function parseUrl(str) {
  32. return new URL(str, str.startsWith('http') ? undefined : window.location.origin);
  33. }
  34. // return current locale chosen by user
  35. export function getCurrentLocale() {
  36. return document.documentElement.lang;
  37. }
  38. // given a month (0-11), returns it in the documents language
  39. export function translateMonth(month) {
  40. return new Date(Date.UTC(2022, month, 12)).toLocaleString(getCurrentLocale(), {month: 'short', timeZone: 'UTC'});
  41. }
  42. // given a weekday (0-6, Sunday to Saturday), returns it in the documents language
  43. export function translateDay(day) {
  44. return new Date(Date.UTC(2022, 7, day)).toLocaleString(getCurrentLocale(), {weekday: 'short', timeZone: 'UTC'});
  45. }
  46. // convert a Blob to a DataURI
  47. export function blobToDataURI(blob) {
  48. return new Promise((resolve, reject) => {
  49. try {
  50. const reader = new FileReader();
  51. reader.addEventListener('load', (e) => {
  52. resolve(e.target.result);
  53. });
  54. reader.addEventListener('error', () => {
  55. reject(new Error('FileReader failed'));
  56. });
  57. reader.readAsDataURL(blob);
  58. } catch (err) {
  59. reject(err);
  60. }
  61. });
  62. }
  63. // convert image Blob to another mime-type format.
  64. export function convertImage(blob, mime) {
  65. return new Promise(async (resolve, reject) => {
  66. try {
  67. const img = new Image();
  68. const canvas = document.createElement('canvas');
  69. img.addEventListener('load', () => {
  70. try {
  71. canvas.width = img.naturalWidth;
  72. canvas.height = img.naturalHeight;
  73. const context = canvas.getContext('2d');
  74. context.drawImage(img, 0, 0);
  75. canvas.toBlob((blob) => {
  76. if (!(blob instanceof Blob)) return reject(new Error('imageBlobToPng failed'));
  77. resolve(blob);
  78. }, mime);
  79. } catch (err) {
  80. reject(err);
  81. }
  82. });
  83. img.addEventListener('error', () => {
  84. reject(new Error('imageBlobToPng failed'));
  85. });
  86. img.src = await blobToDataURI(blob);
  87. } catch (err) {
  88. reject(err);
  89. }
  90. });
  91. }
  92. export function toAbsoluteUrl(url) {
  93. if (url.startsWith('http://') || url.startsWith('https://')) {
  94. return url;
  95. }
  96. if (url.startsWith('//')) {
  97. return `${window.location.protocol}${url}`; // it's also a somewhat absolute URL (with the current scheme)
  98. }
  99. if (url && !url.startsWith('/')) {
  100. throw new Error('unsupported url, it should either start with / or http(s)://');
  101. }
  102. return `${window.location.origin}${url}`;
  103. }
  104. // Encode an ArrayBuffer into a URLEncoded base64 string.
  105. export function encodeURLEncodedBase64(arrayBuffer) {
  106. return encode(arrayBuffer)
  107. .replace(/\+/g, '-')
  108. .replace(/\//g, '_')
  109. .replace(/=/g, '');
  110. }
  111. // Decode a URLEncoded base64 to an ArrayBuffer string.
  112. export function decodeURLEncodedBase64(base64url) {
  113. return decode(base64url
  114. .replace(/_/g, '/')
  115. .replace(/-/g, '+'));
  116. }
  117. const domParser = new DOMParser();
  118. const xmlSerializer = new XMLSerializer();
  119. export function parseDom(text, contentType) {
  120. return domParser.parseFromString(text, contentType);
  121. }
  122. export function serializeXml(node) {
  123. return xmlSerializer.serializeToString(node);
  124. }