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.2KB

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