| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338 |
- const PANEL_ID = 'grammar-panel';
- const PANEL_STYLE_ID = 'grammar-panel-style';
- const PARAGRAPH_SELECTORS = 'p, article p, section p, div';
- let panelEl = null;
- function ensurePanelStyle() {
- if (document.getElementById(PANEL_STYLE_ID)) return;
- const style = document.createElement('style');
- style.id = PANEL_STYLE_ID;
- style.textContent = `
- .grammar-panel {
- position: fixed;
- right: 16px;
- bottom: 16px;
- width: 220px;
- padding: 12px;
- border-radius: 10px;
- box-shadow: 0 8px 24px rgba(15, 23, 42, 0.18);
- background: #fff;
- font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
- z-index: 2147483647;
- border: 1px solid rgba(15, 23, 42, 0.08);
- }
- .grammar-panel__header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 10px;
- }
- .grammar-panel__title {
- font-size: 14px;
- font-weight: 600;
- margin: 0;
- color: #0f172a;
- }
- .grammar-panel__close {
- background: transparent;
- border: none;
- width: 10px;
- height: 20px;
- font-size: 16px;
- cursor: pointer;
- color: #475569;
- }
- .grammar-panel button {
- width: 100%;
- padding: 8px;
- margin-bottom: 6px;
- border: none;
- border-radius: 6px;
- font-size: 13px;
- cursor: pointer;
- background: #2563eb;
- color: white;
- transition: background 0.2s ease;
- }
- .grammar-panel button:hover {
- background: #1d4ed8;
- }
- .grammar-panel__status {
- min-height: 16px;
- font-size: 11px;
- color: #475569;
- margin-top: 4px;
- }
- .grammar-panel__status.error {
- color: #dc2626;
- }
- .grammar-panel__status.success {
- color: #0a8754;
- }
- `;
- document.head.appendChild(style);
- }
- function callBackend(payload) {
- return new Promise((resolve, reject) => {
- chrome.runtime.sendMessage(
- { type: 'GRAMMAR_API_REQUEST', ...payload },
- (response) => {
- if (chrome.runtime.lastError) {
- reject(new Error(chrome.runtime.lastError.message));
- return;
- }
- if (!response) {
- reject(new Error('后台未返回数据。'));
- return;
- }
- if (response.error) {
- reject(new Error(response.error));
- return;
- }
- resolve(response);
- }
- );
- });
- }
- function isParagraphElement(node) {
- return (
- node &&
- node.nodeType === Node.ELEMENT_NODE &&
- node.matches &&
- node.matches(PARAGRAPH_SELECTORS)
- );
- }
- function collectParagraphNodes(container) {
- if (!container || container.nodeType !== Node.ELEMENT_NODE) return [];
- const paragraphs = Array.from(container.querySelectorAll('p')).filter(
- (el) => el.innerText.trim()
- );
- if (paragraphs.length > 0) return paragraphs;
- return [container];
- }
- function buildParagraphTarget(nodes) {
- const usableNodes = nodes.filter(
- (node) => node && node.innerText && node.innerText.trim()
- );
- if (usableNodes.length === 0) {
- throw new Error('未找到可用段落文本。');
- }
- const originals = usableNodes.map((node) => node.innerHTML);
- const paragraphs = usableNodes.map((node) => node.innerText.trim());
- return {
- payload: { paragraphs },
- apply(htmlList) {
- const list = Array.isArray(htmlList) ? htmlList : [];
- usableNodes.forEach((node, idx) => {
- const html = list[idx];
- if (typeof html === 'string' && html.trim()) {
- node.innerHTML = html;
- }
- });
- },
- restore() {
- usableNodes.forEach((node, idx) => {
- node.innerHTML = originals[idx];
- });
- }
- };
- }
- function getSelectionTarget() {
- const selection = window.getSelection();
- if (!selection || selection.rangeCount === 0) {
- throw new Error('请先在页面中选择一段文本。');
- }
- const range = selection.getRangeAt(0);
- if (range.collapsed) {
- throw new Error('所选文本为空。');
- }
- const root =
- range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE
- ? range.commonAncestorContainer
- : range.commonAncestorContainer.parentElement || document.body;
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
- acceptNode(node) {
- if (!(node instanceof HTMLElement)) return NodeFilter.FILTER_SKIP;
- return isParagraphElement(node) && range.intersectsNode(node)
- ? NodeFilter.FILTER_ACCEPT
- : NodeFilter.FILTER_SKIP;
- }
- });
- const nodes = [];
- let current = walker.nextNode();
- while (current) {
- nodes.push(current);
- current = walker.nextNode();
- }
- if (nodes.length === 0) {
- const fallback =
- (range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE
- ? range.commonAncestorContainer
- : range.commonAncestorContainer.parentElement) || document.body;
- nodes.push(fallback.closest(PARAGRAPH_SELECTORS) || fallback);
- }
- return buildParagraphTarget(nodes);
- }
- function getParagraphTarget() {
- const selection = window.getSelection();
- let node =
- selection && selection.rangeCount > 0
- ? selection.getRangeAt(0).commonAncestorContainer
- : document.activeElement;
- if (!node) {
- node = document.body;
- }
- if (node.nodeType === Node.TEXT_NODE) {
- node = node.parentElement;
- }
- const paragraph =
- node.closest(PARAGRAPH_SELECTORS) || document.querySelector('p') || document.body;
- return buildParagraphTarget([paragraph]);
- }
- function getArticleTarget() {
- const container =
- document.querySelector('article') ||
- document.querySelector('main') ||
- document.body;
- const nodes = collectParagraphNodes(container).filter(
- (node) => node.innerText.trim()
- );
- return buildParagraphTarget(nodes);
- }
- async function handleAnalyze(mode) {
- let targetGetter;
- switch (mode) {
- case 'selection':
- targetGetter = getSelectionTarget;
- break;
- case 'paragraph':
- targetGetter = getParagraphTarget;
- break;
- case 'article':
- targetGetter = getArticleTarget;
- break;
- default:
- throw new Error('未知的分析模式。');
- }
- const target = targetGetter();
- try {
- const response = await callBackend(target.payload);
- const htmlList =
- response.highlightedHtmls ||
- (response.highlightedHtml ? [response.highlightedHtml] : []);
- if (!htmlList || htmlList.length === 0) {
- throw new Error('后台未返回数据。');
- }
- target.apply(htmlList);
- return {};
- } catch (error) {
- target.restore?.();
- throw error;
- }
- }
- function setPanelStatus(message, type = '') {
- if (!panelEl) return;
- const status = panelEl.querySelector('.grammar-panel__status');
- if (!status) return;
- status.textContent = message || '';
- status.className = `grammar-panel__status ${type}`;
- }
- function setPanelDisabled(disabled) {
- if (!panelEl) return;
- panelEl.querySelectorAll('button[data-mode]').forEach((btn) => {
- btn.disabled = disabled;
- });
- }
- function createPanel() {
- ensurePanelStyle();
- if (panelEl) return panelEl;
- const panel = document.createElement('div');
- panel.id = PANEL_ID;
- panel.className = 'grammar-panel';
- panel.innerHTML = `
- <div class="grammar-panel__header">
- <p class="grammar-panel__title">Grammar Glow</p>
- <button class="grammar-panel__close" title="关闭">X</button>
- </div>
- <button data-mode="selection">分析选中文本</button>
- <button data-mode="paragraph">分析当前段落</button>
- <button data-mode="article">分析整篇文章</button>
- <div class="grammar-panel__status"></div>
- `;
- panel.querySelector('.grammar-panel__close')?.addEventListener('click', () => {
- panel.remove();
- panelEl = null;
- });
- panel.querySelectorAll('button[data-mode]').forEach((btn) => {
- btn.addEventListener('click', async () => {
- const mode = btn.dataset.mode;
- setPanelStatus('处理中...', '');
- setPanelDisabled(true);
- try {
- await handleAnalyze(mode);
- setPanelStatus('已完成高亮。', 'success');
- } catch (error) {
- setPanelStatus(error.message || '未知错误', 'error');
- } finally {
- setPanelDisabled(false);
- }
- });
- });
- document.body.appendChild(panel);
- panelEl = panel;
- return panel;
- }
- function togglePanel() {
- if (panelEl) {
- panelEl.remove();
- panelEl = null;
- return;
- }
- createPanel();
- }
- chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
- if (message?.type === 'GRAMMAR_ANALYZE') {
- handleAnalyze(message.mode)
- .then(() => sendResponse({ success: true }))
- .catch((error) => {
- sendResponse({ error: error.message || '未知错误' });
- });
- return true;
- }
- if (message?.type === 'GRAMMAR_TOGGLE_PANEL') {
- togglePanel();
- }
- });
|