Files
gitea-MIRROR/web_src/js/utils.ts
Gary Wang d692b8d1db enhance(ui): unify all paginations into one compact style (#40514)
Server lists and the dashboard repo list rendered pagination
differently, and the server one wasted a lot of space. All pagers now
show the first, last and current page plus neighbours in seven fixed
slots, so the arrows never move. Lists with an unknown total show
Previous, Next and the current page.

<img width="672" height="383" alt="Before and after of numbered,
dashboard and previous/next pagination on first, middle and last pages,
on desktop and phone"
src="https://github.com/user-attachments/assets/c1bef79b-9579-490e-b009-d98d784b9b1c">

The pull request list now uses the same arrow between branches as the
compare page.

| Before | After |
|---|---|
| <img width="250" alt="Double chevron between branches"
src="https://github.com/user-attachments/assets/889ad911-950a-46cf-b06e-c18e06f48a29">
| <img width="250" alt="Arrow between branches"
src="https://github.com/user-attachments/assets/694ff6f9-659e-4d46-9826-b04f7cf7889a">
|

Assisted-by: Claude Code:claude-opus-5-5

---------

Co-authored-by: silverwind <me@silverwind.io>
2026-11-27 04:40:28 +00:00

227 lines
8.7 KiB
TypeScript

import type {IssuePageInfo, IssuePathInfo, RepoOwnerPathInfo} from './types.ts';
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 */
export function basename(path: string): string {
const lastSlashIndex = path.lastIndexOf('/');
return lastSlashIndex < 0 ? path : path.substring(lastSlashIndex + 1);
}
/** transform /path/to/file.ext to .ext, dotfiles like /path/to/.gitignore have no extension */
export function extname(path: string): string {
const lastPointIndex = path.lastIndexOf('.');
if (lastPointIndex <= path.lastIndexOf('/') + 1) return '';
return path.substring(lastPointIndex);
}
/** test whether a variable is an object */
export function isObject(obj: unknown): obj is Record<string, unknown> {
return Object.prototype.toString.call(obj) === '[object Object]';
}
/** Whether the current platform is macOS or iOS. */
export const isMac = /Mac/i.test(navigator.userAgent);
/** Platform-aware display symbols for keyboard modifier and special keys. */
export const keySymbols: Record<string, string> = isMac ?
{Mod: '⌘', Alt: '⌥', Shift: '⇧', Ctrl: '⌃', Up: '↑', Down: '↓', Enter: '⏎'} :
{Mod: 'Ctrl', Shift: 'Shift', Alt: 'Alt', Up: '↑', Down: '↓', Enter: '⏎'};
/** returns whether a dark theme is enabled */
export function isDarkTheme(): boolean {
const style = window.getComputedStyle(document.documentElement);
return style.getPropertyValue('--is-dark-theme').trim().toLowerCase() === 'true';
}
/** strip <tags> from a string */
export function stripTags(text: string): string {
let prev = '';
while (prev !== text) {
prev = text;
text = text.replace(/<[^>]*>?/g, '');
}
return text;
}
export function parseIssueHref(href: string): IssuePathInfo | null {
const {appSubUrl} = window.config;
let pathname: string;
try {
pathname = new URL(href || '', window.location.href).pathname;
} catch {
return null;
}
if (!pathname.startsWith(appSubUrl)) return null;
const match = /^\/([-.\w]+)\/([-.\w]+)\/(issues|pulls)\/([0-9]+)(?:\/|$)/.exec(pathname.slice(appSubUrl.length));
if (!match) return null;
const [, ownerName, repoName, pathType, indexString] = match;
return {ownerName, repoName, pathType, indexString};
}
export function parseRepoOwnerPathInfo(pathname: string): RepoOwnerPathInfo | null {
const appSubUrl = window.config.appSubUrl;
if (appSubUrl && pathname.startsWith(appSubUrl)) pathname = pathname.substring(appSubUrl.length);
const match = /([^/]+)\/([^/]+)/.exec(pathname);
if (!match) return null;
const [, ownerName, repoName] = match;
return {ownerName, repoName};
}
export function parseIssuePageInfo(): IssuePageInfo {
const el = document.querySelector('#issue-page-info');
return {
issueNumber: parseInt(el?.getAttribute('data-issue-index') || ''),
issueDependencySearchType: el?.getAttribute('data-issue-dependency-search-type') || '',
repoId: parseInt(el?.getAttribute('data-issue-repo-id') || ''),
repoLink: el?.getAttribute('data-issue-repo-link') || '',
};
}
/** return current locale chosen by user */
export function getCurrentLocale(): string {
return document.documentElement.lang;
}
/** given a month (0-11), returns it in the documents language */
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 */
export function translateDay(day: number) {
return new Date(Date.UTC(2022, 7, day)).toLocaleString(getCurrentLocale(), {weekday: 'short', timeZone: 'UTC'});
}
/** convert a Blob to a DataURI */
export function blobToDataURI(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
try {
const reader = new FileReader();
reader.addEventListener('load', (e) => {
if (e.target) {
resolve(e.target.result as string);
} else {
reject(new Error('blobToDataURI: FileReader failed'));
}
});
reader.addEventListener('error', () => {
reject(new Error('blobToDataURI: FileReader error'));
});
reader.readAsDataURL(blob);
} catch (err: unknown) {
reject(err instanceof Error ? err : new Error(String(err)));
}
});
}
/** convert image Blob to another mime-type format. */
export function convertImage(blob: Blob, mime: string): Promise<Blob> {
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');
if (!context) return reject(new Error('convertImage: no context'));
context.drawImage(img, 0, 0);
canvas.toBlob((blob) => {
if (!(blob instanceof Blob)) return reject(new Error('convertImage: toBlob failed'));
resolve(blob);
}, mime);
} catch (err: unknown) {
reject(err instanceof Error ? err : new Error(String(err)));
}
});
img.addEventListener('error', () => {
reject(new Error('convertImage: image failed to load'));
});
img.src = await blobToDataURI(blob);
} catch (err: unknown) {
reject(err instanceof Error ? err : new Error(String(err)));
}
});
}
/** Encode an Uint8Array into a URLEncoded base64 string. */
export function encodeURLEncodedBase64(uint8Array: Uint8Array): string {
return btoa(Array.from(uint8Array, (byte) => String.fromCharCode(byte)).join(''))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
/** Decode a URLEncoded base64 to an Uint8Array. */
export function decodeURLEncodedBase64(base64url: string): Uint8Array {
return Uint8Array.from(atob(base64url.replace(/_/g, '/').replace(/-/g, '+')), (ch) => ch.charCodeAt(0));
}
const domParser = new DOMParser();
const xmlSerializer = new XMLSerializer();
export function parseDom(text: string, contentType: DOMParserSupportedType): Document {
return domParser.parseFromString(text, contentType);
}
export function serializeXml(node: Element | Node): string {
return xmlSerializer.serializeToString(node);
}
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export function isImageFile({name, type}: {name: string | null, type: string | null}): boolean {
return Boolean(/\.(avif|jpeg|jpg|jxl|png|gif|webp|svg|heic)$/i.test(name || '') || type?.startsWith('image/'));
}
export function isVideoFile({name, type}: {name: string | null, type: string | null}): boolean {
return Boolean(/\.(mpg|mpeg|mp4|m4v|mkv|mov|webm)$/i.test(name || '') || type?.startsWith('video/'));
}
const byteUnits = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];
export function formatBytes(num: number, precision = 2): string {
if (!Number.isFinite(num) || num < 0) return `0 ${byteUnits[0]}`;
if (num < 1024) return `${num} ${byteUnits[0]}`;
const exp = Math.min(Math.floor(Math.log2(num) / 10), byteUnits.length - 1);
const value = num / (1024 ** exp);
const digits = Math.max(0, precision - 1 - Math.floor(Math.log10(value)));
return `${value.toFixed(digits)} ${byteUnits[exp]}`;
}
// mirrors Paginator.Pages in modules/paginator/paginator.go
export function getPaginationPages(current: number, total: number): Array<number> {
if (total <= 7) return [1, 2, 3, 4, 5, 6, 7].slice(0, total);
if (current <= 4) return [1, 2, 3, 4, 5, -1, total];
if (current >= total - 3) return [1, -1, total - 4, total - 3, total - 2, total - 1, total];
return [1, -1, current - 1, current, current + 1, -1, total];
}
export function toggleFullScreen(fullScreenEl: HTMLElement, isFullScreen: boolean, sourceParentSelector?: string): void {
// hide other elements
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);
const sourceParentEl = sourceParentSelector ? document.querySelector(sourceParentSelector)! : contentEl;
const outerEl = document.querySelector('.full.height')!;
toggleElemClass(fullScreenEl, 'fullscreen', isFullScreen);
if (isFullScreen) {
outerEl.append(fullScreenEl);
} else {
sourceParentEl.append(fullScreenEl);
}
}