Files
Atay-Makhzan/web_src/js/utils.ts
T

213 lines
7.6 KiB
TypeScript
Raw Normal View History

2024-11-08 10:21:13 +08:00
import {decode, encode} from 'uint8-to-base64';
import type {IssuePageInfo, IssuePathInfo, RepoOwnerPathInfo} from './types.ts';
2025-07-10 00:46:51 +08:00
import {toggleElemClass, toggleElem} from './utils/dom.ts';
/** transform /path/to/file.ext to /path/to */
export function dirname(path: string): string {
const lastSlashIndex = path.lastIndexOf('/');
return lastSlashIndex < 0 ? '' : path.substring(0, lastSlashIndex);
}
/** transform /path/to/file.ext to file.ext */
2024-08-28 18:32:38 +02:00
export function basename(path: string): string {
2024-02-25 15:31:15 +01:00
const lastSlashIndex = path.lastIndexOf('/');
return lastSlashIndex < 0 ? path : path.substring(lastSlashIndex + 1);
2020-05-14 18:06:01 +02:00
}
/** transform /path/to/file.ext to .ext */
2024-08-28 18:32:38 +02:00
export function extname(path: string): string {
2024-06-27 17:31:49 +08:00
const lastSlashIndex = path.lastIndexOf('/');
2024-02-25 15:31:15 +01:00
const lastPointIndex = path.lastIndexOf('.');
2024-06-27 17:31:49 +08:00
if (lastSlashIndex > lastPointIndex) return '';
2024-02-25 15:31:15 +01:00
return lastPointIndex < 0 ? '' : path.substring(lastPointIndex);
2020-05-14 18:06:01 +02:00
}
/** test whether a variable is an object */
2025-12-03 03:13:16 +01:00
export function isObject<T = Record<string, any>>(obj: any): obj is T {
2020-05-14 18:06:01 +02:00
return Object.prototype.toString.call(obj) === '[object Object]';
}
/** returns whether a dark theme is enabled */
2024-08-28 18:32:38 +02:00
export function isDarkTheme(): boolean {
2021-11-25 08:14:48 +01:00
const style = window.getComputedStyle(document.documentElement);
return style.getPropertyValue('--is-dark-theme').trim().toLowerCase() === 'true';
2020-05-14 18:06:01 +02:00
}
2020-05-21 04:00:43 +02:00
/** strip <tags> from a string */
2024-08-28 18:32:38 +02:00
export function stripTags(text: string): string {
let prev = '';
while (prev !== text) {
prev = text;
text = text.replace(/<[^>]*>?/g, '');
}
return text;
2020-07-27 08:24:09 +02:00
}
2024-10-31 04:06:36 +08:00
export function parseIssueHref(href: string): IssuePathInfo {
// FIXME: it should use pathname and trim the appSubUrl ahead
2021-10-22 22:34:01 +08:00
const path = (href || '').replace(/[#?].*$/, '');
2024-10-31 04:06:36 +08:00
const [_, ownerName, repoName, pathType, indexString] = /([^/]+)\/([^/]+)\/(issues|pulls)\/([0-9]+)/.exec(path) || [];
return {ownerName, repoName, pathType, indexString};
}
export function parseRepoOwnerPathInfo(pathname: string): RepoOwnerPathInfo {
const appSubUrl = window.config.appSubUrl;
if (appSubUrl && pathname.startsWith(appSubUrl)) pathname = pathname.substring(appSubUrl.length);
const [_, ownerName, repoName] = /([^/]+)\/([^/]+)/.exec(pathname) || [];
return {ownerName, repoName};
2021-10-22 22:34:01 +08:00
}
2022-06-09 19:15:08 +08:00
2024-11-08 10:21:13 +08:00
export function parseIssuePageInfo(): IssuePageInfo {
const el = document.querySelector('#issue-page-info');
return {
2025-12-03 03:13:16 +01:00
issueNumber: parseInt(el?.getAttribute('data-issue-index') || ''),
2024-11-08 10:21:13 +08:00
issueDependencySearchType: el?.getAttribute('data-issue-dependency-search-type') || '',
2025-12-03 03:13:16 +01:00
repoId: parseInt(el?.getAttribute('data-issue-repo-id') || ''),
2024-11-08 10:21:13 +08:00
repoLink: el?.getAttribute('data-issue-repo-link') || '',
};
}
/** parse a URL, either relative '/path' or absolute 'https://localhost/path' */
2024-08-28 18:32:38 +02:00
export function parseUrl(str: string): URL {
return new URL(str, str.startsWith('http') ? undefined : window.location.origin);
}
/** return current locale chosen by user */
2024-08-28 18:32:38 +02:00
export function getCurrentLocale(): string {
return document.documentElement.lang;
}
/** given a month (0-11), returns it in the documents language */
2024-08-28 18:32:38 +02:00
export function translateMonth(month: number) {
return new Date(Date.UTC(2022, month, 12)).toLocaleString(getCurrentLocale(), {month: 'short', timeZone: 'UTC'});
}
/** given a weekday (0-6, Sunday to Saturday), returns it in the documents language */
2024-08-28 18:32:38 +02:00
export function translateDay(day: number) {
return new Date(Date.UTC(2022, 7, day)).toLocaleString(getCurrentLocale(), {weekday: 'short', timeZone: 'UTC'});
}
2022-11-21 10:59:42 +01:00
/** convert a Blob to a DataURI */
2024-08-28 18:32:38 +02:00
export function blobToDataURI(blob: Blob): Promise<string> {
2022-11-21 10:59:42 +01:00
return new Promise((resolve, reject) => {
try {
const reader = new FileReader();
reader.addEventListener('load', (e) => {
2025-12-03 03:13:16 +01:00
if (e.target) {
resolve(e.target.result as string);
} else {
reject(new Error('blobToDataURI: FileReader failed'));
}
2022-11-21 10:59:42 +01:00
});
reader.addEventListener('error', () => {
2025-12-03 03:13:16 +01:00
reject(new Error('blobToDataURI: FileReader error'));
2022-11-21 10:59:42 +01:00
});
reader.readAsDataURL(blob);
} catch (err) {
reject(err);
}
});
}
/** convert image Blob to another mime-type format. */
2024-08-28 18:32:38 +02:00
export function convertImage(blob: Blob, mime: string): Promise<Blob> {
2022-11-21 10:59:42 +01:00
return new Promise(async (resolve, reject) => {
try {
const img = new Image();
const canvas = document.createElement('canvas');
img.addEventListener('load', () => {
try {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const context = canvas.getContext('2d');
2025-12-03 03:13:16 +01:00
if (!context) return reject(new Error('convertImage: no context'));
2022-11-21 10:59:42 +01:00
context.drawImage(img, 0, 0);
canvas.toBlob((blob) => {
2025-12-03 03:13:16 +01:00
if (!(blob instanceof Blob)) return reject(new Error('convertImage: toBlob failed'));
2022-11-21 10:59:42 +01:00
resolve(blob);
}, mime);
} catch (err) {
reject(err);
}
});
img.addEventListener('error', () => {
2025-12-03 03:13:16 +01:00
reject(new Error('convertImage: image failed to load'));
2022-11-21 10:59:42 +01:00
});
img.src = await blobToDataURI(blob);
} catch (err) {
reject(err);
}
});
}
2024-08-28 18:32:38 +02:00
export function toAbsoluteUrl(url: string): string {
if (url.startsWith('http://') || url.startsWith('https://')) {
return url;
}
if (url.startsWith('//')) {
return `${window.location.protocol}${url}`; // it's also a somewhat absolute URL (with the current scheme)
}
if (url && !url.startsWith('/')) {
throw new Error('unsupported url, it should either start with / or http(s)://');
}
return `${window.location.origin}${url}`;
}
2023-02-18 20:17:39 +01:00
/** Encode an Uint8Array into a URLEncoded base64 string. */
export function encodeURLEncodedBase64(uint8Array: Uint8Array): string {
return encode(uint8Array)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
/** Decode a URLEncoded base64 to an Uint8Array. */
export function decodeURLEncodedBase64(base64url: string): Uint8Array {
return decode(base64url
.replace(/_/g, '/')
.replace(/-/g, '+'));
}
const domParser = new DOMParser();
const xmlSerializer = new XMLSerializer();
2024-08-28 18:32:38 +02:00
export function parseDom(text: string, contentType: DOMParserSupportedType): Document {
return domParser.parseFromString(text, contentType);
}
2024-08-28 18:32:38 +02:00
export function serializeXml(node: Element | Node): string {
return xmlSerializer.serializeToString(node);
}
2024-02-24 02:41:24 +03:00
2024-08-28 18:32:38 +02:00
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
2024-06-27 17:31:49 +08:00
2025-01-22 08:11:51 +01:00
export function isImageFile({name, type}: {name?: string, type?: string}): boolean {
2025-12-03 03:13:16 +01:00
return Boolean(/\.(avif|jpe?g|png|gif|webp|svg|heic)$/i.test(name || '') || type?.startsWith('image/'));
2024-06-27 17:31:49 +08:00
}
2025-01-22 08:11:51 +01:00
export function isVideoFile({name, type}: {name?: string, type?: string}): boolean {
2025-12-03 03:13:16 +01:00
return Boolean(/\.(mpe?g|mp4|mkv|webm)$/i.test(name || '') || type?.startsWith('video/'));
2024-06-27 17:31:49 +08:00
}
export function toggleFullScreen(fullscreenElementsSelector: string, isFullScreen: boolean, sourceParentSelector?: string): void {
// hide other elements
2025-12-03 03:13:16 +01:00
const headerEl = document.querySelector('#navbar')!;
const contentEl = document.querySelector('.page-content')!;
const footerEl = document.querySelector('.page-footer')!;
toggleElem(headerEl, !isFullScreen);
toggleElem(contentEl, !isFullScreen);
toggleElem(footerEl, !isFullScreen);
2025-12-03 03:13:16 +01:00
const sourceParentEl = sourceParentSelector ? document.querySelector(sourceParentSelector)! : contentEl;
const fullScreenEl = document.querySelector(fullscreenElementsSelector)!;
const outerEl = document.querySelector('.full.height')!;
2025-07-10 00:46:51 +08:00
toggleElemClass(fullscreenElementsSelector, 'fullscreen', isFullScreen);
if (isFullScreen) {
outerEl.append(fullScreenEl);
} else {
sourceParentEl.append(fullScreenEl);
}
}