diff --git a/packages/webextension/app/manifest.json b/packages/webextension/app/manifest.json index 7e55acd..2b1128b 100644 --- a/packages/webextension/app/manifest.json +++ b/packages/webextension/app/manifest.json @@ -38,13 +38,12 @@ ], "permissions": [ "activeTab", - "contextMenus", "webRequest", "webRequestBlocking", "tabs", "" ], - "applications": { + "__firefox__applications": { "gecko": { "id": "editor@textlint.github.com" } diff --git a/packages/webextension/app/scripts/InstalledApp/component/InstalledTextlintList.tsx b/packages/webextension/app/scripts/InstalledApp/component/InstalledTextlintList.tsx index 9770530..728ab39 100644 --- a/packages/webextension/app/scripts/InstalledApp/component/InstalledTextlintList.tsx +++ b/packages/webextension/app/scripts/InstalledApp/component/InstalledTextlintList.tsx @@ -4,6 +4,7 @@ import { ActionGroup, Flex, Item, ListBox, Text } from "@adobe/react-spectrum"; import { usePort } from "../StateContext"; import { Script } from "../../background/database"; import FileCode from "@spectrum-icons/workflow/FileCode"; +import { logger } from "../../utils/logger"; export type InstalledTextlintListProps = { url: string; @@ -18,7 +19,7 @@ export const InstalledTextlintList = (props: InstalledTextlintListProps) => { items: res }; } catch (error) { - console.error(error); + logger.error(error); return { items: [] }; diff --git a/packages/webextension/app/scripts/InstalledApp/pages/EditPage.tsx b/packages/webextension/app/scripts/InstalledApp/pages/EditPage.tsx index 42790bf..c940858 100644 --- a/packages/webextension/app/scripts/InstalledApp/pages/EditPage.tsx +++ b/packages/webextension/app/scripts/InstalledApp/pages/EditPage.tsx @@ -5,6 +5,7 @@ import { usePort } from "../StateContext"; import { ScriptMeta } from "../component/ScriptMeta"; import "./EditPage.css"; import { Flex } from "@adobe/react-spectrum"; +import { logger } from "../../utils/logger"; export type EditPageProps = { name?: string; @@ -21,7 +22,7 @@ export const EditPage = (props: EditPageProps) => { const port = usePort(); const onSave = (textlintrc: string) => { if (!props.name || !props.namespace) { - console.error("props is wrong", props); + logger.error("props is wrong", props); return; } port.updateScript({ @@ -33,14 +34,13 @@ export const EditPage = (props: EditPageProps) => { useEffect(() => { (async function loadScript() { if (!props.name || !props.namespace) { - console.error("props is wrong", props); + logger.error("props is wrong", props); return; } const script = await port.findScriptsWithName({ name: props.name, namespace: props.namespace }); if (!script) { - return console.error("script is not found", props); + return logger.error("script is not found", props); } - console.log(); setMeta({ name: script.name, namespace: script.namespace, diff --git a/packages/webextension/app/scripts/background.ts b/packages/webextension/app/scripts/background.ts index 1e92bf9..0fe74c1 100644 --- a/packages/webextension/app/scripts/background.ts +++ b/packages/webextension/app/scripts/background.ts @@ -6,9 +6,10 @@ import { openDatabase } from "./background/database"; import { LintEngineAPI } from "textchecker-element"; import { TextlintResult } from "@textlint/types"; import { scriptWorkerSet } from "./background/scriptWorkerSet"; +import { logger } from "./utils/logger"; // browser.runtime.onInstalled.addListener((details) => { -// // console.log("previousVersion", details.previousVersion); +// // logger.log("previousVersion", details.previousVersion); // }); // // browser.tabs.onUpdated.addListener(async (tabId) => { @@ -50,7 +51,7 @@ async function openInstallDialog(url: string) { browser.webRequest.onHeadersReceived.addListener( (details) => { - if (details.method != "GET") return {}; + if (details.method !== "GET") return {}; if (!responseHasUserScriptType(details.responseHeaders)) return {}; openInstallDialog(details.url); // https://stackoverflow.com/a/18684302 @@ -79,7 +80,7 @@ browser.runtime.onConnect.addListener(async (port) => { } const db = await openDatabase(); const originUrl = port.sender?.url; - console.log("[background] originUrl", originUrl); + logger.log("originUrl", originUrl); if (!originUrl) { return; } @@ -101,7 +102,7 @@ browser.runtime.onConnect.addListener(async (port) => { return Comlink.expose(exports, createBackgroundEndpoint(port)); } const scripts = await db.findScriptsWithPatten(originUrl); - console.log("scripts", scripts); + logger.log("scripts", scripts); const scriptWorkers = scripts.map((script) => { const runningWorker = scriptWorkerSet.get(script); if (runningWorker) { @@ -118,17 +119,17 @@ browser.runtime.onConnect.addListener(async (port) => { ext: script.ext }; }); - console.log("[Background] workers started", scriptWorkers); + logger.log("workers started", scriptWorkers); // Support multiple workers const lintEngine: LintEngineAPI = { async lintText({ text }: { text: string }): Promise { - console.log("[Background] text:", text); + logger.log("text:", text); const allLintResults = await Promise.all( scriptWorkers.map(({ worker, ext }) => { return worker.createLintEngine({ ext }).lintText({ text }); }) ); - console.log("[Background] lintText", allLintResults); + logger.log("lintText", allLintResults); return allLintResults.flat(); }, async fixText({ text }): Promise<{ output: string }> { @@ -157,13 +158,13 @@ browser.runtime.onConnect.addListener(async (port) => { } }; port.onDisconnect.addListener(async () => { - console.log("[Background] dispose worker"); + logger.log("dispose worker"); const scripts = await db.findScriptsWithPatten(originUrl); scripts.forEach((script) => { scriptWorkerSet.delete({ script: script, url: originUrl }); }); }); - console.log("[Background] content port", port); + logger.log("content port", port); scriptWorkerSet.dump(); Comlink.expose(backgroundExposedObject, createBackgroundEndpoint(port)); await Promise.all(scriptWorkers.map(({ worker }) => worker.ready())); diff --git a/packages/webextension/app/scripts/background/database.ts b/packages/webextension/app/scripts/background/database.ts index b963c62..035b3d0 100644 --- a/packages/webextension/app/scripts/background/database.ts +++ b/packages/webextension/app/scripts/background/database.ts @@ -16,6 +16,10 @@ export type Script = { export type TextlintDBSchema = { scripts: Script[]; }; +/** + * Create unique key of Script + * @param script + */ export const keyOfScript = (script: { name: string; namespace: string }): string => { return `${script.namespace}@${script.name}`; }; diff --git a/packages/webextension/app/scripts/background/scriptWorkerSet.ts b/packages/webextension/app/scripts/background/scriptWorkerSet.ts index 2f1db33..63883a7 100644 --- a/packages/webextension/app/scripts/background/scriptWorkerSet.ts +++ b/packages/webextension/app/scripts/background/scriptWorkerSet.ts @@ -1,5 +1,6 @@ import { TextlintWorker } from "./textlint"; import { keyOfScript, Script } from "./database"; +import { logger } from "../utils/logger"; // worker: Set const _workerRunningUrlMap = new Map>(); @@ -30,7 +31,7 @@ export const scriptWorkerSet = { return _scriptRunningWorkerMap.delete(keyOfScript(script)); }, dump() { - console.log("Running Scripts: ", _scriptRunningWorkerMap.keys()); - console.log("Running Workers x URLs: ", _workerRunningUrlMap.entries()); + logger.log("Running Scripts: ", _scriptRunningWorkerMap.keys()); + logger.log("Running Workers x URLs: ", _workerRunningUrlMap.entries()); } }; diff --git a/packages/webextension/app/scripts/background/textlint.ts b/packages/webextension/app/scripts/background/textlint.ts index b89f418..5f717c4 100644 --- a/packages/webextension/app/scripts/background/textlint.ts +++ b/packages/webextension/app/scripts/background/textlint.ts @@ -8,6 +8,8 @@ import { } from "@textlint/script-compiler"; import type { TextlintRcConfig } from "@textlint/config-loader"; import { Script } from "./database"; +import { logger } from "../utils/logger"; + const waiterForInit = (worker: Worker) => { let initialized = false; let _resolve: null | ((init: boolean) => void) = null; @@ -118,7 +120,7 @@ export const createTextlintWorker = (script: Script) => { }); }; const log = (...args: any[]) => { - console.log("[Background]", ...args); + logger.log(...args); }; return { createLintEngine({ ext }: { ext: string }) { diff --git a/packages/webextension/app/scripts/contentScript.ts b/packages/webextension/app/scripts/contentScript.ts index 6541d3d..6bd3019 100644 --- a/packages/webextension/app/scripts/contentScript.ts +++ b/packages/webextension/app/scripts/contentScript.ts @@ -4,13 +4,14 @@ import { createEndpoint } from "comlink-extension"; import * as Comlink from "comlink"; import type { backgroundExposedObject } from "./background"; import { nonRandomKey } from "./shared/page-contents-shared"; +import { logger } from "./utils/logger"; const rawPort = browser.runtime.connect(); // content-script <-> background page const port = Comlink.wrap(createEndpoint(rawPort)); rawPort.onMessage.addListener((event) => { if (event === "textlint-editor-boot") { - console.log("[ContentScript]", "boot event received"); + logger.log("[ContentScript]", "boot event received"); // Inject page-script try { const script = browser.extension.getURL("scripts/pageScript.js"); @@ -18,7 +19,7 @@ rawPort.onMessage.addListener((event) => { pageScript.src = script; document.body.append(pageScript); } catch (error) { - console.error(error); + logger.error(error); } } }); diff --git a/packages/webextension/app/scripts/install-dialog.ts b/packages/webextension/app/scripts/install-dialog.ts index fb89464..56827be 100644 --- a/packages/webextension/app/scripts/install-dialog.ts +++ b/packages/webextension/app/scripts/install-dialog.ts @@ -3,6 +3,7 @@ import * as Comlink from "comlink"; import type { backgroundExposedObject } from "./background"; import { browser } from "webextension-polyfill-ts"; import { parseMetadata, TextlintScriptMetadata } from "@textlint/script-parser"; +import { logger } from "./utils/logger"; const port = Comlink.wrap(createEndpoint(browser.runtime.connect())); @@ -29,7 +30,7 @@ async function installHandler({ textlintrc: JSON.stringify(metadata.config, null, 4) }); } catch (error) { - console.error("[InstallDialog]", error); + logger.error("[InstallDialog]", error); } } diff --git a/packages/webextension/app/scripts/pageScript.ts b/packages/webextension/app/scripts/pageScript.ts index 6202f5f..004f81c 100644 --- a/packages/webextension/app/scripts/pageScript.ts +++ b/packages/webextension/app/scripts/pageScript.ts @@ -2,10 +2,11 @@ import { attachToTextArea, LintEngineAPI } from "textchecker-element"; import { nonRandomKey } from "./shared/page-contents-shared"; import type { TextlintMessage } from "@textlint/types"; import { applyFixesToText } from "@textlint/source-code-fixer"; +import { logger } from "./utils/logger"; const commandHandler = (command: string, args: any): Promise => { return new Promise((resolve) => { - console.log("[PageScript]", command, args); + logger.log("[PageScript]", command, args); const listener = (message: MessageEvent) => { if ( message.data && @@ -45,7 +46,7 @@ const isIgnored = ({ text, message }: { text: string; message: TextlintMessage } const lintEngine: LintEngineAPI = { async lintText({ text }) { const results = await commandHandler>("lintText", { text }); - console.log("results", results); + logger.log("results", results); return results.map((result) => { return { filePath: result.filePath, @@ -78,7 +79,7 @@ async function contentScriptMain() { if (set.has(textAreaElement)) { return; } - console.log("[contentScript] attach textarea", textAreaElement); + logger.log("[contentScript] attach textarea", textAreaElement); attachToTextArea({ textAreaElement: textAreaElement, lintingDebounceMs: 200, @@ -106,7 +107,7 @@ async function contentScriptMain() { }); } -console.log("[PageScript]", "main loaded"); +logger.log("[PageScript]", "main loaded"); contentScriptMain().catch((error) => { - console.error("[PageScript] Error", error); + logger.error("[PageScript] Error", error); }); diff --git a/packages/webextension/app/scripts/utils/logger.ts b/packages/webextension/app/scripts/utils/logger.ts new file mode 100644 index 0000000..6e0a171 --- /dev/null +++ b/packages/webextension/app/scripts/utils/logger.ts @@ -0,0 +1,29 @@ +// contentScript does not loggin in production by default +const canLog = () => { + // localStorage.setItem("DEBUG", "@textlint/editor"); + const enabledDebugStorage = + typeof window !== "undefined" && + typeof window.localStorage !== "undefined" && + (window.localStorage.getItem("DEBUG")?.includes("@textlint") || window.localStorage.getItem("DEBUG") === "*"); + // ?debug_textlint + const enabledDebugLocation = + typeof window !== "undefined" && + typeof window.location !== "undefined" && + new URL(window.location.href).searchParams.has("debug_textlint"); + + return process.env.NODE_ENV === "development" || enabledDebugLocation || enabledDebugStorage; +}; +export const logger = { + log(...args: any[]) { + if (!canLog()) { + return; + } + console.log("[@textlint/editor]", ...args); + }, + error(...args: any[]) { + if (!canLog()) { + return; + } + console.error("[@textlint/editor]", ...args); + } +};