gitea源码

utils.ts 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import {decode, encode} from 'uint8-to-base64';
  2. import type {IssuePageInfo, IssuePathInfo, RepoOwnerPathInfo} from './types.ts';
  3. import {toggleElemClass, toggleElem} from './utils/dom.ts';
  4. /** transform /path/to/file.ext to /path/to */
  5. export function dirname(path: string): string {
  6. const lastSlashIndex = path.lastIndexOf('/');
  7. return lastSlashIndex < 0 ? '' : path.substring(0, lastSlashIndex);
  8. }
  9. /** transform /path/to/file.ext to file.ext */
  10. export function basename(path: string): string {
  11. const lastSlashIndex = path.lastIndexOf('/');
  12. return lastSlashIndex < 0 ? path : path.substring(lastSlashIndex + 1);
  13. }
  14. /** transform /path/to/file.ext to .ext */
  15. export function extname(path: string): string {
  16. const lastSlashIndex = path.lastIndexOf('/');
  17. const lastPointIndex = path.lastIndexOf('.');
  18. if (lastSlashIndex > lastPointIndex) return '';
  19. return lastPointIndex < 0 ? '' : path.substring(lastPointIndex);
  20. }
  21. /** test whether a variable is an object */
  22. export function isObject(obj: any): boolean {
  23. return Object.prototype.toString.call(obj) === '[object Object]';
  24. }
  25. /** returns whether a dark theme is enabled */
  26. export function isDarkTheme(): boolean {
  27. const style = window.getComputedStyle(document.documentElement);
  28. return style.getPropertyValue('--is-dark-theme').trim().toLowerCase() === 'true';
  29. }
  30. /** strip <tags> from a string */
  31. export function stripTags(text: string): string {
  32. return text.replace(/<[^>]*>?/g, '');
  33. }
  34. export function parseIssueHref(href: string): IssuePathInfo {
  35. // FIXME: it should use pathname and trim the appSubUrl ahead
  36. const path = (href || '').replace(/[#?].*$/, '');
  37. const [_, ownerName, repoName, pathType, indexString] = /([^/]+)\/([^/]+)\/(issues|pulls)\/([0-9]+)/.exec(path) || [];
  38. return {ownerName, repoName, pathType, indexString};
  39. }
  40. export function parseRepoOwnerPathInfo(pathname: string): RepoOwnerPathInfo {
  41. const appSubUrl = window.config.appSubUrl;
  42. if (appSubUrl && pathname.startsWith(appSubUrl)) pathname = pathname.substring(appSubUrl.length);
  43. const [_, ownerName, repoName] = /([^/]+)\/([^/]+)/.exec(pathname) || [];
  44. return {ownerName, repoName};
  45. }
  46. export function parseIssuePageInfo(): IssuePageInfo {
  47. const el = document.querySelector('#issue-page-info');
  48. return {
  49. issueNumber: parseInt(el?.getAttribute('data-issue-index')),
  50. issueDependencySearchType: el?.getAttribute('data-issue-dependency-search-type') || '',
  51. repoId: parseInt(el?.getAttribute('data-issue-repo-id')),
  52. repoLink: el?.getAttribute('data-issue-repo-link') || '',
  53. };
  54. }
  55. /** parse a URL, either relative '/path' or absolute 'https://localhost/path' */
  56. export function parseUrl(str: string): URL {
  57. return new URL(str, str.startsWith('http') ? undefined : window.location.origin);
  58. }
  59. /** return current locale chosen by user */
  60. export function getCurrentLocale(): string {
  61. return document.documentElement.lang;
  62. }
  63. /** given a month (0-11), returns it in the documents language */
  64. export function translateMonth(month: number) {
  65. return new Date(Date.UTC(2022, month, 12)).toLocaleString(getCurrentLocale(), {month: 'short', timeZone: 'UTC'});
  66. }
  67. /** given a weekday (0-6, Sunday to Saturday), returns it in the documents language */
  68. export function translateDay(day: number) {
  69. return new Date(Date.UTC(2022, 7, day)).toLocaleString(getCurrentLocale(), {weekday: 'short', timeZone: 'UTC'});
  70. }
  71. /** convert a Blob to a DataURI */
  72. export function blobToDataURI(blob: Blob): Promise<string> {
  73. return new Promise((resolve, reject) => {
  74. try {
  75. const reader = new FileReader();
  76. reader.addEventListener('load', (e) => {
  77. resolve(e.target.result as string);
  78. });
  79. reader.addEventListener('error', () => {
  80. reject(new Error('FileReader failed'));
  81. });
  82. reader.readAsDataURL(blob);
  83. } catch (err) {
  84. reject(err);
  85. }
  86. });
  87. }
  88. /** convert image Blob to another mime-type format. */
  89. export function convertImage(blob: Blob, mime: string): Promise<Blob> {
  90. return new Promise(async (resolve, reject) => {
  91. try {
  92. const img = new Image();
  93. const canvas = document.createElement('canvas');
  94. img.addEventListener('load', () => {
  95. try {
  96. canvas.width = img.naturalWidth;
  97. canvas.height = img.naturalHeight;
  98. const context = canvas.getContext('2d');
  99. context.drawImage(img, 0, 0);
  100. canvas.toBlob((blob) => {
  101. if (!(blob instanceof Blob)) return reject(new Error('imageBlobToPng failed'));
  102. resolve(blob);
  103. }, mime);
  104. } catch (err) {
  105. reject(err);
  106. }
  107. });
  108. img.addEventListener('error', () => {
  109. reject(new Error('imageBlobToPng failed'));
  110. });
  111. img.src = await blobToDataURI(blob);
  112. } catch (err) {
  113. reject(err);
  114. }
  115. });
  116. }
  117. export function toAbsoluteUrl(url: string): string {
  118. if (url.startsWith('http://') || url.startsWith('https://')) {
  119. return url;
  120. }
  121. if (url.startsWith('//')) {
  122. return `${window.location.protocol}${url}`; // it's also a somewhat absolute URL (with the current scheme)
  123. }
  124. if (url && !url.startsWith('/')) {
  125. throw new Error('unsupported url, it should either start with / or http(s)://');
  126. }
  127. return `${window.location.origin}${url}`;
  128. }
  129. /** Encode an Uint8Array into a URLEncoded base64 string. */
  130. export function encodeURLEncodedBase64(uint8Array: Uint8Array): string {
  131. return encode(uint8Array)
  132. .replace(/\+/g, '-')
  133. .replace(/\//g, '_')
  134. .replace(/=/g, '');
  135. }
  136. /** Decode a URLEncoded base64 to an Uint8Array. */
  137. export function decodeURLEncodedBase64(base64url: string): Uint8Array {
  138. return decode(base64url
  139. .replace(/_/g, '/')
  140. .replace(/-/g, '+'));
  141. }
  142. const domParser = new DOMParser();
  143. const xmlSerializer = new XMLSerializer();
  144. export function parseDom(text: string, contentType: DOMParserSupportedType): Document {
  145. return domParser.parseFromString(text, contentType);
  146. }
  147. export function serializeXml(node: Element | Node): string {
  148. return xmlSerializer.serializeToString(node);
  149. }
  150. export function sleep(ms: number): Promise<void> {
  151. return new Promise((resolve) => setTimeout(resolve, ms));
  152. }
  153. export function isImageFile({name, type}: {name?: string, type?: string}): boolean {
  154. return /\.(avif|jpe?g|png|gif|webp|svg|heic)$/i.test(name || '') || type?.startsWith('image/');
  155. }
  156. export function isVideoFile({name, type}: {name?: string, type?: string}): boolean {
  157. return /\.(mpe?g|mp4|mkv|webm)$/i.test(name || '') || type?.startsWith('video/');
  158. }
  159. export function toggleFullScreen(fullscreenElementsSelector: string, isFullScreen: boolean, sourceParentSelector?: string): void {
  160. // hide other elements
  161. const headerEl = document.querySelector('#navbar');
  162. const contentEl = document.querySelector('.page-content');
  163. const footerEl = document.querySelector('.page-footer');
  164. toggleElem(headerEl, !isFullScreen);
  165. toggleElem(contentEl, !isFullScreen);
  166. toggleElem(footerEl, !isFullScreen);
  167. const sourceParentEl = sourceParentSelector ? document.querySelector(sourceParentSelector) : contentEl;
  168. const fullScreenEl = document.querySelector(fullscreenElementsSelector);
  169. const outerEl = document.querySelector('.full.height');
  170. toggleElemClass(fullscreenElementsSelector, 'fullscreen', isFullScreen);
  171. if (isFullScreen) {
  172. outerEl.append(fullScreenEl);
  173. } else {
  174. sourceParentEl.append(fullScreenEl);
  175. }
  176. }