Skip to content

Commit

Permalink
fix(script and core): 修复题库状态检测无限执行的BUG,优化 onrender 中的监听器执行逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
enncy committed May 25, 2023
1 parent ca5d4b3 commit cbe7f0b
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 37 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/core/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function request<T extends 'json' | 'text'>(
url: string,
opts: {
type: 'fetch' | 'GM_xmlhttpRequest';
method?: 'get' | 'post';
method?: 'get' | 'post' | 'head';
responseType?: T;
headers?: Record<string, string>;
data?: Record<string, string>;
Expand All @@ -28,7 +28,7 @@ export function request<T extends 'json' | 'text'>(
// eslint-disable-next-line no-undef
GM_xmlhttpRequest({
url,
method: method === 'get' ? 'GET' : 'POST',
method: method.toUpperCase() as 'GET' | 'HEAD' | 'POST',
data: Object.keys(data).length ? new URLSearchParams(data).toString() : undefined,
headers: Object.keys(headers).length ? headers : undefined,
responseType: responseType === 'json' ? 'json' : undefined,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/interfaces/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export class Script<
});
}

offConfigChange(listener: number | EventListener) {
offConfigChange(listener: number | void | EventListener) {
$store.removeChangeListener(listener);
}

Expand Down
12 changes: 8 additions & 4 deletions packages/core/src/interfaces/store.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ export interface StoreProvider {
getTab(key: string): Promise<any>;
setTab(key: string, value: any): Promise<any>;
addChangeListener(key: string, listener: (curr: any, pre: any, remote?: boolean) => void): number | void;
removeChangeListener(listener: number | EventListener): void;
removeChangeListener(listener: number | void | EventListener): void;
addTabChangeListener(key: string, listener: (curr: any, pre: any) => void): void | Promise<number>;
removeTabChangeListener(key: string, listener: number | EventListener): void;
}

export type StoreListenerType = number | void | EventListener;

export class LocalStoreChangeEvent extends Event {
key: string = '';
value: any;
Expand Down Expand Up @@ -153,9 +155,11 @@ export class GMStoreProvider implements StoreProvider {
});
}

removeChangeListener(listenerId: number): void {
// eslint-disable-next-line no-undef
GM_removeValueChangeListener(listenerId);
removeChangeListener(listenerId: number | void): void {
if (typeof listenerId === 'number') {
// eslint-disable-next-line no-undef
GM_removeValueChangeListener(listenerId);
}
}

async addTabChangeListener(key: string, listener: (curr: any, pre: any) => void) {
Expand Down
57 changes: 39 additions & 18 deletions packages/scripts/src/projects/background.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
import { $, $creator, $gm, $message, $modal, $store, Project, RenderScript, Script, el, request } from '@ocsjs/core';
import {
$,
$creator,
$gm,
$message,
$modal,
$store,
Project,
RenderScript,
Script,
StoreListenerType,
el,
request
} from '@ocsjs/core';
import gt from 'semver/functions/gt';
import { CommonProject } from './common';
import { definedProjects } from '..';

const state = {
console: {
listener: {
logs: 0
listenerIds: {
logs: 0 as StoreListenerType
}
},
app: {
listenerIds: {
sync: 0 as StoreListenerType,
connected: 0 as StoreListenerType,
closeSync: 0 as StoreListenerType
}
}
};
Expand All @@ -28,8 +48,6 @@ export const BackgroundProject = Project.create({
}
},
onrender({ panel }) {
this.offConfigChange(state.console.listener.logs);

const getTypeDesc = (type: LogType) =>
type === 'info'
? '信息'
Expand Down Expand Up @@ -98,16 +116,16 @@ export const BackgroundProject = Project.create({

const { div, logs } = showLogs();

state.console.listener.logs =
this.onConfigChange('logs', (logs) => {
const log = createLog(logs[logs.length - 1]);
div.append(log);
setTimeout(() => {
if (isScrollBottom(div)) {
log.scrollIntoView();
}
}, 10);
}) || 0;
this.offConfigChange(state.console.listenerIds.logs);
state.console.listenerIds.logs = this.onConfigChange('logs', (logs) => {
const log = createLog(logs[logs.length - 1]);
div.append(log);
setTimeout(() => {
if (isScrollBottom(div)) {
log.scrollIntoView();
}
}, 10);
});

const show = () => {
panel.body.replaceChildren(div);
Expand Down Expand Up @@ -170,9 +188,12 @@ export const BackgroundProject = Project.create({
};
update();

this.onConfigChange('sync', update);
this.onConfigChange('connected', update);
this.onConfigChange('closeSync', (closeSync) => {
this.offConfigChange(state.app.listenerIds.sync);
this.offConfigChange(state.app.listenerIds.connected);
this.offConfigChange(state.app.listenerIds.closeSync);
state.app.listenerIds.sync = this.onConfigChange('sync', update);
state.app.listenerIds.connected = this.onConfigChange('connected', update);
state.app.listenerIds.closeSync = this.onConfigChange('closeSync', (closeSync) => {
if (closeSync) {
this.cfg.sync = false;
this.cfg.connected = false;
Expand Down
33 changes: 21 additions & 12 deletions packages/scripts/src/projects/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
$modal
} from '@ocsjs/core';

import type { AnswererWrapper, SearchInformation } from '@ocsjs/core';
import type { AnswererWrapper, SearchInformation, StoreListenerType } from '@ocsjs/core';
import { definedProjects } from '../index';
import { markdown } from '../utils/markdown';

Expand Down Expand Up @@ -59,6 +59,11 @@ const state = {
?.scrollIntoView({ behavior: 'smooth' });
}
}
},
setting: {
listenerIds: {
aw: 0 as StoreListenerType
}
}
};

Expand Down Expand Up @@ -288,7 +293,8 @@ export const CommonProject = Project.create({
onrender({ panel }) {
// 因为需要用到 GM_xhr 所以判断是否处于用户脚本环境
if ($gm.getInfos() !== undefined) {
panel.body.replaceChildren(el('hr'));
panel.body.replaceChildren(...(this.cfg.answererWrappers.length ? [el('hr')] : []));

const refresh = el(
'button',
{ className: 'base-style-button', disabled: this.cfg.answererWrappers.length === 0 },
Expand All @@ -311,8 +317,9 @@ export const CommonProject = Project.create({
if (this.cfg.answererWrappers.length) {
refresh.style.display = 'block';
tableContainer.style.display = 'block';
refresh.textContent = '🚫正在加载...';
refresh.textContent = '🚫正在加载题库状态...';
refresh.setAttribute('disabled', 'true');

const table = el('table');
table.style.width = '100%';
this.cfg.answererWrappers.forEach(async (item) => {
Expand All @@ -328,11 +335,8 @@ export const CommonProject = Project.create({
try {
return await request(new URL(item.url).origin + '/?t=' + t, {
type: 'GM_xmlhttpRequest',
method: 'get',
responseType: 'text',
headers: {
'Content-Type': 'text/html'
}
method: 'head',
responseType: 'text'
});
} catch (err) {
error = err;
Expand All @@ -344,7 +348,8 @@ export const CommonProject = Project.create({
return false;
})()
]);
if (res) {

if (typeof res === 'string') {
success = true;
} else {
success = false;
Expand All @@ -363,7 +368,7 @@ export const CommonProject = Project.create({
setTimeout(() => {
refresh.textContent = '🔄️刷新题库状态';
refresh.removeAttribute('disabled');
}, 3000);
}, 2000);
}
});
tableContainer.append(table);
Expand All @@ -374,8 +379,12 @@ export const CommonProject = Project.create({
};

updateState();
this.onConfigChange('answererWrappers', () => {
updateState();

this.offConfigChange(state.setting.listenerIds.aw);
state.setting.listenerIds.aw = this.onConfigChange('answererWrappers', (_, __, remote) => {
if (remote === false) {
updateState();
}
});
}
},
Expand Down

0 comments on commit cbe7f0b

Please sign in to comment.