Skip to content

Commit

Permalink
feat: 支持解析规则更新
Browse files Browse the repository at this point in the history
  • Loading branch information
Whilconn committed Mar 9, 2024
1 parent e53f2e3 commit 5d88d8f
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 42 deletions.
1 change: 0 additions & 1 deletion .env

This file was deleted.

2 changes: 2 additions & 0 deletions .env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#GITHUB_TOKEN=xxx
VITE_RESOLVE_URL=https://cdn.jsdelivr.net/gh/Whilconn/one-toc/src/shared/resolve-rules.json
12 changes: 6 additions & 6 deletions src/background/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,19 @@ import {

// 将变更的配置项重置为默认值,仅用于插件更新的场景
// 当配置项的选项值发生变化,原来的值在现有备选项中不存在,则将该配置项重置为默认的选项值
function fixSettings(st: Settings) {
if (!st) return st;
function fixSettings(localSettings: Settings): Settings {
if (!localSettings) return localSettings;

const list: [Key1, Option[]][] = [
const keyAndOptions: [Key1, Option[]][] = [
['position', POSITION_OPTIONS],
['theme', THEME_OPTIONS],
['strategy', STRATEGY_OPTIONS],
];

const settings = { ...st };
const settings = { ...DEFAULT_SETTINGS, ...localSettings };

for (const [key, opts] of list) {
if (opts.some((o) => o.value === st[key])) continue;
for (const [key, opts] of keyAndOptions) {
if (opts.some((o) => o.value === localSettings[key])) continue;
settings[key] = DEFAULT_SETTINGS[key];
}

Expand Down
3 changes: 3 additions & 0 deletions src/content-view/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ErrorBoundary } from '../shared/error-boundary';
import { addMessageListener, Message } from '../extension-utils/api';
import { loadSettings, Settings } from '../extension-utils/settings';
import { splitTextByLine } from '../content-utils/text-util';
import { updateResolveRules } from '../shared/resolve-rules';

let visible = false;
let reactRoot: Root | null = null;
Expand Down Expand Up @@ -70,6 +71,8 @@ function findAutoOpenRule(settings: Settings): [string, number] | void {
}

void loadSettings().then((s) => {
void updateResolveRules();

const rule = findAutoOpenRule(s);
if (!rule) return;

Expand Down
2 changes: 1 addition & 1 deletion src/extension-utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function sendTabMessage(tab: Tab, name: string) {
chrome.tabs
.sendMessage(tab.id, { name })
.then((response: any) => {
if (import.meta.env.DEV) console.log('[sendTabMessage Success]:', response.response);
if (import.meta.env.DEV) console.log('[sendTabMessage Success]:', response);
})
.catch((error: any) => {
if (import.meta.env.DEV) console.error('[sendTabMessage Error]:', error);
Expand Down
6 changes: 4 additions & 2 deletions src/extension-utils/settings.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { loadStorage, saveStorage } from './api';
import { RESOLVE_RULES, ResolveRule } from '../shared/resolve-rules';
import { RESOLVE_RULES, RESOLVE_RULES_VERSION, ResolveRule } from '../shared/resolve-rules';

export interface Settings {
position: string;
Expand All @@ -9,6 +9,7 @@ export interface Settings {
// 已读版本号,用于判断是否已经查看releaseNote
knownVersion: string;
resolveRules: ResolveRule[];
resolveRulesVersion: string;
}

export const THEME_OPTIONS = [
Expand Down Expand Up @@ -37,6 +38,7 @@ export const DEFAULT_SETTINGS: Settings = {
autoOpenRules: import.meta.env.DEV ? '**' : '',
knownVersion: '',
resolveRules: RESOLVE_RULES,
resolveRulesVersion: RESOLVE_RULES_VERSION,
};

export const SETTINGS_KEYS = Object.keys(DEFAULT_SETTINGS);
Expand All @@ -48,6 +50,6 @@ export function loadSettings() {
return loadStorage(SETTINGS_KEYS) as Promise<Settings>;
}

export function saveSettings(settings: Settings) {
export function saveSettings(settings: Partial<Settings>) {
return saveStorage(settings) as Promise<void>;
}
17 changes: 17 additions & 0 deletions src/options-view/options.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,24 @@ import {
saveSettings,
STRATEGY_OPTIONS,
} from '../extension-utils/settings';
import { updateResolveRules } from '../shared/resolve-rules';
import pkg from '../../package.json';
import './options.less';

function openShortcutsPage() {
createTab('chrome://extensions/shortcuts');
}

function onUpdateResolveRules() {
updateResolveRules()
.then(() => {
return message.success('更新成功');
})
.catch((err: Error) => {
return message.error(err.message || '更新失败');
});
}

function Options() {
const ua = window.navigator.userAgent;

Expand Down Expand Up @@ -93,6 +104,12 @@ function Options() {
);
})}

<Form.Item label="🌐&ensp;解析规则">
<Button onClick={onUpdateResolveRules} type="link">
更新
</Button>
</Form.Item>

<p>🚁&ensp;自动打开规则</p>

<Form.Item name={SETTINGS_KEYMAP.autoOpenRules}>
Expand Down
35 changes: 35 additions & 0 deletions src/shared/resolve-rules.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"version": "1.0.0",
"rules": [
{
"pages": ["https://www.huxiu.com/article/**"],
"article": "#article-content",
"headings": ["#article-content [label*=标题][class*=title]"]
},
{
"pages": ["https://my.oschina.net/u/**"],
"article": ".article-detail .content",
"headings": []
},
{
"pages": ["https://mp.weixin.qq.com/s/**"],
"article": "#js_content",
"headings": []
},
{
"pages": ["https://www.iteye.com/blog/**"],
"article": ".iteye-blog-content-contain",
"headings": []
},
{
"pages": ["https://www.iteye.com/news/**"],
"article": "#news_content",
"headings": []
},
{
"pages": ["https://zhuanlan.zhihu.com/p/**"],
"article": ".Post-RichText",
"headings": []
}
]
}
57 changes: 25 additions & 32 deletions src/shared/resolve-rules.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,9 @@
import * as micromatch from 'micromatch';
import resolveRuleJson from './resolve-rules.json';
import { loadSettings, saveSettings, Settings } from '../extension-utils/settings';

export const RESOLVE_RULES: ResolveRule[] = [
{
pages: ['https://www.huxiu.com/article/**'],
article: '#article-content',
headings: ['#article-content [label*=标题][class*=title]'],
},
{
pages: ['https://my.oschina.net/u/**'],
article: '.article-detail .content',
headings: [],
},
{
pages: ['https://mp.weixin.qq.com/s/**'],
article: '#js_content',
headings: [],
},
{
pages: ['https://www.iteye.com/blog/**'],
article: '.iteye-blog-content-contain',
headings: [],
},
{
pages: ['https://www.iteye.com/news/**'],
article: '#news_content',
headings: [],
},
{
pages: ['https://zhuanlan.zhihu.com/p/**'],
article: '.Post-RichText',
headings: [],
},
];
export const RESOLVE_RULES_VERSION = resolveRuleJson.version as string;
export const RESOLVE_RULES: ResolveRule[] = resolveRuleJson.rules;

export function matchResolveRule(rules: ResolveRule[]) {
const pathInUrl = location.host + location.pathname;
Expand All @@ -40,6 +12,27 @@ export function matchResolveRule(rules: ResolveRule[]) {
return rules.find((c) => micromatch.some([location.href, pathInUrl], c.pages));
}

/** 更新解析规则 **/
export async function updateResolveRules() {
const settings: Settings = await loadSettings();

const resolveConfigUrl = import.meta.env.VITE_RESOLVE_URL as string;
const resolveConfigJson = (await fetch(resolveConfigUrl).then((r) => {
return r.ok ? r.json() : new Error(`${r.status} ${r.statusText}`);
})) as { version: string; rules: ResolveRule[] };

if (!resolveConfigJson?.version) return Promise.reject(resolveConfigJson);

if (!settings?.resolveRulesVersion || resolveConfigJson.version > settings.resolveRulesVersion) {
return saveSettings({
resolveRules: resolveConfigJson.rules,
resolveRulesVersion: resolveConfigJson.version,
});
}

return Promise.reject(new Error('更新失败'));
}

export type ResolveRule = {
// 网页匹配规则
pages: string[];
Expand Down

0 comments on commit 5d88d8f

Please sign in to comment.