Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,46 @@
# Changelog


## v1.2.0-beta.16

[compare changes](https://github.com/NativeMindBrowser/NativeMindExtension/compare/v1.2.0-beta.15...v1.2.0-beta.16)

### 🚀 Enhancements

- **background:** Inject content script on installation ([a9b410d](https://github.com/NativeMindBrowser/NativeMindExtension/commit/a9b410d))

### ❤️ Contributors

- Tony Hu ([@tonyhu-012](http://github.com/tonyhu-012))

## v1.2.0-beta.15

[compare changes](https://github.com/NativeMindBrowser/NativeMindExtension/compare/v1.2.0-beta.14...v1.2.0-beta.15)

### 🚀 Enhancements

- **wxt:** Add module to expose web resources and update config ([93c5d03](https://github.com/NativeMindBrowser/NativeMindExtension/commit/93c5d03))

### 🩹 Fixes

- **styles:** Enhance style injection and loading mechanism for shadow DOM ([e947697](https://github.com/NativeMindBrowser/NativeMindExtension/commit/e947697))

### ❤️ Contributors

- Tony Hu ([@tonyhu-012](http://github.com/tonyhu-012))

## v1.2.0-beta.14

[compare changes](https://github.com/NativeMindBrowser/NativeMindExtension/compare/v1.2.0-beta.13...v1.2.0-beta.14)

### 🩹 Fixes

- **translator:** Ensure translation menu updates only when document is visible and improve context menu handling ([2f8ad72](https://github.com/NativeMindBrowser/NativeMindExtension/commit/2f8ad72))

### ❤️ Contributors

- Tony Hu ([@tonyhu-012](http://github.com/tonyhu-012))

## v1.2.0-beta.13

[compare changes](https://github.com/NativeMindBrowser/NativeMindExtension/compare/v1.2.0-beta.12...v1.2.0-beta.13)
Expand Down
4 changes: 2 additions & 2 deletions composables/useInjectStyle.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { onScopeDispose } from 'vue'

export function useInjectStyle(inlineCss: string) {
export function useInjectStyle(inlineCss: string, attachedElement?: HTMLElement) {
const styleElement = document.createElement('style')
styleElement.textContent = inlineCss
styleElement.setAttribute('data-nativemind-style', 'true')
styleElement.setAttribute('data-nativemind-style-injected', 'true')

// Append the style element to the head
document.head.appendChild(styleElement)
;(attachedElement ?? document.head).appendChild(styleElement)

onScopeDispose(() => {
styleElement.remove()
Expand Down
31 changes: 18 additions & 13 deletions entrypoints/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { INVALID_URLS } from '@/utils/constants'
import { CONTEXT_MENU, CONTEXT_MENU_ITEM_TRANSLATE_PAGE } from '@/utils/context-menu'
import logger from '@/utils/logger'
import { bgBroadcastRpc } from '@/utils/rpc'
import { registerBackgroundRpcEvent } from '@/utils/rpc/background-fns'
import { isTabValid } from '@/utils/tab'
import { registerDeclarativeNetRequestRule } from '@/utils/web-request'

Expand Down Expand Up @@ -37,8 +36,7 @@ export default defineBackground(() => {
})

const setPopupStatusBasedOnUrl = async (tabId: number, url: string) => {
const isValidUrl = /https?:\/\//.test(url ?? '')
if (!isValidUrl || unAttachedTabs.has(tabId) || INVALID_URLS.some((regex) => regex.test(url))) {
if (INVALID_URLS.some((regex) => regex.test(url))) {
await browser.action.setPopup({ popup: 'popup.html' })
}
else {
Expand Down Expand Up @@ -84,14 +82,8 @@ export default defineBackground(() => {
})
})

const unAttachedTabs = new Set<number>()

browser.runtime.onInstalled.addListener(async () => {
logger.debug('Extension Installed')
const tabs = await browser.tabs.query({ currentWindow: true })
for (const tab of tabs) {
tab.id && unAttachedTabs.add(tab.id)
}
await browser.contextMenus.removeAll()
for (const menu of CONTEXT_MENU) {
browser.contextMenus.create({
Expand All @@ -100,6 +92,23 @@ export default defineBackground(() => {
contexts: menu.contexts,
})
}
// inject content script into all tabs which are opened before the extension is installed
const tabs = await browser.tabs.query({})
for (const tab of tabs) {
if (tab.id && tab.url) {
const tabUrl = tab.url
if (INVALID_URLS.some((regex) => regex.test(tabUrl))) continue
await browser.scripting.executeScript({
files: ['/content-scripts/content.js'],
target: { tabId: tab.id },
world: 'ISOLATED',
}).then(() => {
logger.info('Content script injected', { tabId: tab.id })
}).catch((error) => {
logger.error('Failed to inject content script', { tabId: tab.id, error })
})
}
}
})

browser.contextMenus.onClicked.addListener(async (info, tab) => {
Expand All @@ -112,9 +121,5 @@ export default defineBackground(() => {
}
})

registerBackgroundRpcEvent('ready', (tabId) => {
unAttachedTabs.delete(tabId)
})

logger.info('Hello background!', { id: browser.runtime.id })
})
54 changes: 35 additions & 19 deletions entrypoints/content/composables/useTranslator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,35 +61,51 @@ async function _useTranslator() {
})

watch(enabled, async (newVal) => {
await setTranslationMenuTargetLanguage(newVal, targetLocale.value)
if (document.visibilityState === 'visible') {
await setTranslationMenuTargetLanguage(newVal, targetLocale.value)
}
})

watch(targetLocale, async (newVal) => {
await setTranslationMenuTargetLanguage(enabled.value, newVal)
if (document.visibilityState === 'visible') {
await setTranslationMenuTargetLanguage(enabled.value, newVal)
}
})

let isWaiting = false

registerContentScriptRpcEvent('contextMenuClicked', async (e) => {
if (!enabled.value && userConfig.llm.endpointType.get() === 'ollama') {
if (!(await ollamaStatusStore.updateConnectionStatus())) {
toast('Failed to connect to Ollama server, please check your Ollama connection', { duration: 2000 })
showSettings(true, 'server-address-section')
return
if (isWaiting) return
isWaiting = true
try {
if (!enabled.value && userConfig.llm.endpointType.get() === 'ollama') {
if (!(await ollamaStatusStore.updateConnectionStatus())) {
toast('Failed to connect to Ollama server, please check your Ollama connection', { duration: 2000 })
showSettings(true, 'server-address-section')
return
}
else if ((await ollamaStatusStore.updateModelList()).length === 0) {
toast('No model found, please download a model.', { duration: 2000 })
showSettings(true, 'model-download-section')
return
}
}
if (e.menuItemId === 'native-mind-page-translate') {
await onInit()
enabled.value = toggleTranslation(!enabled.value)
}
else if ((await ollamaStatusStore.updateModelList()).length === 0) {
toast('No model found, please download a model.', { duration: 2000 })
showSettings(true, 'model-download-section')
return
else if (e.menuItemId === 'native-mind-selection-translate') {
await onInit()
const selection = window.getSelection()
const commonAncestor = getCommonAncestorElement(selection)
commonAncestor && translation.translateElement(commonAncestor)
}
}
if (e.menuItemId === 'native-mind-page-translate') {
await onInit()
enabled.value = toggleTranslation(!enabled.value)
catch (error) {
logger.error('Error handling context menu click', error)
}
else if (e.menuItemId === 'native-mind-selection-translate') {
await onInit()
const selection = window.getSelection()
const commonAncestor = getCommonAncestorElement(selection)
commonAncestor && translation.translateElement(commonAncestor)
finally {
isWaiting = false
}
})

Expand Down
2 changes: 1 addition & 1 deletion entrypoints/content/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { createShadowRootOverlay } from './ui'

export default defineContentScript({
matches: ['*://*/*'],
cssInjectionMode: 'ui',
cssInjectionMode: 'manual',
runAt: 'document_start',
async main(ctx) {
const ui = await createShadowRootOverlay(ctx, ({ rootElement }) => {
Expand Down
21 changes: 18 additions & 3 deletions entrypoints/content/ui.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
import { createPinia } from 'pinia'
import type { Component } from 'vue'
import { createApp } from 'vue'
import { browser } from 'wxt/browser'
import { ContentScriptContext } from 'wxt/utils/content-script-context'
import { createShadowRootUi } from 'wxt/utils/content-script-ui/shadow-root'
import { splitShadowRootCss } from 'wxt/utils/split-shadow-root-css'

import { initToast } from '@/composables/useToast'
import { FONT_FACE_CSS } from '@/utils/constants'
import { convertPropertiesIntoSimpleVariables, createStyleSheetByCssText, loadContentScriptCss, replaceFontFaceUrl, scopeStyleIntoShadowRoot } from '@/utils/css'
import { i18n } from '@/utils/i18n'

async function loadStyleSheet(shadowRoot: ShadowRoot) {
const contentScriptCss = await loadContentScriptCss(import.meta.env.ENTRYPOINT)
const fontFaceCss = await loadContentScriptCss(FONT_FACE_CSS)
const { shadowCss, documentCss } = splitShadowRootCss(contentScriptCss)
shadowRoot.adoptedStyleSheets.push(scopeStyleIntoShadowRoot(shadowCss))
shadowRoot.adoptedStyleSheets.push(convertPropertiesIntoSimpleVariables(scopeStyleIntoShadowRoot(documentCss), true))
// font-face can only be applied to the document, not the shadow root
document.adoptedStyleSheets.push(replaceFontFaceUrl(createStyleSheetByCssText(fontFaceCss), (url) => browser.runtime.getURL(url as Parameters<typeof browser.runtime.getURL>[0])))
}

export async function createShadowRootOverlay(ctx: ContentScriptContext, component: Component<{ rootElement: HTMLDivElement }>) {
const ui = await createShadowRootUi(ctx, {
name: 'nativemind-container',
position: 'overlay',
isolateEvents: true,
mode: 'open',
anchor: 'html',
onMount(uiContainer, _shadow, shadowHost) {
async onMount(uiContainer, shadowRoot, shadowHost) {
await loadStyleSheet(shadowRoot)
const rootElement = document.createElement('div')
const toastRoot = document.createElement('div')
uiContainer.appendChild(rootElement)
Expand All @@ -31,8 +46,8 @@ export async function createShadowRootOverlay(ctx: ContentScriptContext, compone
app.mount(rootElement)
return app
},
onRemove(app) {
app?.unmount()
async onRemove(app) {
(await app)?.unmount()
},
})
return ui
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "nativemind-extension",
"version": "1.2.0-beta.13",
"version": "1.2.0-beta.16",
"private": false,
"author": "NativeMind",
"keywords": [
Expand Down Expand Up @@ -100,6 +100,7 @@
"eslint": "^9.26.0",
"eslint-plugin-simple-import-sort": "^12.1.1",
"fs-extra": "^11.3.0",
"glob": "^11.0.3",
"globals": "^16.1.0",
"husky": "^9.1.7",
"prettier-plugin-tailwindcss": "^0.6.11",
Expand Down
Loading