Skip to content

Commit

Permalink
v1.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhUyU1997 committed Apr 21, 2024
1 parent 5fddaff commit 81bbe31
Show file tree
Hide file tree
Showing 13 changed files with 582 additions and 215 deletions.
86 changes: 70 additions & 16 deletions entrypoints/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import {
SiteModeStorage,
onMessage,
} from "./common/messaging";
import { LemmaData } from "./common/define";
import { logger } from "./common/logger";
import { IsSupported } from "./common/utils";
import { safeStorage } from "./common/storage";
import { DEFAULT_HIGHLIGHT_STYLE } from "./common/style";

async function loadJsonFile(path: PublicPath) {
const file_path = browser.runtime.getURL(path);
Expand Down Expand Up @@ -62,33 +63,36 @@ class BGHelper {
}
}
static loadSiteMode() {
return storage.getItem<SiteModeStorage>("local:site-mode").then((data) => {
if (!data) storage.setItem<SiteModeStorage>("local:site-mode", {});
return safeStorage.getItem("local:site-mode").then((data) => {
if (!data) safeStorage.setItem("local:site-mode", {});
BGHelper.siteModeRecord = data ?? {};
});
}

static async loadMode() {
const mode = await storage.getItem<GlobalMode>("local:mode");
if (!mode) storage.setItem<GlobalMode>("local:mode", "enable");
const mode = await safeStorage.getItem("local:mode");
if (!mode) safeStorage.setItem("local:mode", "enable");

storage.watch<GlobalMode>("local:mode", (newValue) => {
safeStorage.watch("local:mode", (newValue) => {
BGHelper.mode = newValue ?? "enable";
});
BGHelper.mode = mode ?? "enable";
}
static syncSiteModeToStorage() {
return storage.setItem<SiteModeStorage>(
"local:site-mode",
BGHelper.siteModeRecord
);
return safeStorage.setItem("local:site-mode", BGHelper.siteModeRecord);
}

static async load() {
const precent = await storage.getItem<number>("local:percent");
if (!precent) storage.setItem<number>("local:percent", 30);
const ignore = storage.getItem<string[]>("local:ignore-word");
if (!ignore) storage.setItem<string[]>("local:ignore-word", []);
const precent = await safeStorage.getItem("local:percent");
if (!precent) safeStorage.setItem("local:percent", 30);
const ignore = await safeStorage.getItem("local:ignore-word");
if (!ignore) safeStorage.setItem("local:ignore-word", []);

const preference = await safeStorage.getItem("local:preference");
if (!preference)
safeStorage.setItem("local:preference", {
highlight: DEFAULT_HIGHLIGHT_STYLE,
});

await BGHelper.loadSiteMode();
await BGHelper.loadMode();
Expand All @@ -100,10 +104,10 @@ export default defineBackground(async () => {
logger.log("Hello background!", { id: browser.runtime.id });
browser.runtime.onInstalled.addListener(() => {
loadRankFile().then((data) => {
storage.setItem<string[]>("local:rank", data);
safeStorage.setItem("local:rank", data);
});
loadLemmaFile().then((data) => {
storage.setItem<LemmaData>("local:lemma", data);
safeStorage.setItem("local:lemma", data);
});
});

Expand Down Expand Up @@ -134,4 +138,54 @@ export default defineBackground(async () => {
const mode = BGHelper.mode;
return IsSupported(mode, siteMode);
});
onMessage("replaceCSS", async (message) => {
const { old, css } = message.data;
logger.log("injectCSS", css);
const tabId = message.sender?.tab?.id;

if (tabId) {
await browser.scripting.removeCSS({
css: old,
target: {
allFrames: true,
tabId,
},
});
browser.scripting.insertCSS({
css,
target: {
allFrames: true,
tabId,
},
});
}
});
onMessage("injectCSS", (message) => {
const { css } = message.data;
logger.log("injectCSS", css);
const tabId = message.sender?.tab?.id;

if (tabId)
browser.scripting.insertCSS({
css,
target: {
allFrames: true,
tabId,
},
});
});
onMessage("removeCSS", (message) => {
const { css } = message.data;
logger.log("removeCSS", css);
const tabId = message.sender?.tab?.id;

if (tabId)
browser.scripting.removeCSS({
css,
target: {
allFrames: true,
tabId,
},
});
});
});
16 changes: 10 additions & 6 deletions entrypoints/common/messaging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,22 @@ export type GlobalMode = "enable" | "disable" | "forbidden";

export type SitMode = "follow" | "exclude" | "include";

export type SiteModeStorage = Record<string, SitMode>
export type SiteModeStorage = Record<string, SitMode>;
interface ProtocolMap {
changeSetting({ enable }: { enable: boolean }): void;
notifyBackground({ url, hidden }: { url: string; hidden: boolean }): void;
translation({ words }: { words: string[] }): Record<string, string>;
changeSetting(data: { enable: boolean }): void;
notifyBackground(data: { url: string; hidden: boolean }): void;
translation(data: { words: string[] }): Record<string, string>;
getGlobalMode(): GlobalMode;
// setGlobalMode(mode: GlobalMode): void;
getSiteMode(hostName: string): SitMode;
setSiteMode({ hostName, mode }: { hostName: string; mode: SitMode }): void;
notifySiteModeChanged(mode: SitMode) : void
setSiteMode(data: { hostName: string; mode: SitMode }): void;
notifySiteModeChanged(mode: SitMode): void;

isSupported(hostName: string): boolean;
replaceCSS(data: { old:string, css: string }): void;

injectCSS(data: { css: string }): void;
removeCSS(data: { css: string }): void;
}

export const { sendMessage, onMessage } =
Expand Down
44 changes: 44 additions & 0 deletions entrypoints/common/storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { GetItemOptions, Unwatch, WatchCallback } from "wxt/storage";
import { LemmaData } from "./define";
import { GlobalMode, SitMode } from "./messaging";

export interface Preference {
highlight: string;
}

interface StorageMap {
"local:percent": number;
"local:rank": string[];
"local:lemma": LemmaData;
"local:ignore-word": string[];
"local:site-mode": Record<string, SitMode>;
"local:mode": GlobalMode;
"local:preference": Preference;
}

export interface GenericStorage<TStorageMap extends Record<string, any>> {
getItem<K extends Extract<keyof TStorageMap, string>>(
key: K,
opts?: GetItemOptions<TStorageMap[K]>
): Promise<TStorageMap[K] | null>;
setItem<K extends Extract<keyof TStorageMap, string>>(
key: K,
value: TStorageMap[K] | null
): Promise<void>;
watch<K extends Extract<keyof TStorageMap, string>>(
key: K,
cb: WatchCallback<TStorageMap[K] | null>
): Unwatch;
unwatch(): void;
}

declare type ExtensionMessenger<TStorageMap extends Record<string, any>> =
GenericStorage<TStorageMap>;

function defineExtensionStorage<
TStorageMap extends Record<string, any> = Record<string, any>
>(): ExtensionMessenger<TStorageMap> {
return storage;
}

export const safeStorage = defineExtensionStorage<StorageMap>();
26 changes: 26 additions & 0 deletions entrypoints/common/style.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const Template = (css: string) =>
`.insight-word-enable insight-word.insight-word-highlight {
/* 修改下面样式 */
${css
.split("\n")
.filter((i) => i.trim() !== "")
.map((i) => " " + i.trim())
.join("\n")}
/* 结束 */
}`;

export const PRESET_HIGHLIGHT_STYLE = [
Template(`
text-shadow: 0 0 5px #ade30b, 0 0 5px #ade30b
`),
Template(`
text-decoration: rgba(10, 163, 205, 0.491) wavy underline;
`),
Template(`
background-color: rgba(10, 163, 205, 0.491);
`),
Template(`
filter: drop-shadow(0 0 3px #ade30b) drop-shadow(0 0 3px #ade30b);
`),
];
export const DEFAULT_HIGHLIGHT_STYLE = PRESET_HIGHLIGHT_STYLE[0];
44 changes: 35 additions & 9 deletions entrypoints/content.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
import "./index.less";
import { GlobalMode, SitMode, onMessage } from "./common/messaging";
import {
GlobalMode,
SitMode,
onMessage,
sendMessage,
} from "./common/messaging";
import { Unwatch, WatchCallback } from "wxt/storage";
import { logger } from "./common/logger";
import Render from "./page/render";
import { Helper } from "./page/helper";
import { Setting } from "./page/setting";
import { Highlight } from "./page/highlight";
import { Preference, safeStorage } from "./common/storage";

export default defineContentScript({
matches: ["*://*/*"],
allFrames: true,
runAt: "document_idle",

async main(ctx) {
async main(ctx: any) {
logger.log("Hello content.");
const support = await Setting.isSupported();
if (!support) {
Expand All @@ -22,7 +28,7 @@ export default defineContentScript({

await Setting.load();
const mode = Setting.mode;
const percent = await storage.getItem<number>("local:percent");
const percent = await safeStorage.getItem("local:percent");
logger.log("local:mode", mode);
logger.log("local:percent", percent);

Expand Down Expand Up @@ -75,11 +81,24 @@ export default defineContentScript({
if (newValue) Helper.updataIgnore(newValue);
Highlight.updateStyleByIgnore();
};

const watchCbPreference: WatchCallback<Preference | null> = (
newValue,
oldValue
) => {
logger.log("watch local:preference", newValue);
if (newValue) {
const old = Setting.preference.highlight;
Setting.preference = newValue;
sendMessage("replaceCSS", { old, css: Setting.preference.highlight });
}
};
const syncSetting = async () => {
const siteMode = await Setting.getSiteModeFromBG();
const mode = await storage.getItem<GlobalMode>("local:mode");
const percent = await storage.getItem<number>("local:percent");
const ignoreWord = await storage.getItem<string[]>("local:ignore-word");
const mode = await safeStorage.getItem("local:mode");
const percent = await safeStorage.getItem("local:percent");
const ignoreWord = await safeStorage.getItem("local:ignore-word");
const preference = await safeStorage.getItem("local:preference");

if (siteMode !== Setting.siteMode) {
watchCbSiteMode(siteMode, Setting.siteMode);
Expand All @@ -95,6 +114,10 @@ export default defineContentScript({
if (ignoreWord?.length !== Helper.ignoreSet.size) {
watchCbIgnoreWord(ignoreWord, []);
}

if (preference?.highlight !== Setting.preference.highlight) {
watchCbPreference(preference, Setting.preference);
}
};

let unwatchList: Unwatch[] = [];
Expand All @@ -115,10 +138,13 @@ export default defineContentScript({
watchCbSiteMode(siteMode, Setting.siteMode);
})
);
unwatchList.push(storage.watch<GlobalMode>("local:mode", watchCbMode));
unwatchList.push(storage.watch<number>("local:percent", watchCbFilter));
unwatchList.push(safeStorage.watch("local:mode", watchCbMode));
unwatchList.push(safeStorage.watch("local:percent", watchCbFilter));
unwatchList.push(
safeStorage.watch("local:ignore-word", watchCbIgnoreWord)
);
unwatchList.push(
storage.watch<string[]>("local:ignore-word", watchCbIgnoreWord)
safeStorage.watch("local:preference", watchCbPreference)
);
};

Expand Down
18 changes: 3 additions & 15 deletions entrypoints/index.less
Original file line number Diff line number Diff line change
@@ -1,19 +1,7 @@
.insight-word-enable {
insight-word.insight-word-highlight {
display: inline;
position: relative;
text-decoration: rgba(10, 163, 205, 0.491) wavy underline;
}

code insight-word.insight-word-highlight {
text-decoration: inherit;
}

pre insight-word.insight-word-highlight {
text-decoration: inherit;
}

code insight-word.insight-word-highlight,
pre insight-word.insight-word-highlight,
insight-word.insight-word-ignore {
text-decoration: inherit;
all: inherit;
}
}
20 changes: 15 additions & 5 deletions entrypoints/page/setting.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { logger } from "../common/logger";
import { GlobalMode, SitMode, sendMessage } from "../common/messaging";
import { Preference, safeStorage } from "../common/storage";
import { DEFAULT_HIGHLIGHT_STYLE } from "../common/style";
import { IsSupported } from "../common/utils";

export class Setting {
static mode: GlobalMode = "enable";
static siteMode: SitMode = "follow";
static enable = true;

static filterPercent = 30;
static preference: Preference = {
highlight: DEFAULT_HIGHLIGHT_STYLE,
};
static setEnable(value: GlobalMode) {
Setting.mode = value;
}
Expand Down Expand Up @@ -44,10 +48,16 @@ export class Setting {
}

static async load() {
const mode = await storage.getItem<GlobalMode>("local:mode");
Setting.mode = mode ?? "enable";
const mode = await safeStorage.getItem("local:mode");
Setting.mode = mode ?? Setting.mode;
const siteMode = await Setting.getSiteModeFromBG();
Setting.siteMode = siteMode ?? "follow";
await Setting.checkEnable();
Setting.siteMode = siteMode ?? Setting.siteMode;
const preference = await safeStorage.getItem("local:preference");
Setting.preference = preference ?? Setting.preference;
if (await Setting.checkEnable()) {
sendMessage("injectCSS", {
css: Setting.preference.highlight,
});
}
}
}
4 changes: 2 additions & 2 deletions entrypoints/popup/App.css
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#root {
min-width: 300px;
min-width: 320px;
max-width: 1280px;
max-height: 600px;
margin: 0 auto;
padding: 1rem;
text-align: center;
}

Loading

0 comments on commit 81bbe31

Please sign in to comment.