mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-05 10:10:14 +00:00
refactor: introduce ActivePageTimer to help to do partial page refresh (#38372)
Before, the logic is already there for "pull merge box". After, the logic is extracted into a general class ActivePageTimer and will help more pages (including #38329)
This commit is contained in:
@@ -339,3 +339,75 @@ let elemIdCounter = 0;
|
||||
export function generateElemId(prefix: string = ''): string {
|
||||
return `${prefix}${elemIdCounter++}`;
|
||||
}
|
||||
|
||||
export type ActivePageTimerOptions = {
|
||||
once?: boolean;
|
||||
interval: () => number; // if it returns 0, the timer is stopped
|
||||
callback: () => Promise<void>;
|
||||
};
|
||||
|
||||
export class ActivePageTimer {
|
||||
private readonly opts: ActivePageTimerOptions;
|
||||
private readonly onVisibilityChange: () => void;
|
||||
|
||||
private sysTimerId?: number;
|
||||
private startTime?: number;
|
||||
|
||||
constructor(opts: ActivePageTimerOptions) {
|
||||
this.opts = opts;
|
||||
this.onVisibilityChange = () => {
|
||||
if (!this.startTime) return;
|
||||
const interval = this.opts.interval();
|
||||
if (document.hidden) {
|
||||
this.clearSysTimer();
|
||||
} else if (interval) {
|
||||
this.startSysTimer(interval);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private async handler() {
|
||||
this.clear();
|
||||
await this.opts.callback();
|
||||
if (!this.opts.once) this.start();
|
||||
}
|
||||
|
||||
start() {
|
||||
const interval = this.opts.interval();
|
||||
if (!interval) return;
|
||||
if (this.sysTimerId) return;
|
||||
if (!this.startTime) {
|
||||
this.startTime = Date.now();
|
||||
document.addEventListener('visibilitychange', this.onVisibilityChange);
|
||||
}
|
||||
if (!document.hidden) this.startSysTimer(interval);
|
||||
}
|
||||
|
||||
private startSysTimer(interval: number) {
|
||||
const remaining = interval - (Date.now() - this.startTime!);
|
||||
if (remaining <= 0) {
|
||||
this.handler();
|
||||
} else {
|
||||
this.sysTimerId = window.setTimeout(() => this.handler(), remaining);
|
||||
}
|
||||
}
|
||||
|
||||
private clearSysTimer() {
|
||||
if (!this.sysTimerId) return;
|
||||
window.clearTimeout(this.sysTimerId);
|
||||
this.sysTimerId = undefined;
|
||||
}
|
||||
|
||||
clear() {
|
||||
if (!this.startTime) return;
|
||||
this.startTime = undefined;
|
||||
this.clearSysTimer();
|
||||
document.removeEventListener('visibilitychange', this.onVisibilityChange);
|
||||
}
|
||||
}
|
||||
|
||||
export function activePageTimerRefresh(opts: ActivePageTimerOptions): ActivePageTimer {
|
||||
const timer = new ActivePageTimer(opts);
|
||||
timer.start();
|
||||
return timer;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user