Showing preview only (2,875K chars total). Download the full file or copy to clipboard to get everything.
Repository: nextai-translator/nextai-translator
Branch: main
Commit: 602c64e6472b
Files: 253
Total size: 2.7 MB
Directory structure:
gitextract_rd5emhhi/
├── .eslintignore
├── .eslintrc.js
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug-report.yml
│ │ ├── config.yml
│ │ └── feature.yml
│ ├── dependabot.yml
│ └── workflows/
│ ├── lint.yaml
│ ├── playwright.yml
│ ├── release.yaml
│ ├── test-build.yaml
│ ├── unit-test.yaml
│ └── winget.yml
├── .gitignore
├── .prettierrc.js
├── AGENTS.md
├── CLIP-EXTENSIONS-CN.md
├── CLIP-EXTENSIONS.md
├── LICENSE
├── Makefile
├── README-CN.md
├── README.md
├── clip-extensions/
│ ├── popclip/
│ │ ├── Config.plist
│ │ └── nextai-translator.sh
│ └── snipdo/
│ ├── nextai-translator.json
│ └── nextai-translator.ps1
├── docs/
│ ├── chatglm-cn.md
│ ├── chatglm.md
│ ├── chatgpt-cn.md
│ ├── chatgpt.md
│ ├── kimi-cn.md
│ └── kimi.md
├── e2e/
│ ├── common.ts
│ ├── fixtures.ts
│ ├── hotkey.spec.ts
│ ├── index.spec.ts
│ ├── test.html
│ └── titlebar.spec.ts
├── package.json
├── playwright.config.ts
├── scripts/
│ └── release.py
├── src/
│ ├── browser-extension/
│ │ ├── background/
│ │ │ └── index.ts
│ │ ├── common.ts
│ │ ├── content_script/
│ │ │ ├── InnerContainer.tsx
│ │ │ ├── TitleBar.tsx
│ │ │ ├── consts.ts
│ │ │ ├── index.tsx
│ │ │ └── utils.ts
│ │ ├── enable-dev-hmr.ts
│ │ ├── manifest.ts
│ │ ├── options/
│ │ │ ├── index.css
│ │ │ ├── index.html
│ │ │ └── index.tsx
│ │ └── popup/
│ │ ├── index.css
│ │ ├── index.html
│ │ └── index.tsx
│ ├── common/
│ │ ├── __tests__/
│ │ │ └── translate.test.ts
│ │ ├── analysis.ts
│ │ ├── background/
│ │ │ ├── eventnames.ts
│ │ │ ├── fetch.ts
│ │ │ ├── local-storage.ts
│ │ │ └── services/
│ │ │ ├── action.ts
│ │ │ ├── base.ts
│ │ │ ├── history.ts
│ │ │ └── vocabulary.ts
│ │ ├── components/
│ │ │ ├── ActionForm.tsx
│ │ │ ├── ActionManager.tsx
│ │ │ ├── CodeBlock.tsx
│ │ │ ├── CopyButton.tsx
│ │ │ ├── DurationPicker.tsx
│ │ │ ├── ErrorFallback.tsx
│ │ │ ├── Form/
│ │ │ │ ├── form.ts
│ │ │ │ ├── index.module.css
│ │ │ │ ├── index.ts
│ │ │ │ ├── item.tsx
│ │ │ │ ├── typings.ts
│ │ │ │ └── validators.ts
│ │ │ ├── GlobalSuspense.tsx
│ │ │ ├── IconPicker.tsx
│ │ │ ├── IpLocationNotification.tsx
│ │ │ ├── LogoWithText.tsx
│ │ │ ├── Markdown.tsx
│ │ │ ├── NumberInput.tsx
│ │ │ ├── ProxyTester.tsx
│ │ │ ├── RenderingFormatSelector.tsx
│ │ │ ├── Settings.tsx
│ │ │ ├── SpeakerIcon.tsx
│ │ │ ├── SpeakerMotion.tsx
│ │ │ ├── SpinnerIcon.tsx
│ │ │ ├── Toaster.tsx
│ │ │ ├── Tooltip.tsx
│ │ │ ├── TranslationHistory.tsx
│ │ │ ├── Translator.tsx
│ │ │ ├── Vocabulary.tsx
│ │ │ └── icons/
│ │ │ ├── CerebrasIcon.tsx
│ │ │ ├── ChatGLMIcon.tsx
│ │ │ ├── ClaudeIcon.tsx
│ │ │ ├── CohereIcon.tsx
│ │ │ ├── DeepSeekIcon.tsx
│ │ │ ├── GroqIcon.tsx
│ │ │ ├── KimiIcon.tsx
│ │ │ ├── MoonshotIcon.tsx
│ │ │ └── OllamaIcon.tsx
│ │ ├── constants.ts
│ │ ├── engines/
│ │ │ ├── abstract-engine.ts
│ │ │ ├── abstract-openai.spec.ts
│ │ │ ├── abstract-openai.ts
│ │ │ ├── azure.ts
│ │ │ ├── cerebras.ts
│ │ │ ├── chatglm.ts
│ │ │ ├── chatgpt.ts
│ │ │ ├── claude.ts
│ │ │ ├── cohere.ts
│ │ │ ├── deepseek.ts
│ │ │ ├── gemini.ts
│ │ │ ├── groq.ts
│ │ │ ├── index.ts
│ │ │ ├── interfaces.ts
│ │ │ ├── kimi.ts
│ │ │ ├── minimax.ts
│ │ │ ├── moonshot.ts
│ │ │ ├── ollama.ts
│ │ │ └── openai.ts
│ │ ├── geo-data.ts
│ │ ├── geo.ts
│ │ ├── highlight-in-textarea/
│ │ │ ├── index.css
│ │ │ └── index.ts
│ │ ├── hooks/
│ │ │ ├── global.ts
│ │ │ ├── useCollectedWordTotal.ts
│ │ │ ├── useCurrentThemeType.ts
│ │ │ ├── useMemoWindow.ts
│ │ │ ├── usePinned.ts
│ │ │ ├── usePromotionNeverDisplay.ts
│ │ │ ├── usePromotionShowed.ts
│ │ │ ├── useSettings.ts
│ │ │ ├── useTheme.ts
│ │ │ ├── useThemeDetector.ts
│ │ │ └── useThemeType.ts
│ │ ├── i18n/
│ │ │ └── locales/
│ │ │ ├── en/
│ │ │ │ └── translation.json
│ │ │ ├── ja/
│ │ │ │ └── translation.json
│ │ │ ├── th/
│ │ │ │ └── translation.json
│ │ │ ├── tr/
│ │ │ │ └── translation.json
│ │ │ ├── zh-Hans/
│ │ │ │ └── translation.json
│ │ │ └── zh-Hant/
│ │ │ └── translation.json
│ │ ├── i18n.d.ts
│ │ ├── i18n.js
│ │ ├── internal-services/
│ │ │ ├── action.ts
│ │ │ ├── db.ts
│ │ │ ├── history.ts
│ │ │ └── vocabulary.ts
│ │ ├── lang/
│ │ │ ├── data.ts
│ │ │ └── index.ts
│ │ ├── openai-api-path.spec.ts
│ │ ├── openai-api-path.ts
│ │ ├── polyfills/
│ │ │ ├── electron.ts
│ │ │ ├── tauri.ts
│ │ │ └── userscript.ts
│ │ ├── services/
│ │ │ ├── action.ts
│ │ │ ├── history.ts
│ │ │ ├── promotion.ts
│ │ │ └── vocabulary.ts
│ │ ├── store/
│ │ │ └── setting.ts
│ │ ├── store.ts
│ │ ├── token.ts
│ │ ├── traditional-or-simplified.ts
│ │ ├── translate.ts
│ │ ├── tts/
│ │ │ ├── edge-tts.ts
│ │ │ ├── index.ts
│ │ │ └── types.ts
│ │ ├── types.ts
│ │ ├── universal-fetch.ts
│ │ ├── usehooks.ts
│ │ ├── user-event.ts
│ │ └── utils.ts
│ ├── index.d.ts
│ └── tauri/
│ ├── App.tsx
│ ├── bindings.ts
│ ├── components/
│ │ └── Window.tsx
│ ├── dummy.html
│ ├── index.html
│ ├── index.tsx
│ ├── legacy-tauri-ipc.ts
│ ├── utils.ts
│ └── windows/
│ ├── ActionManagerWindow.tsx
│ ├── HistoryWindow.tsx
│ ├── ScreenshotWindow.tsx
│ ├── SettingsWindow.tsx
│ ├── ThumbWindow.tsx
│ ├── TranslatorWindow.tsx
│ └── UpdaterWindow.tsx
├── src-safari/
│ ├── .gitignore
│ ├── NextAI Translator.xcodeproj/
│ │ ├── project.pbxproj
│ │ └── project.xcworkspace/
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata/
│ │ └── IDEWorkspaceChecks.plist
│ ├── Shared (App)/
│ │ ├── Assets.xcassets/
│ │ │ ├── AccentColor.colorset/
│ │ │ │ └── Contents.json
│ │ │ ├── AppIcon.appiconset/
│ │ │ │ └── Contents.json
│ │ │ ├── Contents.json
│ │ │ └── LargeIcon.imageset/
│ │ │ └── Contents.json
│ │ ├── Base.lproj/
│ │ │ └── Main.html
│ │ ├── Resources/
│ │ │ ├── Script.js
│ │ │ └── Style.css
│ │ └── ViewController.swift
│ ├── Shared (Extension)/
│ │ └── SafariWebExtensionHandler.swift
│ ├── iOS (App)/
│ │ ├── AppDelegate.swift
│ │ ├── Base.lproj/
│ │ │ ├── LaunchScreen.storyboard
│ │ │ └── Main.storyboard
│ │ ├── Info.plist
│ │ └── SceneDelegate.swift
│ ├── iOS (Extension)/
│ │ └── Info.plist
│ ├── macOS (App)/
│ │ ├── AppDelegate.swift
│ │ ├── Base.lproj/
│ │ │ └── Main.storyboard
│ │ ├── Info.plist
│ │ └── NextAI Translator.entitlements
│ └── macOS (Extension)/
│ ├── Info.plist
│ └── NextAI Translator.entitlements
├── src-tauri/
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── build.rs
│ ├── capabilities/
│ │ └── migrated.json
│ ├── gen/
│ │ └── schemas/
│ │ ├── acl-manifests.json
│ │ ├── capabilities.json
│ │ ├── desktop-schema.json
│ │ ├── linux-schema.json
│ │ ├── macOS-schema.json
│ │ ├── plugin-manifests.json
│ │ └── windows-schema.json
│ ├── icons/
│ │ └── icon.icns
│ ├── resources/
│ │ ├── backspace.applescript
│ │ ├── bin/
│ │ │ ├── ocr_apple
│ │ │ └── ocr_intel
│ │ ├── copy.applescript
│ │ ├── get-selected-text-by-ax.applescript
│ │ ├── left.applescript
│ │ ├── paste.applescript
│ │ ├── right.applescript
│ │ └── select-all.applescript
│ ├── src/
│ │ ├── config.rs
│ │ ├── fetch.rs
│ │ ├── insertion.rs
│ │ ├── lang.rs
│ │ ├── main.rs
│ │ ├── ocr.rs
│ │ ├── tray.rs
│ │ ├── utils.rs
│ │ ├── windows.rs
│ │ └── writing.rs
│ └── tauri.conf.json
├── tsconfig.json
├── typos.toml
├── vite.config.chromium.ts
├── vite.config.firefox.ts
├── vite.config.tauri.ts
├── vite.config.ts
└── vite.config.userscript.ts
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintignore
================================================
public
dist
src/tauri/bindings.ts
src-safari
================================================
FILE: .eslintrc.js
================================================
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: ['eslint:recommended', 'plugin:react/recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
overrides: [],
parser: '@typescript-eslint/parser',
parserOptions: {
project: true,
tsconfigRootDir: __dirname,
ecmaVersion: 'latest',
sourceType: 'module',
},
root: true,
plugins: ['react', 'react-hooks', '@typescript-eslint', 'prettier', 'baseui'],
rules: {
'react/react-in-jsx-scope': 'off',
'camelcase': 'error',
'eqeqeq': ['error', 'always'],
'no-duplicate-imports': 'error',
'baseui/deprecated-theme-api': 'warn',
'baseui/deprecated-component-api': 'warn',
'baseui/no-deep-imports': 'warn',
'prettier/prettier': 'error',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'error',
'spaced-comment': ['error', 'always', { markers: ['/'] }],
},
settings: {
'import/resolver': {
typescript: {},
},
'react': {
version: 'detect',
},
},
}
================================================
FILE: .github/ISSUE_TEMPLATE/bug-report.yml
================================================
name: Bug report
description: Problems with the software
title: '[Bug] {{请输入标题,不要留空,并把两个花括号去掉 - Please enter a title, do not leave it blank, and remove the two curly brackets}}'
labels: ['bug']
body:
- type: markdown
attributes:
value: |
**非常感谢您的反馈!Thank you very much for your feedback!**
有关讨论、建议或者咨询的内容请去往[讨论区](https://github.com/nextai-translator/nextai-translator/discussions)。
For suggestions or help, please consider using [Github Discussion](https://github.com/nextai-translator/nextai-translator/discussions) instead.
- type: checkboxes
attributes:
label: Please search before asking
description: |
辛苦提 Bug 前,检索一下 [问题](https://github.com/nextai-translator/nextai-translator/issues?q=) 列表是否已经存在类似问题。麻烦提供系统版本、录屏或者截图、复现步骤,有助于更好的解决问题。
非 Bug 相关,烦请移步 [讨论区](https://github.com/nextai-translator/nextai-translator/discussions) 找寻有关讨论。
Please search [issues](https://github.com/nextai-translator/nextai-translator/issues) to check if your issue has already been reported.
Not related to bugs, please go to the [discussion area](https://github.com/nextai-translator/nextai-translator/discussions) for relevant discussions.
options:
- label: >
I searched in the [issues](https://github.com/nextai-translator/nextai-translator/issues) and found nothing similar.
required: true
- type: checkboxes
attributes:
label: Please read README
description: |
辛苦提 Bug 前(尤其是桌面端应用划词不出现图标、权限弹窗、报告文件已损坏的部分),请仔细阅读一下 README 中的 [Troubleshooting](https://github.com/nextai-translator/nextai-translator/tree/main#troubleshooting) 是否已经给出相关解决方案
Before reporting bugs (especially for issues such as missing icons in the desktop application, permission pop-ups, and damaged report files), please carefully read the [Troubleshooting](https://github.com/nextai-translator/nextai-translator/tree/main#troubleshooting) section in README to see if relevant solutions have already been provided.
options:
- label: I have read the troubleshooting section in the README in detail.
required: true
- type: checkboxes
attributes:
label: Please check your network and OpenAI API quota
description: |
如果您遇到的报错是 Failed to fetch 或者 API quota exceed,则说明是网络问题或者 OpenAI API 使用量超过阈值,这些问题都与 NextAI Translator 无关,请自行解决
If you encounter error messages such as 'Failed to fetch' or 'API quota exceed', it means there is a network issue or the usage limit of OpenAI API has been exceeded. These issues are not related to NextAI Translator, please resolve them on your own.
options:
- label: I am sure it is not a network issue or an OpenAI API quota issue.
required: true
- type: input
attributes:
label: NextAI Translator version
description: >
请提供您正在使用的 NextAI Translator 的版本。Please provide the version of NextAI Translator you are using. For example, `v0.1.0`.
validations:
required: true
- type: input
attributes:
label: Model name
description: >
请提供您正在使用的模型,最好把 settings 页面截图放上来。Please provide the model you are currently using, it would be best to upload a screenshot of your settings page.
validations:
required: true
- type: input
attributes:
label: 系统/浏览器版本 System/Browser version
description: >
请提供您正在使用的系统/浏览器版本。Please provide the version of the System/Browser you are using. For example, `macOS 11.2.3` or `Chrome 89.0.4389.114`.
validations:
required: true
- type: textarea
attributes:
label: 复现步骤 Reproduce step
description: >
请提供完整且简明的复现步骤,以方便及时定位并解决问题。Please provide complete and concise reproduction steps to facilitate timely identification and resolution of the issue.
validations:
required: true
- type: textarea
attributes:
label: 你看到了什么错误?What errors do you see?
validations:
required: true
- type: textarea
attributes:
label: 你期望看到什么?What did you expect to see?
validations:
required: true
- type: textarea
attributes:
label: 还有其他的内容吗?Anything else?
- type: checkboxes
attributes:
label: 你是否愿意提交一份 PR 来修改这个错误?Are you willing to submit a PR?
description: >
我们期待开发人员和用户的帮助,以解决在 NextAI Translator 中发现的任何问题。 如果您愿意通过提交 PR 来解决此问题,请勾选。We eagerly anticipate developers' and users' support and collaboration in resolving any issues found in NextAI Translator. If you are willing to offer a solution by submitting a PR to fix this matter, kindly mark the checkbox provided.
options:
- label: 我愿意提供 PR! I'm willing to submit a PR!
- type: markdown
attributes:
value: '非常感谢您的反馈!Thank you very much for your feedback!'
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: Ask a question or get support
url: https://github.com/nextai-translator/nextai-translator/discussions/categories/q-a
about: Ask a question or request support for NextAI Translator
================================================
FILE: .github/ISSUE_TEMPLATE/feature.yml
================================================
name: Feature
description: Add new feature, improve code, and more
labels: [ "enhancement" ]
body:
- type: markdown
attributes:
value: |
**非常感谢您的功能建议!Thank you very much for your feature proposal!**
- type: checkboxes
attributes:
label: Search before asking
description: >
请在提交前搜索 [issues](https://github.com/nextai-translator/nextai-translator/issues),以查看您的问题是否已经被提交。
Please search [issues](https://github.com/nextai-translator/nextai-translator/issues) to check if your issue has already been reported.
options:
- label: >
在 [issues](https://github.com/nextai-translator/nextai-translator/issues) 中没有找到类似的内容。
I searched in the [issues](https://github.com/nextai-translator/nextai-translator/issues) and found nothing similar.
required: true
- type: input
attributes:
label: feature
description: >
一句话概括你的功能建议。Please provide a brief description of your feature proposal.
validations:
required: true
- type: textarea
attributes:
label: 描述 Motivation
description: >
解释一下这个功能将如何解决您的问题。
Explain how this feature will resolve your problem, including the way it addresses the issue that you are facing.
validations:
required: true
- type: textarea
attributes:
label: Solution
description: 描述建议的解决方案。Describe the proposed solution. (if you have any additional information, please add it here.)
- type: textarea
attributes:
label: 还有其他内容吗?Anything else?
- type: checkboxes
attributes:
label: 你是否愿意提交一份 PR?Are you willing to submit a PR?
description: >
我们期待开发人员和用户的帮助,以解决在 NextAI Translator 中发现的任何问题。 如果您愿意通过提交 PR 来解决此问题,请勾选。We eagerly anticipate developers' and users' support and collaboration in resolving any issues found in NextAI Translator. If you are willing to offer a solution by submitting a PR to fix this matter, kindly mark the checkbox provided.
options:
- label: 我愿意提供 PR! I'm willing to submit a PR!
- type: markdown
attributes:
value: "非常感谢您的功能建议!Thank you very much for your feature proposal!"
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
================================================
FILE: .github/workflows/lint.yaml
================================================
name: Lint
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
typos-check:
name: Spell Check with Typos
runs-on: ubuntu-latest
steps:
- name: Checkout Actions Repository
uses: actions/checkout@v4
- name: Check spelling with custom config file
uses: crate-ci/typos@v1.16.10
with:
config: ./typos.toml
clippy:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
with:
components: clippy
- run: mkdir -p ./dist/tauri
- uses: giraffate/clippy-action@v1
with:
reporter: 'github-pr-review'
github_token: ${{ secrets.GITHUB_TOKEN }}
clippy_flags: -- -Dwarning
workdir: ./src-tauri
rustfmt:
runs-on: ubuntu-latest
permissions:
pull-requests: write
checks: write
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- uses: LoliGothick/rustfmt-check@master
with:
token: ${{ secrets.GITHUB_TOKEN }}
flags: --all
working-directory: ./src-tauri
eslint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8.6.0
- uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: Install packages
run: pnpm install --no-frozen-lockfile
- name: Run type check
run: pnpm tsc
- name: Run eslint
run: pnpm lint
================================================
FILE: .github/workflows/playwright.yml
================================================
name: Playwright Tests
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
e2e-test:
timeout-minutes: 60
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8.6.0
- uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Install Playwright Browsers
run: pnpm exec playwright install chromium --with-deps
- name: Build Chromium extension
run: pnpm vite build -c vite.config.chromium.ts
- name: Run Playwright tests
run: pnpm test:e2e --reporter github
================================================
FILE: .github/workflows/release.yaml
================================================
name: Release
on:
push:
tags: [ v\d+\.\d+\.\d+ ]
jobs:
create-release:
permissions:
contents: write
runs-on: ubuntu-22.04
outputs:
release_id: ${{ steps.create-release.outputs.id }}
release_upload_url: ${{ steps.create-release.outputs.upload_url }}
release_body: "${{ steps.tag.outputs.message }}"
steps:
- uses: actions/checkout@v4
- name: Get version
id: get_version
uses: battila7/get-version-action@v2
- name: Get tag message
id: tag
run: |
git fetch --depth=1 origin +refs/tags/*:refs/tags/*
echo "message<<EOF" >> $GITHUB_OUTPUT
echo "$(git tag -l --format='%(contents)' ${{ steps.get_version.outputs.version }})" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Create Release
id: create-release
uses: ncipollo/release-action@v1
with:
draft: true
name: ${{ steps.get_version.outputs.version }}
tag: ${{ steps.get_version.outputs.version }}
body: "${{ steps.tag.outputs.message }}"
build-tauri-renderer:
needs: create-release
permissions:
contents: write
packages: write
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Get version
id: get_version
uses: battila7/get-version-action@v2
- uses: pnpm/action-setup@v2
with:
version: 8.6.0
- name: setup node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: Install Rust nightly
uses: dtolnay/rust-toolchain@nightly
with:
toolchain: nightly
override: true
- name: install frontend dependencies
run: pnpm install --no-frozen-lockfile # change this to npm or pnpm depending on which one you use
- name: Change Version
env:
VERSION: "${{ steps.get_version.outputs.version-without-v }}"
run: make change-version change-package-version
- uses: oNaiPs/secrets-to-env-action@v1
with:
secrets: ${{ toJSON(secrets) }}
- name: build tauri renderer
run: pnpm build-tauri-renderer
- uses: actions/upload-artifact@v4
with:
name: tauri-renderer
path: dist/tauri/
build-tauri:
needs: [create-release, build-tauri-renderer]
permissions:
contents: write
packages: write
strategy:
fail-fast: false
matrix:
config:
- os: ubuntu-latest
arch: x86_64
rust_target: x86_64-unknown-linux-gnu
- os: macos-latest
arch: x86_64
rust_target: x86_64-apple-darwin
- os: macos-latest
arch: aarch64
rust_target: aarch64-apple-darwin
- os: windows-latest
arch: x86_64
rust_target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.config.os }}
steps:
- uses: actions/checkout@v4
- name: Get version
id: get_version
uses: battila7/get-version-action@v2
- uses: pnpm/action-setup@v2
with:
version: 8.6.0
- name: Setup node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: Install Rust nightly
uses: dtolnay/rust-toolchain@nightly
with:
targets: ${{ matrix.config.rust_target }}
toolchain: nightly
override: true
- name: Install frontend dependencies
run: pnpm install --no-frozen-lockfile # change this to npm or pnpm depending on which one you use
- name: Install dependencies (ubuntu only)
if: matrix.config.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libx11-dev libxdo-dev libxcb-shape0-dev libxcb-xfixes0-dev
sudo apt-get install -y libunwind-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libgstreamer-plugins-bad1.0-dev gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav gstreamer1.0-tools gstreamer1.0-x gstreamer1.0-alsa gstreamer1.0-gl gstreamer1.0-gtk3 gstreamer1.0-qt5 gstreamer1.0-pulseaudio
- name: Install dependencies (mac only)
if: matrix.config.os == 'macos-latest'
run: |
rustup target add aarch64-apple-darwin
- name: Change Version
env:
VERSION: "${{ steps.get_version.outputs.version-without-v }}"
run: make change-version change-package-version
- uses: actions/download-artifact@v4
with:
name: tauri-renderer
path: dist/tauri
- name: Install Cargo Tauri for info
run: cargo install tauri-cli --version "=2.8.4" --locked
- name: Tauri info
run: cargo tauri info
- uses: oNaiPs/secrets-to-env-action@v1
with:
secrets: ${{ toJSON(secrets) }}
- name: Build Tauri App
uses: tauri-apps/tauri-action@v0
if: matrix.config.os != 'macos-latest' || matrix.config.arch != 'aarch64'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ needs.create-release.outputs.release_id }}
releaseBody: ${{ needs.create-release.outputs.release_body }}
tauriScript: cargo tauri
updaterJsonPreferNsis: true
- name: Build Tauri App (macOS aarch64)
uses: tauri-apps/tauri-action@v0
if: matrix.config.os == 'macos-latest' && matrix.config.arch == 'aarch64'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ needs.create-release.outputs.release_id }}
releaseBody: ${{ needs.create-release.outputs.release_body }}
args: --target aarch64-apple-darwin
tauriScript: cargo tauri
updaterJsonPreferNsis: true
build-clip-extension:
runs-on: ubuntu-22.04
permissions:
contents: write
packages: write
needs: create-release
steps:
- uses: actions/checkout@v4
- name: Get version
id: get_version
uses: battila7/get-version-action@v2
- name: Build PopClip extension
run: make build-popclip-extension
- name: Upload PopClip extension to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.release_upload_url }}
asset_path: dist/nextai-translator.popclipextz
asset_name: nextai-translator.popclipextz
asset_content_type: application/zip
- name: Build SnipDo extension
run: make build-snipdo-extension
- name: Upload SnipDo extension to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.release_upload_url }}
asset_path: dist/nextai-translator.pbar
asset_name: nextai-translator.pbar
asset_content_type: application/zip
build-browser-extension:
runs-on: ubuntu-22.04
permissions:
contents: write
packages: write
needs: create-release
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8.6.0
- name: setup node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: Install Rust nightly
uses: dtolnay/rust-toolchain@nightly
with:
toolchain: nightly
override: true
- name: Get version
id: get_version
uses: battila7/get-version-action@v2
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Build browser extension
run: make build-browser-extension
env:
VERSION: "${{ steps.get_version.outputs.version-without-v }}"
- name: Build userscript
run: make build-userscript
env:
VERSION: "${{ steps.get_version.outputs.version-without-v }}"
- name: Package plugin and create userscript
run: |
mkdir release
mv dist/browser-extension/*.zip release/
mv dist/nextai-translator.user.js release/nextai-translator-${{ steps.get_version.outputs.version-without-v }}.user.js
- name: Upload Chromium extensions to release
id: upload-chromium-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.release_upload_url }}
asset_path: release/chromium.zip
asset_name: nextai-translator-chromium-extension-${{ steps.get_version.outputs.version-without-v }}.zip
asset_content_type: application/zip
- name: Upload Firefox extensions to release
id: upload-firefox-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.release_upload_url }}
asset_path: release/firefox.zip
asset_name: nextai-translator-firefox-extension-${{ steps.get_version.outputs.version-without-v }}.xpi
asset_content_type: application/zip
- name: Upload userscript to release
id: upload-userscript-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.release_upload_url }}
asset_path: release/nextai-translator-${{ steps.get_version.outputs.version-without-v }}.user.js
asset_name: nextai-translator-${{ steps.get_version.outputs.version-without-v }}.user.js
asset_content_type: application/javascript
publish-release:
permissions:
contents: write
runs-on: ubuntu-22.04
needs: [create-release, build-tauri, build-clip-extension, build-browser-extension]
steps:
- name: publish release
id: publish-release
uses: actions/github-script@v6
env:
release_id: ${{ needs.create-release.outputs.release_id }}
with:
script: |
github.rest.repos.updateRelease({
owner: context.repo.owner,
repo: context.repo.repo,
release_id: process.env.release_id,
draft: false,
prerelease: false
})
================================================
FILE: .github/workflows/test-build.yaml
================================================
name: Test Build
on:
workflow_dispatch:
jobs:
build-tauri:
permissions:
contents: write
strategy:
fail-fast: false
matrix:
platform: [macos-latest, ubuntu-22.04, windows-latest]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8.6.0
- uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: install Rust nightly
uses: dtolnay/rust-toolchain@nightly
- name: install dependencies (ubuntu only)
if: matrix.platform == 'ubuntu-22.04'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf libx11-dev libxdo-dev libxcb-shape0-dev libxcb-xfixes0-dev
- name: install dependencies (mac only)
if: matrix.platform == 'macos-latest'
run: |
rustup target add aarch64-apple-darwin
- name: install frontend dependencies
run: pnpm install --no-frozen-lockfile # change this to npm or pnpm depending on which one you use
- name: Build Tauri App (MacOS Universal)
uses: tauri-apps/tauri-action@dev
if: matrix.platform == 'macos-latest'
id: tauri-action-mac
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: test-release
args: --target universal-apple-darwin
- name: Build Tauri App
uses: tauri-apps/tauri-action@dev
if: matrix.platform != 'macos-latest'
id: tauri-action
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: test-release
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: tauri-client-app-artifact
path: |
${{ fromJSON(steps.tauri-action-mac.outputs.artifactPaths)[0] }}
${{ fromJSON(steps.tauri-action.outputs.artifactPaths)[0] }}
build-browser-extension:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8.6.0
- uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
- name: Build
run: make build-browser-extension
# todo: upload browser extension artifacts
================================================
FILE: .github/workflows/unit-test.yaml
================================================
name: Unit Test
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
unit-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8.6.0
- uses: actions/setup-node@v3
with:
node-version: 18
cache: 'pnpm'
- name: Install packages
run: pnpm install --no-frozen-lockfile
- name: Run test
run: pnpm test
================================================
FILE: .github/workflows/winget.yml
================================================
name: Publish to WinGet
on:
release:
types: [released]
jobs:
publish:
# Action can only be run on windows
runs-on: windows-latest
steps:
- uses: vedantmgoyal2009/winget-releaser@v2
with:
identifier: yetone.OpenAITranslator
max-versions-to-keep: 5 # keep only latest 5 versions
installers-regex: '\.msi$' # Only .msi files
token: ${{ secrets.WINGET_TOKEN }}
================================================
FILE: .gitignore
================================================
npm-debug.log
node_modules/
dist/
tmp/
release/
yarn-error.log
npm-error.log
.DS_Store
*.json-e
*.js-e
.vscode
.idea
.eslintcache
.yarn
.yarnrc.yml
/test-results/
/playwright-report/
/playwright/.cache/
================================================
FILE: .prettierrc.js
================================================
module.exports = {
singleQuote: true,
jsxSingleQuote: true,
semi: false,
trailingComma: 'es5',
tabWidth: 4,
useTabs: false,
quoteProps: 'consistent',
bracketSpacing: true,
printWidth: 120,
}
================================================
FILE: AGENTS.md
================================================
# Repository Guidelines
## Project Structure & Module Organization
- `src/browser-extension/` hosts extension surfaces (popup, options, background) and manifest tooling.
- `src/tauri/` contains the React renderer for desktop windows, while `src/common/` keeps shared hooks, stores, and translator logic consumed by both targets.
- `src-tauri/` is the Rust/Tauri backend for native commands, updates, and packaging; platform assets live in `src-tauri/resources` and `src-tauri/icons`.
- Supporting content sits in `public/` (static assets), `scripts/` (build helpers), `docs/` (provider guides), and `e2e/` (Playwright specs). Build outputs land in `dist/` and long-lived bundles in `release/`.
## Build, Test, and Development Commands
Install dependencies with `pnpm install` (package manager is pinned in `package.json`).
- `pnpm dev-chromium` starts the extension in Vite with HMR; `pnpm dev-tauri` boots the desktop shell with Tauri devtools.
- `pnpm build-browser-extension`, `pnpm build-tauri`, and `pnpm build-userscript` produce distributable bundles; use `pnpm clean` to reset `dist/` before packaging.
- `pnpm test` runs Vitest suites and `pnpm test:e2e` executes Playwright specs in `e2e/`.
- `pnpm lint`, `pnpm lint:fix`, and `pnpm format` keep ESLint and Prettier satisfied across TS/JS/CSS/MD files.
## Coding Style & Naming Conventions
TypeScript + React 18 (with Styletron) is the primary stack. Keep 4-space indentation, single quotes, and trailing commas—Prettier enforces this, so format before pushing. Components stay in `PascalCase`, hooks/utilities in `camelCase`, and constants in `SCREAMING_SNAKE_CASE`. Reuse helpers from `src/common` instead of duplicating logic, and keep staged files lint-clean to satisfy the pre-commit hook.
## Testing Guidelines
Unit tests live next to the code (`__tests__/foo.test.ts` or `foo.spec.ts`) and run with Vitest. Mock remote APIs and keep snapshots deterministic, especially around translation results. Update Playwright specs in `e2e/*.spec.ts` when UI flows change, and verify `pnpm test` plus `pnpm test:e2e` before requesting review.
## Commit & Pull Request Guidelines
Follow the lightweight conventional pattern seen in history (`fix:`, `feat:`, `chore:`) with concise, imperative summaries and optional scope (e.g., `fix: handle streaming fallback`). Reference related issues in parentheses `(#1234)` when helpful. PRs should describe the change, attach screenshots or GIFs for UI work, list verification commands, and call out platform coverage across Chrome, Firefox, and Tauri targets. Request review after lint/tests pass and diffs are free of secrets.
## Security & Configuration Tips
Never commit API keys or user artifacts; rely on runtime configuration via the in-app settings or local `.env` files ignored by git. When adding providers, document required environment keys under `docs/` and guard sensitive defaults behind toggles in `src/common`.
================================================
FILE: CLIP-EXTENSIONS-CN.md
================================================
桌面端应用全局划词插件
----------------------
<p align="center">
<br> <a href="CLIP-EXTENSIONS.md">English</a> | 中文
</p>
划词翻译是本软件的杀手锏功能,对于浏览器插件来说,浏览器提供了简单的 API 来获得选中的文本,但是对于桌面端应用来说,各个操作系统都没有统一的 API 来获得选中的文本。
通常都是使用剪切板来获得选中的文本,但是这样会在一些应用中造成剪切板混乱等 bug,在 macOS 中还会因为没有选中文本就按下 cmd+c 快捷键导致发出警告声。幸运的是,各个操作系统中已经有很多成熟的划词软件,而且它们有完善的插件机制,所以 NextAI Translator 特地开发了针对这些划词软件的插件来让用户无痛地使用划词翻译。
# macOS
## PopClip
[PopClip](https://pilotmoon.com/popclip/) 是 macOS 上成熟的划词软件,它提供了完善的插件机制,我们提供了它的插件,安装步骤如下:
* 1. 下载并安装 [PopClip](https://pilotmoon.com/popclip/)
* 2. 下载 [nextai-translator.popclipextz](https://github.com/nextai-translator/nextai-translator/releases/latest/download/nextai-translator.popclipextz)
* 3. 双击下载完毕的 nextai-translator.popclipextz,点击弹出窗口中的 Install "NextAI Translator" 按钮即可安装完毕
<p align="center">
<img width="400" src="https://user-images.githubusercontent.com/1206493/240260692-8af6141a-3dba-4775-921d-505223addf9e.png" />
</p>
* 4. 在 PopClip 中开启 NextAI Translator
<p align="center">
<img width="400" src="https://user-images.githubusercontent.com/1206493/240258859-c4f2ec91-255f-414c-a4a4-aca25fceb0b5.png" />
</p>
* 5. 效果如下
<p align="center">
<img width="600" src="https://user-images.githubusercontent.com/1206493/240355949-8f41d98d-f097-4ce4-a533-af60e1757ca1.gif" />
</p>
# Windows
## SnipDo
* 1. 下载并安装 [SnipDo](https://apps.microsoft.com/store/detail/snipdo/9NPZ2TVKJVT7)
* 2. 下载 [nextai-translator.pbar](https://github.com/nextai-translator/nextai-translator/releases/latest/download/nextai-translator.pbar)
* 3. 双击下载完毕的 nextai-translator.pbar 即可安装
* 4. 在 SnipDo 的设置页面中启用 NextAI Translator
<p align="center">
<img width="200" src="https://github.com/nextai-translator/nextai-translator/assets/1206493/09d66943-06db-4ba7-b217-a434c33cc8aa" />
</p>
建议只保留 NextAI Translator:
<p align="center">
<img width="600" src="https://github.com/nextai-translator/nextai-translator/assets/1206493/76b619d9-e63d-4d67-a32c-a0d2d6923558" />
</p>
* 5. 效果如下
<p align="center">
<img width="600" src="https://user-images.githubusercontent.com/1206493/240358161-2788eb97-d00b-4808-aa86-a7fcfe3f71dd.gif" />
</p>
================================================
FILE: CLIP-EXTENSIONS.md
================================================
Desktop Application Global Clip Extensions
------------------------------------------
<p align="center">
<br> English | <a href="CLIP-EXTENSIONS-CN.md">中文</a>
</p>
Clip translation is the killer feature of this software. For browser plugins, the browser provides a simple API to get the selected text, but for desktop applications, there is no unified API for each operating system to get the selected text.
Usually the clipboard is used to get the selected text, but this can cause bugs such as clipboard clutter in some applications and a warning sound in macOS because the cmd+c shortcut is pressed without the text selected. Fortunately, there are many mature clip software for various operating systems and they have a good plug-in mechanism, so NextAI Translator has developed plug-ins for these clip software to allow users to use paddleboarding translation painlessly.
# macOS
## PopClip
[PopClip](https://pilotmoon.com/popclip/) is a well-established clip word software on macOS, it provides a perfect plug-in mechanism, we provide its plug-in, the installation steps are as follows:
* 1. Download and install [PopClip](https://pilotmoon.com/popclip/)
* 2. Download [nextai-translator.popclipextz](https://github.com/nextai-translator/nextai-translator/releases/latest/download/nextai-translator.popclipextz)
* 3. Double-click the downloaded nextai-translator.popclipextz and click the Install "NextAI Translator" button in the popup window to finish the installation
<p align="center">
<img width="400" src="https://user-images.githubusercontent.com/1206493/240260692-8af6141a-3dba-4775-921d-505223addf9e.png" />
</p>
* 4. Open NextAI Translator in PopClip
<p align="center">
<img width="400" src="https://user-images.githubusercontent.com/1206493/240258859-c4f2ec91-255f-414c-a4a4-aca25fceb0b5.png" />
</p>
* 5. The effect is as follows
<p align="center">
<img width="600" src="https://user-images.githubusercontent.com/1206493/240355949-8f41d98d-f097-4ce4-a533-af60e1757ca1.gif" />
</p>
## Windows
## SnipDo
* 1. Download and install [SnipDo](https://apps.microsoft.com/store/detail/snipdo/9NPZ2TVKJVT7)
* 2. Download [nextai-translator.pbar](https://github.com/nextai-translator/nextai-translator/releases/latest/download/nextai-translator.pbar)
* 3. Double-click the downloaded nextai-translator.pbar to install it
* 4. Enable NextAI Translator in SnipDo's settings page
<p align="center">
<img width="200" src="https://github.com/nextai-translator/nextai-translator/assets/1206493/09d66943-06db-4ba7-b217-a434c33cc8aa" />
</p>
Suggest to only keep NextAI Translator:
<p align="center">
<img width="600" src="https://github.com/nextai-translator/nextai-translator/assets/1206493/76b619d9-e63d-4d67-a32c-a0d2d6923558" />
</p>
* 5. The effect is as follows
<p align="center">
<img width="600" src="https://user-images.githubusercontent.com/1206493/240358161-2788eb97-d00b-4808-aa86-a7fcfe3f71dd.gif" />
</p>
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
================================================
FILE: Makefile
================================================
VERSION ?= 0.1.0
clean:
rm -rf dist
change-version:
sed -i -e "s/\"version\": \".*\"/\"version\": \"$(VERSION)\"/" src-tauri/tauri.conf.json
change-package-version:
sed -i -e "s/\"version\": \".*\"/\"version\": \"$(VERSION)\"/" package.json
build-browser-extension: change-package-version
pnpm vite build -c vite.config.chromium.ts
pnpm vite build -c vite.config.firefox.ts
cd dist/browser-extension/chromium && zip -r ../chromium.zip .
cd dist/browser-extension/firefox && zip -r ../firefox.zip .
build-userscript: change-package-version
pnpm vite build -c vite.config.userscript.ts
build-popclip-extension:
rm -f dist/nextai-translator.popclipextz
mkdir -p dist/nextai-translator.popclipext
cp -r clip-extensions/popclip/* dist/nextai-translator.popclipext
cd dist && zip -r nextai-translator.popclipextz nextai-translator.popclipext && rm -r nextai-translator.popclipext
build-snipdo-extension:
rm -f dist/nextai-translator.pbar
zip -j -r dist/nextai-translator.pbar clip-extensions/snipdo/*
================================================
FILE: README-CN.md
================================================
# 因为收到了 OpenAI 公司的品牌名称所有权的警告,所以此项目和此产品改名为 nextai translator,望您能够理解。
<p align="center">
<br> <a href="README.md">English</a> | 中文
</p>
<p align="center">
<em>The translator that does more than just translation</em>
</p>
<p align="center">
<a href="LICENSE" target="_blank">
<img alt="MIT License" src="https://img.shields.io/github/license/nextai-translator/nextai-translator.svg?style=flat-square" />
</a>
<!-- TypeScript Badge -->
<img alt="TypeScript" src="https://img.shields.io/badge/-TypeScript-blue?style=flat-square&logo=typescript&logoColor=white" />
<!-- Rust Badge -->
<img alt="Rust" src="https://img.shields.io/badge/-Rust-orange?style=flat-square&logo=rust&logoColor=white" />
<a href="https://chrome.google.com/webstore/detail/nextai-translator/ogjibjphoadhljaoicdnjnmgokohngcc" target="_blank">
<img alt="Chrome" src="https://img.shields.io/chrome-web-store/stars/ogjibjphoadhljaoicdnjnmgokohngcc?color=blue&label=Chrome&style=flat-square&logo=google-chrome&logoColor=white" />
</a>
<a href="https://addons.mozilla.org/en-US/firefox/addon/nextai-translator/" target="_blank">
<img alt="Firefox" src="https://img.shields.io/amo/stars/nextai-translator?color=orange&label=Firefox&style=flat-square&logo=firefox&logoColor=white" />
</a>
<a href="https://github.com/nextai-translator/nextai-translator/releases" target="_blank">
<img alt="macOS" src="https://img.shields.io/badge/-macOS-black?style=flat-square&logo=apple&logoColor=white" />
</a>
<a href="https://github.com/nextai-translator/nextai-translator/releases" target="_blank">
<img alt="Windows" src="https://img.shields.io/badge/-Windows-blue?style=flat-square&logo=windows&logoColor=white" />
</a>
<a href="https://github.com/nextai-translator/nextai-translator/releases" target="_blank">
<img alt="Linux" src="https://img.shields.io/badge/-Linux-yellow?style=flat-square&logo=linux&logoColor=white" />
</a>
</p>
# 为啥要造这个轮子?
我开发了一个 Bob 的插件 [bob-plugin-nextai-translator](https://github.com/yetone/bob-plugin-nextai-translator) 使用 ChatGPT API 在 macOS 上进行全局划词翻译。
但是由于很多用户并不是 macOS 用户,所以特此开发了一个浏览器插件方便非 macOS 用户使用 ChatGPT 进行划词翻译。
# 既是浏览器插件也是跨平台桌面端应用!
<p align="center">
<img width="560" src="https://user-images.githubusercontent.com/1206493/223899374-ff386436-63b8-4618-afdd-fed2e6b48d56.png" />
</p>
# 使用截图
<p align="center">
<img width="800" src="https://user-images.githubusercontent.com/1206493/223200182-6a1d2a02-3fe0-4723-bdae-99d8b7212a33.gif" />
</p>
# 特性
1. 支持三种翻译模式:翻译、润色、总结
2. 支持 55 种语言的相互翻译、润色和总结功能
3. 支持实时翻译、润色和总结,以最快的速度响应用户,让翻译、润色和总结的过程达到前所未有的流畅和顺滑
4. 支持自定义翻译文本
5. 支持一键复制
6. 支持 TTS
7. 有桌面端应用,全平台(Windows + macOS + Linux)支持!
8. 支持截图翻译
9. 支持生词本,同时支持基于生词本里的单词生成帮助记忆的内容
10. 支持 [OpenAI](https://openai.com/)、[Azure OpenAI Service](https://azure.microsoft.com/en-us/products/cognitive-services/openai-service)、[MiniMax](https://www.minimaxi.com/) 等多种 LLM 服务商
# 使用准备
- (必须)申请 [OpenAI API Key](https://platform.openai.com/account/api-keys) 或 [Azure OpenAI Service API Key](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?tabs=command-line&pivots=rest-api#retrieve-key-and-endpoint)
- (可选)如果无法访问 OpenAI,可以使用 OpenAI API Proxy
# 安装
## Windows
### 手动安装
1. 在 [Latest Release](https://github.com/nextai-translator/nextai-translator/releases/latest) 页面下载以 `.exe` 结尾的安装包
2. 下载完成后双击安装包进行安装
3. 如果提示不安全,可以点击 `更多信息` -> `仍要运行` 进行安装
4. 开始使用吧!
## MacOS
### 手动安装
1. 去 [Latest Release](https://github.com/nextai-translator/nextai-translator/releases/latest) 页面下载对应芯片以 `.dmg` 的安装包(Apple Silicon机器请使用aarch64版本,并注意执行下文`xattr`指令)
2. 下载完成后双击安装包进行安装,然后将 `NextAI Translator` 拖动到 `Applications` 文件夹。
3. 开始使用吧!
### 故障排除
- "NextAI Translator" can’t be opened because the developer cannot be verified.
<p align="center">
<img width="300" src="https://user-images.githubusercontent.com/1206493/223916804-45ce3f34-6a4a-4baf-a0c1-4ab5c54c521f.png" />
</p>
- 点击 `Cancel` 按钮,然后去 `设置` -> `隐私与安全性` 页面,点击 `仍要打开` 按钮,然后在弹出窗口里点击 `打开` 按钮即可,以后打开 `NextAI Translator` 就再也不会有任何弹窗告警了 🎉
<p align="center">
<img width="500" src="https://user-images.githubusercontent.com/1206493/223916970-9c99f15e-cf61-4770-b92d-4a78f980bb26.png" /> <img width="200" src="https://user-images.githubusercontent.com/1206493/223917449-ed1ac19f-c43d-4b13-9888-79ba46ceb862.png" />
</p>
- 如果在 `隐私与安全性` 中找不到以上选项,或启动时提示文件损坏(Apple Silicon版本)。打开 `Terminal.app`,并输入以下命令(中途可能需要输入密码),然后重启 `NextAI Translator` 即可:
```sh
sudo xattr -d com.apple.quarantine /Applications/NextAI\ Translator.app
```
- 如果您每次打开它都遇到权限提示,或者无法执行快捷键划词翻译,请前往 `设置` -> `隐私与安全性` -> `辅助功能` 中删除 NextAI Translator,然后重新添加 NextAI Translator:
<p align="center">
<img width="500" src="https://user-images.githubusercontent.com/1206493/224536148-eec559bf-4d99-48c1-bbd3-2cc105aff084.png" />
<img width="600" src="https://user-images.githubusercontent.com/1206493/224536277-4200f58e-8dc0-4c01-a27a-a30d7d8dc69e.gif" />
</p>
## 安装桌面端划词扩展
详情请见 [桌面端划词扩展](./CLIP-EXTENSIONS-CN.md)
<p align="center">
<img width="600" src="https://user-images.githubusercontent.com/1206493/240355949-8f41d98d-f097-4ce4-a533-af60e1757ca1.gif" />
</p>
## 浏览器插件
1. 访问你使用的浏览器的插件市场安装此插件:
<p align="center">
<a target="_blank" href="https://chrome.google.com/webstore/detail/nextai-translator/ogjibjphoadhljaoicdnjnmgokohngcc">
<img src="https://img.shields.io/chrome-web-store/v/ogjibjphoadhljaoicdnjnmgokohngcc?label=Chrome%20Web%20Store&style=for-the-badge&color=blue&logo=google-chrome&logoColor=white" />
</a>
<a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/nextai-translator/">
<img src="https://img.shields.io/amo/v/nextai-translator?label=Firefox%20Add-on&style=for-the-badge&color=orange&logo=firefox&logoColor=white" />
</a>
</p>
2. 点击浏览器插件列表里的 NextAI Translator 图标,把获取的 API KEY 填入此插件弹出的配置界面中
<p align="center">
<img width="600" src="https://user-images.githubusercontent.com/1206493/222958165-159719b4-28a5-44a4-b700-567786df7f03.png" />
</p>
3. 刷新浏览器页面,即可享受丝滑般的划词翻译体验 🎉
## 配置 Azure OpenAI Service
```ts
const API_URL = `https://${resourceName}.openai.azure.com`
const API_URL_PATH = `/openai/deployments/${deployName}/chat/completions?api-version=${apiVersion}`
```
- resourceName: 你的 Azure OpenAI Service 资源名称。
- deployName: 你的 Azure OpenAI Service 模型部署名称,更改部署名称以切换模型。
- api-version: 2023-05-15,或者更新的版本。(受支持的API version列表可以在[Azure官方文档](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#completions)查找)
# License
[LICENSE](./LICENSE)
# Star 历史
<p align="center">
<a target="_blank" href="https://star-history.com/#nextai-translator/nextai-translator&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=nextai-translator/nextai-translator&type=Date&theme=dark">
<img alt="NebulaGraph Data Intelligence Suite(ngdi)" src="https://api.star-history.com/svg?repos=nextai-translator/nextai-translator&type=Date">
</picture>
</a>
</p>
================================================
FILE: README.md
================================================
# Due to receiving a trademark ownership warning from OpenAI, this project and product has been renamed to nextai translator. We hope you understand.
<p align="center">
<br> English | <a href="README-CN.md">中文</a>
</p>
<p align="center">
<em>The translator that does more than just translation</em>
</p>
<p align="center">
<a href="LICENSE" target="_blank">
<img alt="MIT License" src="https://img.shields.io/github/license/nextai-translator/nextai-translator.svg?style=flat-square" />
</a>
<!-- TypeScript Badge -->
<img alt="TypeScript" src="https://img.shields.io/badge/-TypeScript-blue?style=flat-square&logo=typescript&logoColor=white" />
<!-- Rust Badge -->
<img alt="Rust" src="https://img.shields.io/badge/-Rust-orange?style=flat-square&logo=rust&logoColor=white" />
<a href="https://chrome.google.com/webstore/detail/nextai-translator/ogjibjphoadhljaoicdnjnmgokohngcc" target="_blank">
<img alt="Chrome" src="https://img.shields.io/chrome-web-store/stars/ogjibjphoadhljaoicdnjnmgokohngcc?color=blue&label=Chrome&style=flat-square&logo=google-chrome&logoColor=white" />
</a>
<a href="https://addons.mozilla.org/en-US/firefox/addon/nextai-translator/" target="_blank">
<img alt="Firefox" src="https://img.shields.io/amo/stars/nextai-translator?color=orange&label=Firefox&style=flat-square&logo=firefox&logoColor=white" />
</a>
<a href="https://github.com/nextai-translator/nextai-translator/releases" target="_blank">
<img alt="macOS" src="https://img.shields.io/badge/-macOS-black?style=flat-square&logo=apple&logoColor=white" />
</a>
<a href="https://github.com/nextai-translator/nextai-translator/releases" target="_blank">
<img alt="Windows" src="https://img.shields.io/badge/-Windows-blue?style=flat-square&logo=windows&logoColor=white" />
</a>
<a href="https://github.com/nextai-translator/nextai-translator/releases" target="_blank">
<img alt="Linux" src="https://img.shields.io/badge/-Linux-yellow?style=flat-square&logo=linux&logoColor=white" />
</a>
</p>
# Why Yet another Translator
I have developed a [Bob](https://bobtranslate.com/) [plugin](https://github.com/yetone/bob-plugin-nextai-translator) that utilizes ChatGPT API to provide global word translation on macOS. However, since not all users have access to macOS to benefit from the plugin, I have created this project!
# More than just a browser extension
What began as a Chrome extension has now evolved into a multi-platform desktop app that I am currently developing.
<p align="center">
<img width="560" src="https://user-images.githubusercontent.com/1206493/223899374-ff386436-63b8-4618-afdd-fed2e6b48d56.png" />
</p>
# More than just translation
What began as a translation tool has now evolved to include surprisingly effective word polishing and summarization capabilities, ~~accidentally~~.
# How to use
<p align="center">
<img width="800" src="https://user-images.githubusercontent.com/1206493/223200182-6a1d2a02-3fe0-4723-bdae-99d8b7212a33.gif" />
</p>
# Features
1. It offers three modes: translation, polishing and summarization.
2. Our tool allows for mutual translation, polishing and summarization across 55 different languages.
3. Streaming mode is supported!
4. It allows users to customize their translation text.
5. One-click copying
6. Text-to-Speech (TTS)
7. Available on all platforms (Windows, macOS, and Linux) for both browsers and Desktop
8. Support screenshot translation
9. Support for vocabulary books, as well as support for generating memory aids based on the words in the vocabulary books
10. Supports [OpenAI](https://openai.com/), [Azure OpenAI Service](https://azure.microsoft.com/en-us/products/cognitive-services/openai-service), [MiniMax](https://www.minimaxi.com/), and other LLM providers
# Preparation
- (required) Apply for an OpenAI API key [here](https://platform.openai.com/account/api-keys) or [Azure OpenAI Service API Key](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?tabs=command-line&pivots=rest-api#retrieve-key-and-endpoint)
- (optional) If you cannot access OpenAI, you can use the OpenAI API Proxy.
# Installation
## Windows
### Install Manually
1. Download the installation package ending in `.exe` from the [Latest Release](https://github.com/nextai-translator/nextai-translator/releases/latest) page.
2. Double click the downloaded file to install it.
3. If prompted as unsafe, you can click on `More Info` -> `Run Anyway` to proceed with the installation.
4. Ready to use!
## MacOS
### Install Manually
1. Go to the [Latest Release](https://github.com/nextai-translator/nextai-translator/releases/latest) page and download the corresponding chip's `.dmg` installation package. Note: Use aarch64 version for Apple Silicon machines and run `xattr` command below.
2. Double click the downloaded file to install it.
3. Ready to use!
### Troubleshooting
- "NextAI Translator" can’t be opened because the developer cannot be verified.
<p align="center">
<img width="300" src="https://user-images.githubusercontent.com/1206493/223916804-45ce3f34-6a4a-4baf-a0c1-4ab5c54c521f.png" />
</p>
- Click the `Cancel` button, then go to the `Settings` -> `Privacy and Security` page, click the `Still Open` button, and then click the `Open` button in the pop-up window. After that, there will be no more pop-up warnings when opening `NextAI Translator`. 🎉
<p align="center">
<img width="500" src="https://user-images.githubusercontent.com/1206493/223916970-9c99f15e-cf61-4770-b92d-4a78f980bb26.png" /> <img width="200" src="https://user-images.githubusercontent.com/1206493/223917449-ed1ac19f-c43d-4b13-9888-79ba46ceb862.png" />
</p>
- If you cannot find the above options in `Privacy & Security`, or get error prompts such as broken files with Apple Silicon machines. Open `Terminal.app` and enter the following command (you may need to enter a password halfway through), then restart `NextAI Translator`:
```sh
sudo xattr -d com.apple.quarantine /Applications/NextAI\ Translator.app
```
- If you encounter a permission prompt every time you open it, or if you cannot perform a shortcut translation, please go to `Settings` -> `Privacy & Security` -> `Supporting Features` to remove NextAI Translator, and then re-add NextAI Translator.
<p align="center">
<img width="500" src="https://user-images.githubusercontent.com/1206493/224536148-eec559bf-4d99-48c1-bbd3-2cc105aff084.png" />
<img width="600" src="https://user-images.githubusercontent.com/1206493/224536277-4200f58e-8dc0-4c01-a27a-a30d7d8dc69e.gif" />
</p>
## Installing Desktop Clip Extensions
For details, see [Desktop Clip Extension](./CLIP-EXTENSIONS.md)
<p align="center">
<img width="600" src="https://user-images.githubusercontent.com/1206493/240355949-8f41d98d-f097-4ce4-a533-af60e1757ca1.gif" />
</p>
## Browser Extension
1. Visit your Browser Extension Store to install this plugin:
<p align="center">
<a target="_blank" href="https://chrome.google.com/webstore/detail/nextai-translator/ogjibjphoadhljaoicdnjnmgokohngcc">
<img src="https://img.shields.io/chrome-web-store/v/ogjibjphoadhljaoicdnjnmgokohngcc?label=Chrome%20Web%20Store&style=for-the-badge&color=blue&logo=google-chrome&logoColor=white" />
</a>
<a target="_blank" href="https://addons.mozilla.org/en-US/firefox/addon/nextai-translator/">
<img src="https://img.shields.io/amo/v/nextai-translator?label=Firefox%20Add-on&style=for-the-badge&color=orange&logo=firefox&logoColor=white" />
</a>
</p>
2. Click on the NextAI Translator icon in the browser plugin list, and enter the obtained API KEY into the configuration interface that pops up from this plugin.
<p align="center">
<img width="600" src="https://user-images.githubusercontent.com/1206493/222958165-159719b4-28a5-44a4-b700-567786df7f03.png" />
</p>
3. Refresh the page in the browser to enjoy the smooth translation experience 🎉!
## Configure Azure OpenAI Service
```ts
const API_URL = `https://${resourceName}.openai.azure.com`
const API_URL_PATH = `/openai/deployments/${deployName}/chat/completions?api-version=${apiVersion}`
```
- resourceName: Your Azure OpenAI Service resource name.
- deployName: Your Azure OpenAI Service model deploy name, you can change your model here.
- api-version: 2023-05-15, or newer. (supported api-version can be found at [Azure's official doc](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#completions))
# License
[LICENSE](./LICENSE)
# Star History
<p align="center">
<a target="_blank" href="https://star-history.com/#nextai-translator/nextai-translator&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=nextai-translator/nextai-translator&type=Date&theme=dark">
<img alt="NebulaGraph Data Intelligence Suite(ngdi)" src="https://api.star-history.com/svg?repos=nextai-translator/nextai-translator&type=Date">
</picture>
</a>
</p>
================================================
FILE: clip-extensions/popclip/Config.plist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Actions</key>
<array>
<dict>
<key>Shell Script File</key>
<string>nextai-translator.sh</string>
<key>Image File</key>
<string>icon.png</string>
<key>Title</key>
<string>NextAI Translator</string>
</dict>
</array>
<key>Credits</key>
<array>
<dict>
<key>Link</key>
<string>https://github.com/nextai-translator/nextai-translator</string>
<key>Name</key>
<string>NextAI Translator</string>
</dict>
</array>
<key>Extension Description</key>
<string>Translate text with NextAI Translator.</string>
<key>Extension Identifier</key>
<string>xyz.yetone.apps.openai-translator.clip-extensions.popclip</string>
<key>Extension Image File</key>
<string>nextai-translator.png</string>
<key>Extension Name</key>
<string>NextAI Translator</string>
<key>Required OS Version</key>
<string>10.13</string>
</dict>
</plist>
================================================
FILE: clip-extensions/popclip/nextai-translator.sh
================================================
send_text() {
curl -d "$POPCLIP_TEXT" --unix-socket /tmp/openai-translator.sock http://nextai-translator
}
if ! send_text; then
open -g -a NextAI\ Translator
sleep 2
send_text
fi
================================================
FILE: clip-extensions/snipdo/nextai-translator.json
================================================
{
"name": "NextAI Translator",
"identifier": "xyz.yetone.apps.openai-translator.clip-extensions.snipdo",
"icon": "icon.png",
"actions": [
{
"title": "NextAI Translator",
"icon": "icon.png",
"powershellFile": "nextai-translator.ps1"
}
]
}
================================================
FILE: clip-extensions/snipdo/nextai-translator.ps1
================================================
param(
[string]$PLAIN_TEXT
)
$encode_text = [System.Text.Encoding]::UTF8.GetBytes($PLAIN_TEXT)
curl 127.0.0.1:62007 -Method POST -Body $encode_text -UseBasicParsing
================================================
FILE: docs/chatglm-cn.md
================================================
如何获取 智谱清言(ChatGLM)的 refresh_token 和 token
=================================================
1. 去 [智谱清言官网](https://chatglm.cn) 登录
2. 根据下面视频教程获取 `refresh_token` 和 `token` 填入设置框中,千万别填反了!!!!!!!!!!!!!!
https://github.com/nextai-translator/nextai-translator/assets/1206493/4ee6b295-6a15-4a75-b071-b70b669d5dec
<img width="732" alt="image" src="https://github.com/nextai-translator/nextai-translator/assets/1206493/3ca65ed0-dab8-4101-a2e0-4d346b885461">
================================================
FILE: docs/chatglm.md
================================================
How to obtain the `refresh_token` and `token` for ChatGLM
=========================================================
1. Go to the [ChatGLM official website](https://chatglm.cn) to log in.
2. Follow the video tutorial below to obtain the `refresh_token` and `token`, and fill them into the settings box. Make sure not to fill them in reverse!!!!!!!!!!!!
https://github.com/nextai-translator/nextai-translator/assets/1206493/4ee6b295-6a15-4a75-b071-b70b669d5dec
<img width="732" alt="image" src="https://github.com/nextai-translator/nextai-translator/assets/1206493/3ca65ed0-dab8-4101-a2e0-4d346b885461">
================================================
FILE: docs/chatgpt-cn.md
================================================
FAQ
===
# Q: 遇到了如下报错该怎么办?
<img width="704" alt="image" src="https://github.com/nextai-translator/nextai-translator/assets/1206493/be75f564-21ba-4531-8875-7cd5e8bc554b">
解决方案:
请登录到 [ChatGPT](https://chat.openai.com/) 新建一个对话,随便发送几个字符,等待其正常返回,然后回到 NextAI Translator 重试,例如:
https://github.com/nextai-translator/nextai-translator/assets/1206493/e0d04d55-d1c3-452c-8b70-55dc2167540e
================================================
FILE: docs/chatgpt.md
================================================
FAQ
===
# Q: What should be done when encountering the following error?
<img width="704" alt="image" src="https://github.com/nextai-translator/nextai-translator/assets/1206493/be75f564-21ba-4531-8875-7cd5e8bc554b">
Solution:
Please log in to [ChatGPT](https://chat.openai.com/) and start a new conversation. Send a few characters randomly, wait for it to respond normally, then return to NextAI Translator and try again, for example:
https://github.com/nextai-translator/nextai-translator/assets/1206493/e0d04d55-d1c3-452c-8b70-55dc2167540e
================================================
FILE: docs/kimi-cn.md
================================================
如何获取 Kimi 的 refresh_token 和 access_token
============================================
1. 去 [Kimi 官网](https://kimi.moonshot.cn) 登录
2. 根据下面视频教程获取 `refresh_token` 和 `access_token` 填入设置框中,千万别填反了!!!!!!!!!!!!!!
https://github.com/nextai-translator/nextai-translator/assets/1206493/bd5d13aa-9469-4075-bbae-f490cd6667cd

================================================
FILE: docs/kimi.md
================================================
How to Obtain Kimi refresh_token and access_token
=================================================
1. Go to the [Kimi official website](https://kimi.moonshot.cn) to log in.
2. Obtain the `refresh_token` and `access_token` from the video tutorial below and fill them into the settings box, make sure not to reverse them!!!!!!!!!!!!!!!!!!!!!!
https://github.com/nextai-translator/nextai-translator/assets/1206493/bd5d13aa-9469-4075-bbae-f490cd6667cd

================================================
FILE: e2e/common.ts
================================================
import { Page } from '@playwright/test'
export function getOptionsPageUrl(extensionId: string) {
return `chrome-extension://${extensionId}/src/browser-extension/options/index.html`
}
export function getPopupPageUrl(extensionId: string) {
return `chrome-extension://${extensionId}/src/browser-extension/popup/index.html`
}
export async function selectExampleText(page: Page) {
const textLocator = page.getByTestId('example-text')
const boundingBox = await textLocator.boundingBox()
if (boundingBox) {
// select text
await page.mouse.move(boundingBox.x, boundingBox.y)
await page.mouse.down()
await page.mouse.move(boundingBox.x + boundingBox.width, boundingBox.y + boundingBox.height)
await page.mouse.up()
}
}
================================================
FILE: e2e/fixtures.ts
================================================
import path from 'node:path'
import { type BrowserContext, test as base, chromium } from '@playwright/test'
export const extensionPath = path.join(__dirname, '../dist/browser-extension/chromium')
export const test = base.extend<{
context: BrowserContext
extensionId: string
}>({
context: async ({ headless }, use) => {
const context = await chromium.launchPersistentContext('', {
headless,
args: [
...(headless ? ['--headless=new'] : []),
`--disable-extensions-except=${extensionPath}`,
`--load-extension=${extensionPath}`,
],
})
await use(context)
await context.close()
},
extensionId: async ({ context }, use) => {
// for manifest v3:
let [background] = context.serviceWorkers()
if (!background) background = await context.waitForEvent('serviceworker')
const extensionId = background.url().split('/')[2]
await use(extensionId)
},
})
export const expect = test.expect
================================================
FILE: e2e/hotkey.spec.ts
================================================
import path from 'node:path'
import { getOptionsPageUrl, selectExampleText } from './common'
import { expect, test } from './fixtures'
import { containerID, popupCardID, popupCardInnerContainerId } from '../src/browser-extension/content_script/consts'
test('hotkey should work', async ({ page, extensionId }) => {
await test.step('set hotkey', async () => {
await page.goto(getOptionsPageUrl(extensionId))
const input = page.locator('input[name="apiKey"]')
await input.fill('fake-api-key')
await page.getByTestId('shortcuts').click()
await page.getByTestId('hotkey-recorder').click()
await page.keyboard.down('Alt')
await page.keyboard.down('x')
await page.keyboard.up('Alt')
await page.keyboard.up('x')
await page.getByText('Save', { exact: true }).click()
})
const popupCard = await test.step('show popup card using hotkey', async () => {
await page.goto(`file:${path.join(__dirname, 'test.html')}`)
await selectExampleText(page)
const container = page.locator(`#${containerID}`)
await container.waitFor({ state: 'attached' })
await page.keyboard.down('Alt')
await page.keyboard.press('x')
return container.locator(`#${popupCardID}`)
})
await expect(popupCard).toBeAttached()
await expect(page.locator(`#${popupCardInnerContainerId}`)).toBeVisible()
})
================================================
FILE: e2e/index.spec.ts
================================================
import path from 'node:path'
import { expect, test } from './fixtures'
import { getOptionsPageUrl, getPopupPageUrl, selectExampleText } from './common'
import {
containerID,
popupThumbID,
popupCardID,
popupCardInnerContainerId,
} from '../src/browser-extension/content_script/consts'
test('popup card should be visible', async ({ page }) => {
await page.goto(`file:${path.join(__dirname, 'test.html')}`)
await selectExampleText(page)
const container = page.locator(`#${containerID}`)
const thumb = container.locator(`#${popupThumbID}`)
await expect(thumb).toBeVisible()
await thumb.click()
const popupCard = container.locator(`#${popupCardID}`)
await expect(popupCard).toBeAttached()
await expect(page.locator(`#${popupCardInnerContainerId}`)).toBeVisible()
})
test('popup page should be opened', async ({ page, extensionId }) => {
await page.goto(getPopupPageUrl(extensionId))
await expect(page.getByTestId('popup-container')).toBeVisible()
})
test('options page should be opened', async ({ page, extensionId }) => {
await page.goto(getOptionsPageUrl(extensionId))
await expect(page.getByTestId('settings-container')).toBeVisible()
})
================================================
FILE: e2e/test.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>E2E Testing</title>
</head>
<body>
<span data-testid="example-text">example text</span>
</body>
</html>
================================================
FILE: e2e/titlebar.spec.ts
================================================
import path from 'node:path'
import { expect, test } from './fixtures'
import { selectExampleText } from './common'
import { containerID, popupCardInnerContainerId, popupThumbID } from '../src/browser-extension/content_script/consts'
test.describe('titlebar', () => {
test.beforeEach(async ({ page }) => {
await page.goto(`file:${path.join(__dirname, 'test.html')}`)
await selectExampleText(page)
const thumb = page.locator(`#${containerID} #${popupThumbID}`)
await thumb.click()
})
test('pin/unpin should work', async ({ page }) => {
const pinBtn = page.getByTestId('titlebar-pin-btn')
// pin
await pinBtn.click()
await page.mouse.click(0, 0)
await expect(page.locator(`#${popupCardInnerContainerId}`)).toBeVisible()
// unpin
await pinBtn.click()
await page.mouse.click(0, 0)
await expect(page.locator(`#${popupCardInnerContainerId}`)).not.toBeVisible()
})
test('close should work', async ({ page }) => {
const pinBtn = page.getByTestId('titlebar-close-btn')
await pinBtn.click()
await expect(page.locator(`#${popupCardInnerContainerId}`)).not.toBeVisible()
})
})
================================================
FILE: package.json
================================================
{
"name": "nextai-translator",
"version": "0.1.0",
"description": "nextai-translator",
"packageManager": "pnpm@9.1.3",
"main": "index.js",
"scripts": {
"prepare": "pnpm exec simple-git-hooks",
"build-tauri-renderer": "tsc && vite build -c vite.config.tauri.ts",
"dev-tauri-renderer": "vite -c vite.config.tauri.ts --force",
"build-tauri": "npm run build-tauri-renderer && tauri build",
"dev-tauri": "tauri dev",
"dev-chromium": "vite -c vite.config.chromium.ts",
"dev-firefox": "NODE_ENV=development vite build -c vite.config.firefox.ts --watch",
"build-browser-extension": "tsc && make build-browser-extension",
"build-userscript": "make build-userscript",
"clean": "make clean",
"test": "vitest test",
"test:e2e": "playwright test",
"lint": "eslint \"src/**/*.{ts,tsx}\" --cache",
"lint:fix": "eslint --fix \"src/**/*.{ts,tsx}\"",
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,css,md,json}\" --cache"
},
"simple-git-hooks": {
"pre-commit": "pnpm exec lint-staged"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint \"src/**/*.{ts,tsx}\" --cache",
"prettier --write \"src/**/*.{js,jsx,ts,tsx,css,md,json}\" --cache"
]
},
"author": "",
"license": "AGPL-3.0",
"repository": {
"type": "git",
"url": "https://github.com/nextai-translator/nextai-translator.git"
},
"dependencies": {
"@aptabase/tauri": "^0.4.1",
"@floating-ui/dom": "^1.5.1",
"@sentry/react": "^7.61.0",
"@tauri-apps/api": "^2.8.0",
"@tauri-apps/plugin-autostart": "^2.5.0",
"@tauri-apps/plugin-fs": "^2.4.2",
"@tauri-apps/plugin-global-shortcut": "^2.3.0",
"@tauri-apps/plugin-http": "^2.5.2",
"@tauri-apps/plugin-notification": "^2.3.1",
"@tauri-apps/plugin-process": "^2.3.0",
"@tauri-apps/plugin-shell": "^2.3.1",
"@tauri-apps/plugin-updater": "^2.9.0",
"@types/color": "^3.0.6",
"@types/qs": "^6.9.10",
"@types/react-copy-to-clipboard": "^5.0.4",
"@types/react-syntax-highlighter": "^15.5.7",
"@types/react-window": "^1.8.5",
"baseui-sd": "^12.2.4",
"best-effort-json-parser": "^1.0.1",
"clsx": "^1.2.1",
"color": "^4.2.3",
"common-tags": "^1.8.2",
"date-fns": "^2.29.3",
"dayjs": "^1.11.10",
"dexie": "^3.2.3",
"dexie-react-hooks": "^1.1.3",
"edge-tts-universal": "^1.3.2",
"electron-store": "^8.1.0",
"eventsource-parser": "^1.0.0",
"hotkeys-js": "^3.10.1",
"i18next": "^23.4.4",
"i18next-browser-languagedetector": "^7.1.0",
"i18next-http-backend": "^2.2.1",
"iso-639-1": "^3.0.1",
"jotai": "^2.8.0",
"js-sha3": "^0.9.3",
"js-tiktoken": "^1.0.10",
"jss": "^10.10.0",
"jss-preset-default": "^10.10.0",
"katex": "^0.16.8",
"lodash.debounce": "^4.0.8",
"lru-cache": "^10.0.1",
"prism-react-renderer": "^2.3.0",
"qs": "^6.11.2",
"rc-field-form": "^1.36.0",
"react": "^18.2.0",
"react-code-block": "^1.0.0",
"react-copy-to-clipboard": "^5.1.0",
"react-country-flag": "^3.1.0",
"react-dom": "^18.2.0",
"react-draggable": "^4.4.5",
"react-dropzone": "^14.2.3",
"react-error-boundary": "^4.0.10",
"react-ga4": "^2.1.0",
"react-hooks-global-state": "^2.1.0",
"react-hot-toast": "^2.4.1",
"react-hotkeys-hook": "^4.4.1",
"react-i18next": "^13.0.3",
"react-icons": "^5.0.1",
"react-jss": "^10.10.0",
"react-latex-next": "^2.2.0",
"react-markdown": "^8.0.7",
"react-syntax-highlighter": "npm:@fengkx/react-syntax-highlighter@15.6.1",
"react-use": "^17.4.2",
"react-window": "^1.8.9",
"styletron-engine-atomic": "^1.5.0",
"styletron-react": "^6.1.0",
"swr": "^2.2.0",
"tesseract.js": "^4.0.2",
"underscore": "^1.13.6",
"url-join-ts": "^1.0.5",
"use-deep-compare": "^1.1.0",
"use-resize-observer": "^9.1.0",
"uuid": "^9.0.0",
"web-streams-polyfill": "^3.2.1",
"zustand": "^4.4.0"
},
"devDependencies": {
"@playwright/test": "^1.34.3",
"@samrum/vite-plugin-web-extension": "^5.0.0",
"@tauri-apps/cli": "^2.8.4",
"@types/chrome": "0.0.242",
"@types/common-tags": "^1.8.3",
"@types/fs-extra": "^11.0.1",
"@types/lodash.debounce": "^4.0.7",
"@types/node": "^20.5.9",
"@types/react": "^18.2.18",
"@types/react-dom": "^18.2.7",
"@types/tampermonkey": "^4.0.10",
"@types/underscore": "^1.11.6",
"@types/uuid": "^9.0.2",
"@types/webextension-polyfill": "^0.10.1",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.6.0",
"@vitejs/plugin-react": "^4.0.4",
"archiver": "^5.3.1",
"base64-inline-loader": "^2.0.1",
"chokidar-cli": "^3.0.0",
"electron": "^23.1.3",
"electron-util": "0.17.x",
"esbuild": "^0.19.2",
"esbuild-plugin-copy": "^2.1.1",
"esbuild-plugin-inline-import": "^1.0.1",
"esbuild-server": "^0.3.0",
"eslint": "^8.46.0",
"eslint-config-prettier": "^8.9.0",
"eslint-import-resolver-typescript": "^3.5.5",
"eslint-plugin-baseui": "^13.0.0",
"eslint-plugin-import": "^2.28.0",
"eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-react": "^7.33.1",
"eslint-plugin-react-hooks": "^4.6.0",
"fs-extra": "^11.1.1",
"jsdom": "^22.1.0",
"lint-staged": "^15.2.2",
"prettier": "^3.0.0",
"rollup-plugin-visualizer": "^5.9.0",
"simple-git-hooks": "^2.11.1",
"typescript": "^5.1.6",
"vite": "^4.3.9",
"vite-plugin-dynamic-import": "^1.4.1",
"vite-plugin-monkey": "^3.5.0",
"vite-plugin-svgr": "^4.2.0",
"vite-tsconfig-paths": "^4.2.0",
"vitest": "^0.34.3",
"webextension-polyfill": "^0.10.0"
},
"build": {
"appId": "xyz.yetone.apps",
"productName": "NextAI Translator",
"extraMetadata": {
"name": "nextai-translator",
"main": "main.js"
},
"files": [
{
"from": ".",
"filter": [
"package.json"
]
},
{
"from": "dist/electron/main"
},
{
"from": "dist/electron/renderer"
}
],
"win": {
"icon": "src/electron/assets/images/icon.png",
"target": [
"zip"
]
},
"mac": {
"icon": "src/electron/assets/images/icon.png",
"target": [
"zip"
]
},
"linux": {
"icon": "src/electron/assets/images/icon.png",
"target": [
"zip"
]
},
"directories": {
"buildResources": "resources"
},
"publish": null
}
}
================================================
FILE: playwright.config.ts
================================================
/**
* @see {@link https://playwright.dev/docs/chrome-extensions Chrome extensions | Playwright}
*/
import { defineConfig } from '@playwright/test'
export default defineConfig({
testDir: './e2e',
retries: 2,
})
================================================
FILE: scripts/release.py
================================================
import os
import subprocess
def get_current_version_from_tag():
subprocess.check_output(['git', 'pull', 'origin', 'main', '-r'])
subprocess.check_output(['git', 'fetch', '--tags'])
"""Get the current version from the latest tag in the repository."""
# Get the latest tag in the repository.
tag = subprocess.check_output(['git', 'describe', '--tags', '--abbrev=0']).decode('utf-8').strip()
# Get the current version from the tag.
version = tag.lstrip('v')
# Return the current version.
return version
def generate_new_version():
if os.getenv('VERSION'):
return os.getenv('VERSION')
"""Generate the new version for the current release."""
# Get the current version.
previous_version = get_current_version_from_tag()
# Get the new version.
new_version = previous_version.split('.')
new_version[-1] = str(int(new_version[-1]) + 1)
new_version = '.'.join(new_version)
# Return the new version.
return new_version
def generate_release_note():
"""Generate the release note for the current version."""
# Get the current version.
previous_version = get_current_version_from_tag()
# Get the release note.
release_note = subprocess.check_output(['git', 'log', '--pretty="%s"', 'v' + previous_version + '..HEAD']).decode('utf-8').strip()
# Return the release note.
return release_note
def create_new_tag():
"""Create a new tag for the current release."""
# Get the current version.
new_version = generate_new_version()
release_note = generate_release_note()
release_notes = []
seen = set()
for line in release_note.split('\n'):
line = line.strip().strip('"')
if not line:
continue
t_, _, _ = line.partition(':')
if t_.lower() not in ('fix', 'feat', 'docs', 'refactor', 'optimize', 'enhance', 'openai'):
continue
if line in seen:
continue
release_notes.append(line)
seen.add(line)
if not release_notes:
release_notes.append(f'release: v{new_version}')
tag_message = '\n'.join(release_notes)
args = ['git', 'tag', '-a', 'v' + new_version, '-m', tag_message]
# Create a new tag for the current release.
subprocess.check_output(args)
# Push the new tag to the repository.
subprocess.check_output(['git', 'push', 'origin', 'v' + new_version])
def main():
print(create_new_tag())
if __name__ == '__main__':
main()
================================================
FILE: src/browser-extension/background/index.ts
================================================
/* eslint-disable no-case-declarations */
import browser from 'webextension-polyfill'
import { BackgroundEventNames } from '../../common/background/eventnames'
import { BackgroundFetchRequestMessage, BackgroundFetchResponseMessage } from '../../common/background/fetch'
import { vocabularyInternalService } from '../../common/internal-services/vocabulary'
import { actionInternalService } from '../../common/internal-services/action'
import { historyInternalService } from '../../common/internal-services/history'
import { optionsPageHeaderPromotionIDKey, optionsPageOpenaiAPIKeyPromotionIDKey } from '../common'
import { chatgptArkoseReqParams } from '@/common/constants'
import { keyChatgptArkoseReqForm, keyChatgptArkoseReqUrl } from '@/common/engines/chatgpt'
import { keyKimiAccessToken } from '@/common/engines/kimi'
import { keyChatGLMAccessToken } from '@/common/engines/chatglm'
browser.contextMenus?.create(
{
id: 'open-translator',
type: 'normal',
title: 'NextAI Translator',
contexts: ['page', 'selection'],
},
() => {
browser.runtime.lastError
}
)
browser.contextMenus?.onClicked.addListener(async function (info) {
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true })
tab.id &&
browser.tabs.sendMessage(tab.id, {
type: 'open-translator',
info,
})
})
async function fetchWithStream(
port: browser.Runtime.Port,
message: BackgroundFetchRequestMessage,
signal: AbortSignal
) {
if (!message.details) {
throw new Error('No fetch details')
}
const { url, options } = message.details
let response: Response | null = null
try {
response = await fetch(url, { ...options, signal })
} catch (error) {
if (error instanceof Error) {
const { message, name } = error
port.postMessage({
error: { message, name },
})
}
port.disconnect()
return
}
const responseSend: BackgroundFetchResponseMessage = {
ok: response.ok,
status: response.status,
statusText: response.statusText,
redirected: response.redirected,
type: response.type,
url: response.url,
}
const reader = response?.body?.getReader()
if (!reader) {
port.postMessage(responseSend)
return
}
try {
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
const str = new TextDecoder().decode(value)
port.postMessage({
...responseSend,
data: str,
})
}
} catch (error) {
if (error instanceof Error) {
const { message, name } = error
port.postMessage({
error: { message, name },
})
}
} finally {
port.disconnect()
reader.releaseLock()
}
}
browser.runtime.onConnect.addListener(async function (port) {
switch (port.name) {
case BackgroundEventNames.fetch:
const controller = new AbortController()
const { signal } = controller
port.onMessage.addListener(function (message: BackgroundFetchRequestMessage) {
switch (message.type) {
case 'abort':
controller.abort()
break
case 'open':
fetchWithStream(port, message, signal)
break
}
})
return
}
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function callMethod(request: any, service: any): Promise<any> {
const { method, args } = request
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = (service as any)[method](...args)
if (result instanceof Promise) {
const v = await result
return { result: v }
}
return { result }
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
browser.runtime.onMessage.addListener(async (request) => {
switch (request.type) {
case BackgroundEventNames.vocabularyService:
return await callMethod(request, vocabularyInternalService)
case BackgroundEventNames.actionService:
return await callMethod(request, actionInternalService)
case BackgroundEventNames.historyService:
return await callMethod(request, historyInternalService)
case BackgroundEventNames.getItem:
const resp = await browser.storage.local.get(request.key)
return {
value: resp[request.key],
}
case BackgroundEventNames.setItem:
return await browser.storage.local.set({
[request.key]: request.value,
})
case BackgroundEventNames.removeItem:
return await browser.storage.local.remove(request.key)
case 'openOptionsPage':
await browser.storage.local.set({
[optionsPageOpenaiAPIKeyPromotionIDKey]: request.openaiAPIKeyPromotionID,
})
await browser.storage.local.set({ [optionsPageHeaderPromotionIDKey]: request.headerPromotionID })
browser.runtime.openOptionsPage()
return
}
})
browser.commands.onCommand.addListener(async (command) => {
switch (command) {
case 'open-popup': {
await browser.windows.create({
type: 'popup',
url: '/src/browser-extension/popup/index.html',
})
}
}
})
try {
browser.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.url.includes('/public_key') && !details.url.includes(chatgptArkoseReqParams)) {
if (!details.requestBody) {
return
}
const formData = new URLSearchParams()
for (const k in details.requestBody.formData) {
formData.append(k, details.requestBody.formData[k])
}
browser.storage.local
.set({
[keyChatgptArkoseReqUrl]: details.url,
[keyChatgptArkoseReqForm]:
formData.toString() ||
new TextDecoder('utf-8').decode(new Uint8Array(details.requestBody.raw?.[0].bytes)),
})
.then(() => {
console.log('Arkose req url and form saved')
})
}
},
{
urls: ['https://*.openai.com/*'],
types: ['xmlhttprequest'],
},
['requestBody']
)
browser.webRequest.onBeforeSendHeaders.addListener(
(details) => {
if (details.url.includes('/api/user')) {
const headers = details.requestHeaders || []
const authorization = headers.find((h) => h.name === 'Authorization')?.value || ''
const accessToken = authorization.split(' ')[1]
browser.storage.local
.set({
[keyKimiAccessToken]: accessToken,
})
.then(() => {
console.log('Kimi access_token saved')
})
}
},
{
urls: ['https://*.moonshot.cn/*'],
types: ['xmlhttprequest'],
},
['requestHeaders']
)
browser.webRequest.onBeforeSendHeaders.addListener(
(details) => {
if (details.url.includes('/chatglm/user-api/user/info')) {
const headers = details.requestHeaders || []
const authorization = headers.find((h) => h.name === 'Authorization')?.value || ''
const accessToken = authorization.split(' ')[1]
browser.storage.local
.set({
[keyChatGLMAccessToken]: accessToken,
})
.then(() => {
console.log('Kimi access_token saved')
})
}
},
{
urls: ['https://*.chatglm.cn/*'],
types: ['xmlhttprequest'],
},
['requestHeaders']
)
} catch (error) {
console.error('Error adding webRequest listener', error)
}
================================================
FILE: src/browser-extension/common.ts
================================================
export const optionsPageOpenaiAPIKeyPromotionIDKey = 'optionsPage:openaiAPIKeyPromotionID'
export const optionsPageHeaderPromotionIDKey = 'optionsPage:openaiHeaderPromotionID'
================================================
FILE: src/browser-extension/content_script/InnerContainer.tsx
================================================
import { computePosition, shift, flip, offset, type ReferenceElement, size } from '@floating-ui/dom'
import { PropsWithChildren, useCallback, useEffect, useRef, useState } from 'react'
import Draggable, { DraggableData, DraggableEvent } from 'react-draggable'
import {
documentPadding,
dragRegionSelector,
popupCardInnerContainerId,
popupCardMaxWidth,
popupCardMinHeight,
popupCardMinHeightAfterTranslation,
popupCardMinWidth,
popupCardOffset,
zIndex,
} from './consts'
import { createUseStyles } from 'react-jss'
type Props = {
reference: ReferenceElement
} & PropsWithChildren
const useStyles = createUseStyles({
container: {
position: 'fixed',
zIndex,
borderRadius: '4px',
boxShadow: '0 0 8px rgba(0,0,0,.3)',
minWidth: `${popupCardMinWidth}px`,
maxWidth: `${popupCardMaxWidth}px`,
lineHeight: '1.6',
fontSize: '13px',
color: '#333',
font: '14px/1.6 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji',
minHeight: `${popupCardMinHeight}px`,
width: 'max-content',
},
})
export default function InnerContainer({ children, reference }: Props) {
const styles = useStyles()
const draggedRef = useRef(false)
const draggableRef = useRef<HTMLDivElement | null>(null)
const [position, setPosition] = useState({ x: 0, y: 0 })
const updatePosition = useCallback(async () => {
if (!draggableRef.current) {
return
}
const { x, y } = await computePosition(reference, draggableRef.current, {
placement: 'bottom',
middleware: [
shift({ padding: documentPadding }),
offset(popupCardOffset),
flip(),
size({
apply({ availableHeight, elements }) {
Object.assign(elements.floating.style, {
maxHeight: `${Math.max(popupCardMinHeightAfterTranslation, availableHeight)}px`,
overflow: 'hidden',
})
},
}),
],
strategy: 'fixed',
})
Object.assign(draggableRef.current.style, {
left: `${Math.max(documentPadding, x)}px`,
top: `${Math.max(documentPadding, y)}px`,
})
}, [reference])
function handleOnDrag(event: DraggableEvent, data: DraggableData) {
draggedRef.current = true
setPosition({ x: data.x, y: data.y })
}
useEffect(() => {
if (!draggableRef.current) {
return
}
const resizeObserver = new ResizeObserver(() => {
if (draggedRef.current) {
// do nothing if has been dragged
} else {
updatePosition()
}
})
resizeObserver.observe(draggableRef.current)
return () => {
resizeObserver.disconnect()
}
}, [reference, updatePosition])
return (
<Draggable
nodeRef={draggableRef}
handle={dragRegionSelector}
bounds='html'
position={position}
onDrag={handleOnDrag}
>
<div ref={draggableRef} className={styles.container} id={popupCardInnerContainerId}>
{children}
</div>
</Draggable>
)
}
================================================
FILE: src/browser-extension/content_script/TitleBar.tsx
================================================
import { useState } from 'react'
import { createUseStyles } from 'react-jss'
import { useTranslation } from 'react-i18next'
import { BaseProvider } from 'baseui-sd'
import { Provider as StyletronProvider } from 'styletron-react'
import { Client as Styletron } from 'styletron-engine-atomic'
import { IThemedStyleProps } from '../../common/types'
import { useTheme } from '../../common/hooks/useTheme'
import { RxCross2, RxDrawingPin, RxDrawingPinFilled } from 'react-icons/rx'
import LogoWithText from '../../common/components/LogoWithText'
import { setSettings } from '../../common/utils'
import { Tooltip } from '../../common/components/Tooltip'
const useStyles = createUseStyles({
container: ({ theme }: IThemedStyleProps) => ({
display: 'flex',
background: theme.colors.backgroundPrimary,
padding: '8px 16px 4px 16px',
cursor: 'move',
justifyContent: 'space-between',
}),
actionsContainer: {
display: 'flex',
gap: '8px',
},
actionIconContainer: {
display: 'flex',
alignItems: 'center',
padding: '2px',
cursor: 'pointer',
},
pinIcon: {
rotate: '-45deg',
},
})
type TitleBarProps = {
pinned?: boolean
engine: Styletron
onClose: () => void
}
export default function TitleBar({ pinned = false, onClose, engine }: TitleBarProps) {
const { theme, themeType } = useTheme()
const { t } = useTranslation()
const styles = useStyles({ theme, themeType })
const [isPinned, setIsPinned] = useState(pinned)
async function handleTogglePin() {
setIsPinned((prevIsPinned) => {
setSettings({ pinned: !prevIsPinned })
return !prevIsPinned
})
}
return (
<StyletronProvider value={engine}>
<BaseProvider theme={theme}>
<div data-tauri-drag-region className={styles.container}>
<LogoWithText />
<div className={styles.actionsContainer}>
<Tooltip content={isPinned ? t('Unpin') : t('Pin')} placement='bottom' onMouseEnterDelay={1000}>
<div
className={styles.actionIconContainer}
onClick={handleTogglePin}
data-testid='titlebar-pin-btn'
>
{isPinned ? (
<RxDrawingPinFilled size={13} className={styles.pinIcon} />
) : (
<RxDrawingPin size={13} className={styles.pinIcon} />
)}
</div>
</Tooltip>
<Tooltip content={t('Close')} placement='bottom' onMouseEnterDelay={1000}>
<div
className={styles.actionIconContainer}
onClick={onClose}
data-testid='titlebar-close-btn'
>
<RxCross2 size={16} />
</div>
</Tooltip>
</div>
</div>
</BaseProvider>
</StyletronProvider>
)
}
================================================
FILE: src/browser-extension/content_script/consts.ts
================================================
export const zIndex = '2147483647'
export const popupThumbID = '__yetone-nextai-translator-popup-thumb'
export const popupCardID = '__yetone-nextai-translator-popup-card'
export const containerID = '__yetone-nextai-translator'
export const popupCardMinWidth = 220
export const popupCardMinHeight = 220
export const popupCardMinHeightAfterTranslation = 500
export const popupCardMaxWidth = 660
export const documentPadding = 10
export const popupCardOffset = 7
export const dragRegionSelector = '[data-tauri-drag-region]'
export const popupCardInnerContainerId = '__yetone-nextai-translator-popup-card-inner-container'
================================================
FILE: src/browser-extension/content_script/index.tsx
================================================
import '../enable-dev-hmr'
import * as utils from '@/common/utils'
import React from 'react'
import icon from '@/common/assets/images/icon.png'
import { popupCardID, popupCardOffset, popupThumbID, zIndex } from './consts'
import { Translator } from '@/common/components/Translator'
import { getContainer, queryPopupCardElement, queryPopupThumbElement } from './utils'
import { create } from 'jss'
import preset from 'jss-preset-default'
import { JssProvider, createGenerateId } from 'react-jss'
import { Client as Styletron } from 'styletron-engine-atomic'
import { createRoot, Root } from 'react-dom/client'
import hotkeys from 'hotkeys-js'
import '@/common/i18n.js'
import { PREFIX } from '@/common/constants'
import { getCaretNodeType, getClientX, getClientY, getPageX, getPageY, UserEventType } from '@/common/user-event'
import { GlobalSuspense } from '@/common/components/GlobalSuspense'
import { type ReferenceElement } from '@floating-ui/dom'
import InnerContainer from './InnerContainer'
import TitleBar from './TitleBar'
import { setExternalOriginalText } from '@/common/store'
let root: Root | null = null
const generateId = createGenerateId()
const hidePopupThumbTimer: number | null = null
async function popupThumbClickHandler(event: UserEventType) {
event.stopPropagation()
event.preventDefault()
const $popupThumb: HTMLDivElement | null = await queryPopupThumbElement()
if (!$popupThumb) {
return
}
showPopupCard($popupThumb, $popupThumb.dataset['text'] || '')
}
async function removeContainer() {
const $container = await getContainer()
$container.remove()
}
async function hidePopupThumb() {
const $popupThumb: HTMLDivElement | null = await queryPopupThumbElement()
if (!$popupThumb) {
return
}
$popupThumb.style.visibility = 'hidden'
}
async function hidePopupCard() {
const $popupCard: HTMLDivElement | null = await queryPopupCardElement()
if (!$popupCard) {
return
}
speechSynthesis.cancel()
if (root) {
root.unmount()
root = null
}
removeContainer()
}
async function createPopupCard() {
const $popupCard = document.createElement('div')
$popupCard.id = popupCardID
const $container = await getContainer()
$container.shadowRoot?.querySelector('div')?.appendChild($popupCard)
if ($container.shadowRoot) {
const shadowRoot = $container.shadowRoot
if (import.meta.hot) {
const { addViteStyleTarget } = await import('@samrum/vite-plugin-web-extension/client')
await addViteStyleTarget(shadowRoot)
} else {
const browser = await utils.getBrowser()
import.meta.PLUGIN_WEB_EXT_CHUNK_CSS_PATHS?.forEach((cssPath) => {
const styleEl = document.createElement('link')
styleEl.setAttribute('rel', 'stylesheet')
styleEl.setAttribute('href', browser.runtime.getURL(cssPath))
shadowRoot.appendChild(styleEl)
})
}
}
return $popupCard
}
async function showPopupCard(reference: ReferenceElement, text: string, autoFocus: boolean | undefined = false) {
const $popupThumb: HTMLDivElement | null = await queryPopupThumbElement()
if ($popupThumb) {
$popupThumb.style.visibility = 'hidden'
}
const settings = await utils.getSettings()
let $popupCard = await queryPopupCardElement()
if ($popupCard && settings.pinned) {
setExternalOriginalText(text)
return
} else {
$popupCard = await createPopupCard()
}
const engine = new Styletron({
container: $popupCard.parentElement ?? undefined,
prefix: `${PREFIX}-styletron-`,
})
const jss = create().setup({
...preset(),
insertionPoint: $popupCard.parentElement ?? undefined,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(window as any).__IS_OT_BROWSER_EXTENSION_CONTENT_SCRIPT__ = true
const isUserscript = utils.isUserscript()
const JSS = JssProvider
root = createRoot($popupCard)
root.render(
<React.StrictMode>
<GlobalSuspense>
<JSS jss={jss} generateId={generateId} classNamePrefix='__yetone-nextai-translator-jss-'>
<InnerContainer reference={reference}>
<TitleBar pinned={settings.pinned} onClose={hidePopupCard} engine={engine} />
<Translator
engine={engine}
autoFocus={autoFocus}
showSettingsIcon
defaultShowSettings={isUserscript}
showLogo={false}
/>
</InnerContainer>
</JSS>
</GlobalSuspense>
</React.StrictMode>
)
setExternalOriginalText(text)
}
async function showPopupThumb(text: string, x: number, y: number) {
if (!text) {
return
}
if (hidePopupThumbTimer) {
clearTimeout(hidePopupThumbTimer)
}
const isDark = await utils.isDarkMode()
let $popupThumb: HTMLDivElement | null = await queryPopupThumbElement()
if (!$popupThumb) {
$popupThumb = document.createElement('div')
$popupThumb.id = popupThumbID
$popupThumb.style.position = 'absolute'
$popupThumb.style.zIndex = zIndex
$popupThumb.style.background = isDark ? '#1f1f1f' : '#fff'
$popupThumb.style.padding = '2px'
$popupThumb.style.borderRadius = '4px'
$popupThumb.style.boxShadow = '0 0 4px rgba(0,0,0,.2)'
$popupThumb.style.cursor = 'pointer'
$popupThumb.style.userSelect = 'none'
$popupThumb.style.width = '20px'
$popupThumb.style.height = '20px'
$popupThumb.style.overflow = 'hidden'
$popupThumb.addEventListener('click', popupThumbClickHandler)
$popupThumb.addEventListener('touchend', popupThumbClickHandler)
$popupThumb.addEventListener('mousemove', (event) => {
event.stopPropagation()
})
$popupThumb.addEventListener('touchmove', (event) => {
event.stopPropagation()
})
const $img = document.createElement('img')
$img.src = utils.getAssetUrl(icon)
$img.style.display = 'block'
$img.style.width = '100%'
$img.style.height = '100%'
$popupThumb.appendChild($img)
const $container = await getContainer()
$container.shadowRoot?.querySelector('div')?.appendChild($popupThumb)
}
$popupThumb.dataset['text'] = text
$popupThumb.style.visibility = 'visible'
$popupThumb.style.opacity = '100'
$popupThumb.style.left = `${x}px`
$popupThumb.style.top = `${y}px`
}
async function main() {
const browser = await utils.getBrowser()
let mousedownTarget: EventTarget | null
let lastMouseEvent: UserEventType | undefined
const mouseUpHandler = async (event: UserEventType) => {
lastMouseEvent = event
const settings = await utils.getSettings()
if (
(mousedownTarget instanceof HTMLInputElement || mousedownTarget instanceof HTMLTextAreaElement) &&
settings.selectInputElementsText === false
) {
return
}
window.setTimeout(async () => {
const sel = window.getSelection()
let text = (sel?.toString() ?? '').trim()
if (!text) {
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
const elem = event.target
text = elem.value.substring(elem.selectionStart ?? 0, elem.selectionEnd ?? 0).trim()
}
} else {
if (settings.autoTranslate === true) {
const x = getClientX(event)
const y = getClientY(event)
showPopupCard(
{ getBoundingClientRect: () => new DOMRect(x, y, popupCardOffset, popupCardOffset) },
text
)
} else if (settings.alwaysShowIcons === true && getCaretNodeType(event) === Node.TEXT_NODE) {
showPopupThumb(text, getPageX(event) + popupCardOffset, getPageY(event) + popupCardOffset)
}
}
})
}
document.addEventListener('mouseup', mouseUpHandler)
document.addEventListener('touchend', mouseUpHandler)
browser.runtime.onMessage.addListener(function (request) {
if (request.type === 'open-translator') {
if (window !== window.top) return
const text = request.info.selectionText ?? ''
const x = lastMouseEvent ? getClientX(lastMouseEvent) : 0
const y = lastMouseEvent ? getClientY(lastMouseEvent) : 0
showPopupCard({ getBoundingClientRect: () => new DOMRect(x, y, popupCardOffset, popupCardOffset) }, text)
}
})
const mouseDownHandler = async (event: UserEventType) => {
mousedownTarget = event.target
const settings = await utils.getSettings()
hidePopupThumb()
if (!settings.pinned) {
hidePopupCard()
}
}
document.addEventListener('mousedown', mouseDownHandler)
document.addEventListener('touchstart', mouseDownHandler)
const settings = await utils.getSettings()
await bindHotKey(settings.hotkey)
}
export async function bindHotKey(hotkey_: string | undefined) {
const hotkey = hotkey_?.trim().replace(/-/g, '+')
if (!hotkey) {
return
}
hotkeys(hotkey, (event) => {
event.preventDefault()
const sel = window.getSelection()
let text = (sel?.toString() ?? '').trim()
if (!text) {
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
const elem = event.target
text = elem.value.substring(elem.selectionStart ?? 0, elem.selectionEnd ?? 0)
}
}
const selRange = sel?.getRangeAt(0)
selRange && showPopupCard({ getBoundingClientRect: () => selRange.getBoundingClientRect() }, text)
})
}
if (utils.isFirefox()) {
// workaround for `"then" is read-only` error caused by dexie in firefox
const nativeP = crypto.subtle.digest('SHA-512', new Uint8Array([0]))
Object.defineProperty(Object.getPrototypeOf(nativeP), 'then', {
get: () => Promise.prototype.then,
set: () => {
// do nothing
},
})
}
main()
================================================
FILE: src/browser-extension/content_script/utils.ts
================================================
import { containerID, documentPadding, popupCardID, popupThumbID, zIndex } from './consts'
function attachEventsToContainer($container: HTMLElement) {
$container.addEventListener('mousedown', (event) => {
event.stopPropagation()
})
$container.addEventListener('mouseup', (event) => {
event.stopPropagation()
})
$container.addEventListener('touchstart', (event) => {
event.stopPropagation()
})
$container.addEventListener('touchend', (event) => {
event.stopPropagation()
})
}
export async function getContainer(): Promise<HTMLElement> {
let $container: HTMLElement | null = document.getElementById(containerID)
if (!$container) {
$container = document.createElement('div')
$container.id = containerID
attachEventsToContainer($container)
$container.style.zIndex = zIndex
return new Promise((resolve, reject) => {
setTimeout(() => {
const $container_: HTMLElement | null = document.getElementById(containerID)
if ($container_) {
resolve($container_)
return
}
if (!$container) {
reject(new Error('Failed to create container'))
return
}
const shadowRoot = $container.attachShadow({ mode: 'open' })
const $inner = document.createElement('div')
shadowRoot.appendChild($inner)
const $html = document.body.parentElement
if ($html) {
$html.appendChild($container as HTMLElement)
} else {
document.appendChild($container as HTMLElement)
}
resolve($container)
}, 100)
})
}
return new Promise((resolve) => {
resolve($container as HTMLElement)
})
}
export async function queryPopupThumbElement(): Promise<HTMLDivElement | null> {
const $container = await getContainer()
return $container.shadowRoot?.querySelector(`#${popupThumbID}`) as HTMLDivElement | null
}
export async function queryPopupCardElement(): Promise<HTMLDivElement | null> {
const $container = await getContainer()
return $container.shadowRoot?.querySelector(`#${popupCardID}`) as HTMLDivElement | null
}
export function calculateMaxXY($popupCard: HTMLElement): number[] {
const { innerWidth, innerHeight, scrollX, scrollY } = window
const { scrollLeft, scrollTop } = document.documentElement
const { width, height } = $popupCard.getBoundingClientRect()
const maxX = (scrollX || scrollLeft) + innerWidth - width - documentPadding
const maxY = (scrollY || scrollTop) + innerHeight - height - documentPadding
return [maxX, maxY]
}
================================================
FILE: src/browser-extension/enable-dev-hmr.ts
================================================
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import RefreshRuntime from '/@react-refresh'
if (import.meta.hot) {
RefreshRuntime.injectIntoGlobalHook(window)
// eslint-disable-next-line @typescript-eslint/no-empty-function
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
// eslint-disable-next-line camelcase
window.__vite_plugin_react_preamble_installed__ = true
}
================================================
FILE: src/browser-extension/manifest.ts
================================================
/* eslint-disable camelcase */
import { version } from '../../package.json'
export function getManifest(browser: 'firefox' | 'chromium') {
const manifest: chrome.runtime.Manifest = {
manifest_version: 3,
name: 'NextAI Translator',
description: `NextAI-Translator is a browser extension that uses the ChatGPT API for translation.`,
version: version,
icons: {
'16': 'icon.png',
'32': 'icon.png',
'48': 'icon.png',
'128': 'icon.png',
},
options_ui: {
page: 'src/browser-extension/options/index.html',
open_in_tab: true,
},
action: {
default_icon: 'icon.png',
default_popup: 'src/browser-extension/popup/index.html',
},
content_scripts: [
{
matches: ['<all_urls>'],
all_frames: true,
match_about_blank: true,
js: ['src/browser-extension/content_script/index.tsx'],
},
],
background: {
service_worker: 'src/browser-extension/background/index.ts',
},
permissions: ['storage', 'contextMenus', 'webRequest'],
commands: {
'open-popup': {
suggested_key: {
default: 'Ctrl+Shift+Y',
mac: 'Command+Shift+Y',
},
description: 'Open the popup',
},
},
host_permissions: [
'https://*.openai.com/',
'https://*.openai.azure.com/',
'https://*.ingest.sentry.io/',
'*://speech.platform.bing.com/',
'https://*.googletagmanager.com/',
'https://*.google-analytics.com/',
'https://*.minimax.chat/',
'https://*.githubusercontent.com/',
'https://*.baidu.com/',
'https://api-edge.cognitive.microsofttranslator.com/',
'https://*.microsoft.com/',
'https://*.google.com/',
'https://*.googleapis.com/',
'https://*.moonshot.cn/',
'https://*.volces.com/',
'https://*.chatglm.cn/',
'https://*.cohere.ai/',
'https://*.deepseek.com/',
],
}
if (browser === 'firefox') {
manifest.browser_specific_settings = {
gecko: {
id: 'openaitranslator@gmail.com',
},
}
manifest.background = {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
scripts: ['src/browser-extension/background/index.ts'],
}
}
return manifest
}
================================================
FILE: src/browser-extension/options/index.css
================================================
body {
margin: 0;
}
================================================
FILE: src/browser-extension/options/index.html
================================================
<!DOCTYPE html>
<html>
<head>
<title>NextAI Translator Options</title>
<style>
#root {
height: 100vh;
}
[data-baseweb='tooltip'],
[data-baseweb='toaster'],
[data-baseweb='modal'],
[data-baseweb='popover'] {
z-index: 1000;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/browser-extension/options/index.tsx"></script>
</body>
</html>
================================================
FILE: src/browser-extension/options/index.tsx
================================================
import '../enable-dev-hmr'
import React, { useEffect, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { Settings } from '../../common/components/Settings'
import { Client as Styletron } from 'styletron-engine-atomic'
import '../../common/i18n.js'
import './index.css'
import { createUseStyles } from 'react-jss'
import { IThemedStyleProps } from '../../common/types'
import { useTheme } from '../../common/hooks/useTheme'
import browser from 'webextension-polyfill'
import { optionsPageHeaderPromotionIDKey, optionsPageOpenaiAPIKeyPromotionIDKey } from '../common'
const engine = new Styletron()
const useStyles = createUseStyles({
root: (props: IThemedStyleProps) => ({
display: 'flex',
justifyContent: 'center',
backgroundColor: props.theme.colors.backgroundSecondary,
minHeight: '100%',
}),
container: {
maxWidth: '768px',
height: '100%',
},
})
const Options = () => {
const { theme, themeType } = useTheme()
const styles = useStyles({ theme, themeType })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(window as any).__IS_OT_BROWSER_EXTENSION_OPTIONS__ = true
const [openaiAPIKeyPromotionID, setOpenaiAPIKeyPromotionID] = useState<string>()
const [headerPromotionID, setHeaderPromotionID] = useState<string>()
useEffect(() => {
browser.storage.local.get(optionsPageOpenaiAPIKeyPromotionIDKey).then((resp) => {
setOpenaiAPIKeyPromotionID(resp[optionsPageOpenaiAPIKeyPromotionIDKey])
browser.storage.local.remove(optionsPageOpenaiAPIKeyPromotionIDKey)
})
}, [])
useEffect(() => {
browser.storage.local.get(optionsPageHeaderPromotionIDKey).then((resp) => {
setHeaderPromotionID(resp[optionsPageHeaderPromotionIDKey])
browser.storage.local.remove(optionsPageHeaderPromotionIDKey)
})
}, [])
return (
<div className={styles.root}>
<div className={styles.container}>
<Settings
engine={engine}
openaiAPIKeyPromotionID={openaiAPIKeyPromotionID}
headerPromotionID={headerPromotionID}
/>
</div>
</div>
)
}
const root = createRoot(document.getElementById('root') as HTMLElement)
root.render(
<React.StrictMode>
<Options />
</React.StrictMode>
)
================================================
FILE: src/browser-extension/popup/index.css
================================================
/* @tailwind base; */
/* @tailwind components; */
/* @tailwind utilities; */
html,
body {
padding: 0;
margin: 0;
}
@media (prefers-color-scheme: dark) {
.popup {
background: #1f1f1f;
}
}
================================================
FILE: src/browser-extension/popup/index.html
================================================
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>NextAI Translator</title>
<style>
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
body {
position: relative;
min-width: 700px;
min-height: 600px;
background: #000;
}
#root {
height: 100%;
}
[data-baseweb='tooltip'],
[data-baseweb='toaster'],
[data-baseweb='modal'],
[data-baseweb='popover'] {
z-index: 1000;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/browser-extension/popup/index.tsx"></script>
</body>
</html>
================================================
FILE: src/browser-extension/popup/index.tsx
================================================
import '../enable-dev-hmr'
import { createRoot } from 'react-dom/client'
import { Translator } from '../../common/components/Translator'
import { Client as Styletron } from 'styletron-engine-atomic'
import '../../common/i18n.js'
import './index.css'
import { PREFIX } from '../../common/constants'
import { useTheme } from '../../common/hooks/useTheme'
const engine = new Styletron({
prefix: `${PREFIX}-styletron-`,
})
const root = createRoot(document.getElementById('root') as HTMLElement)
function App() {
const { theme } = useTheme()
return (
<div
style={{
position: 'relative',
height: '100%',
background: theme.colors.backgroundPrimary,
}}
data-testid='popup-container'
>
<Translator showSettingsIcon defaultShowSettings engine={engine} autoFocus />
</div>
)
}
root.render(<App />)
================================================
FILE: src/common/__tests__/translate.test.ts
================================================
import { describe, expect, it } from 'vitest'
import { QuoteProcessor } from '../translate'
describe('QuoteProcessor', () => {
it('should return the string without quote', () => {
const quoteProcessor = new QuoteProcessor()
const deltas = [
...quoteProcessor.quoteStart.split(''),
'T',
'h',
'i',
's',
' ',
'i',
's',
' ',
'a',
' ',
't',
'e',
's',
't',
'.',
...quoteProcessor.quoteEnd.split(''),
]
let targetText = ''
for (const delta of deltas) {
targetText += quoteProcessor.processText(delta)
}
expect(targetText).toEqual('This is a test.')
})
it('should return the string without quote', () => {
const quoteProcessor = new QuoteProcessor()
const deltas = [
...quoteProcessor.quoteStart.split(''),
'T',
'h',
'i',
's',
' ',
'i',
's',
' ',
'a',
' ',
't',
'e',
's',
't',
'.',
'(',
')' + quoteProcessor.quoteEnd.split('')[0],
...quoteProcessor.quoteEnd.split('').slice(1),
]
let targetText = ''
for (const delta of deltas) {
targetText += quoteProcessor.processText(delta)
}
expect(targetText).toEqual('This is a test.()')
})
it('should return the string without quote', () => {
const quoteProcessor = new QuoteProcessor()
const text = 'This is a test.'
const targetText = quoteProcessor.processText(quoteProcessor.quoteStart + text + quoteProcessor.quoteEnd)
expect(targetText).toEqual(text)
})
it('should return the string without quote', () => {
const quoteProcessor = new QuoteProcessor()
const text = 'This is a test.'
const targetText = quoteProcessor.processText(
`${quoteProcessor.quoteStart}This${quoteProcessor.quoteStart} is ${quoteProcessor.quoteEnd}a${quoteProcessor.quoteStart} test.${quoteProcessor.quoteEnd}`
)
expect(targetText).toEqual(text)
})
it('should return the same string if no quote exists', () => {
const quoteProcessor = new QuoteProcessor()
const deltas = [
'<X',
'1',
'2',
'Y>',
'T',
'h',
'i',
's',
' ',
'i',
's',
' ',
'a',
' ',
't',
'e',
's',
't',
'.',
'</',
'X',
'1',
'2',
'Y>',
]
let targetText = ''
for (const delta of deltas) {
targetText += quoteProcessor.processText(delta)
}
expect(targetText).toEqual('<X12Y>This is a test.</X12Y>')
})
it('should return the same string if no quote exists', () => {
const quoteProcessor = new QuoteProcessor()
const text = '<X12Y>This is a test.</X12Y>'
const targetText = quoteProcessor.processText(text)
expect(targetText).toEqual(text)
})
it('should return the same string if no quote exists', () => {
const quoteProcessor = new QuoteProcessor()
const text = `This is${quoteProcessor.quoteStart.slice(0, quoteProcessor.quoteStart.length - 1)} a test.`
const targetText = quoteProcessor.processText(text)
expect(targetText).toEqual(text)
})
it('do not remove the sub part of quote', () => {
const quoteProcessor = new QuoteProcessor()
const text = `This is${quoteProcessor.quoteStart.slice(0, quoteProcessor.quoteStart.length - 1)} a test.`
const targetText = quoteProcessor.processText(quoteProcessor.quoteStart + text + quoteProcessor.quoteEnd)
expect(targetText).toEqual(text)
})
it('do not remove the sub part of quote', () => {
const quoteProcessor = new QuoteProcessor()
const text = `This is${quoteProcessor.quoteEnd.slice(0, quoteProcessor.quoteEnd.length - 1)} a test.`
const targetText = quoteProcessor.processText(quoteProcessor.quoteStart + text + quoteProcessor.quoteEnd)
expect(targetText).toEqual(text)
})
it('do not remove the sub part of quote', () => {
const quoteProcessor = new QuoteProcessor()
const text = `This is${quoteProcessor.quoteStart.slice(
0,
quoteProcessor.quoteStart.length - 1
)} a${quoteProcessor.quoteStart.slice(
0,
quoteProcessor.quoteStart.length - 2
)} te${quoteProcessor.quoteEnd.slice(0, quoteProcessor.quoteEnd.length - 1)}st${quoteProcessor.quoteEnd.slice(
0,
quoteProcessor.quoteEnd.length - 2
)}.`
const targetText = quoteProcessor.processText(quoteProcessor.quoteStart + text + quoteProcessor.quoteEnd)
expect(targetText).toEqual(text)
})
})
================================================
FILE: src/common/analysis.ts
================================================
import * as Sentry from '@sentry/react'
import ReactGA from 'react-ga4'
import { getSettings, isDesktopApp, isUserscript } from './utils'
export async function setupAnalysis() {
if (isUserscript()) {
return
}
doSetupAnalysis()
}
let isAnalysisSetupped = false
export async function doSetupAnalysis() {
if (isAnalysisSetupped) {
return
}
isAnalysisSetupped = true
const settings = await getSettings()
if (settings.disableCollectingStatistics) {
return
}
if (isDesktopApp()) {
Sentry.init({
dsn: 'https://477519542bd6491cb347ca3f55fcdce6@o441417.ingest.sentry.io/4505051776090112',
integrations: [
new Sentry.BrowserTracing({
traceFetch: false,
}),
new Sentry.Replay(),
],
// Performance Monitoring
tracesSampleRate: 0.5, // Capture 100% of the transactions, reduce in production!
// Session Replay
replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.
})
ReactGA.initialize('G-D7054DX333')
}
}
================================================
FILE: src/common/background/eventnames.ts
================================================
import { IVocabularyInternalService } from '../internal-services/vocabulary'
import { IHistoryInternalService } from '../internal-services/history'
export const BackgroundEventNames = {
fetch: 'fetch',
vocabularyService: 'vocabularyService',
actionService: 'actionService',
historyService: 'historyService',
getItem: 'getItem',
setItem: 'setItem',
removeItem: 'removeItem',
}
export type BackgroundVocabularyServiceMethodNames = keyof IVocabularyInternalService
export type BackgroundHistoryServiceMethodNames = keyof IHistoryInternalService
================================================
FILE: src/common/background/fetch.ts
================================================
import { isFirefox } from '../utils'
import { BackgroundEventNames } from './eventnames'
import { ReadableStream as ReadableStreamPolyfill } from 'web-streams-polyfill/ponyfill'
export interface BackgroundFetchRequestMessage {
type: 'open' | 'abort'
details?: { url: string; options: RequestInit }
}
export interface BackgroundFetchResponseMessage
extends Pick<Response, 'ok' | 'status' | 'statusText' | 'redirected' | 'type' | 'url'> {
error?: { message: string; name: string }
status: number
data?: string
}
async function readText(stream: ReadableStream) {
const reader = stream.getReader()
let text = ''
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
const str = new TextDecoder().decode(value)
text += str
}
return text
}
export async function backgroundFetch(input: string, options: RequestInit) {
return new Promise<Response>((resolve, reject) => {
;(async () => {
const { signal, ...fetchOptions } = options
if (signal?.aborted) {
reject(new DOMException('Aborted', 'AbortError'))
return
}
const ReadableStream = isFirefox()
? (ReadableStreamPolyfill as typeof window.ReadableStream)
: window.ReadableStream
const textEncoder = new TextEncoder()
let resolved = false
const browser = (await import('webextension-polyfill')).default
const port = browser.runtime.connect({ name: BackgroundEventNames.fetch })
const message: BackgroundFetchRequestMessage = {
type: 'open',
details: { url: input, options: fetchOptions },
}
const readableStream = new ReadableStream({
start(controller) {
port.onMessage.addListener((msg: BackgroundFetchResponseMessage) => {
const { data, error, ...restResp } = msg
if (error) {
const e = new Error()
e.message = error.message
e.name = error.name
controller.error(e)
return
}
controller.enqueue(textEncoder.encode(data))
if (!resolved) {
resolve({
...restResp,
body: readableStream,
text: () => readText(readableStream),
json: async () => {
const text = await readText(readableStream)
return JSON.parse(text)
},
} as unknown as Response)
resolved = true
}
})
port.onDisconnect.addListener(() => {
signal?.removeEventListener('abort', handleAbort)
try {
controller.close()
} catch (e) {
// may throw if controller is errored
}
})
port.postMessage(message)
},
})
function handleAbort() {
port.postMessage({ type: 'abort' })
}
signal?.addEventListener('abort', handleAbort)
})()
})
}
================================================
FILE: src/common/background/local-storage.ts
================================================
/* eslint-disable @typescript-eslint/no-unused-vars */
import { BackgroundEventNames } from './eventnames'
export async function backgroundGetItem(key: string): Promise<string | null> {
const browser = (await import('webextension-polyfill')).default
const resp = await browser.runtime.sendMessage({
type: BackgroundEventNames.getItem,
key,
})
return resp.value
}
export async function backgroundSetItem(key: string, value: string | null): Promise<void> {
const browser = (await import('webextension-polyfill')).default
await browser.runtime.sendMessage({
type: BackgroundEventNames.setItem,
key,
value,
})
return
}
export async function backgroundRemoveItem(key: string): Promise<void> {
const browser = (await import('webextension-polyfill')).default
await browser.runtime.sendMessage({
type: BackgroundEventNames.removeItem,
key,
})
return
}
================================================
FILE: src/common/background/services/action.ts
================================================
import { IActionInternalService, ICreateActionOption, IUpdateActionOption } from '../../internal-services/action'
import { Action } from '../../internal-services/db'
import { callMethod } from './base'
class BackgroundActionService implements IActionInternalService {
create(opt: ICreateActionOption): Promise<Action> {
return callMethod('actionService', 'create', [opt])
}
update(action: Action, opt: IUpdateActionOption): Promise<Action> {
return callMethod('actionService', 'update', [action, opt])
}
bulkPut(actions: Action[]): Promise<void> {
return callMethod('actionService', 'bulkPut', [actions])
}
get(id: number): Promise<Action | undefined> {
return callMethod('actionService', 'get', [id])
}
getByMode(mode: string): Promise<Action | undefined> {
return callMethod('actionService', 'getByMode', [mode])
}
delete(id: number): Promise<void> {
return callMethod('actionService', 'delete', [id])
}
list(): Promise<Action[]> {
return callMethod('actionService', 'list', [])
}
count(): Promise<number> {
return callMethod('actionService', 'count', [])
}
}
export const backgroundActionService = new BackgroundActionService()
================================================
FILE: src/common/background/services/base.ts
================================================
import { BackgroundEventNames } from '../eventnames'
export async function callMethod(
eventType: keyof typeof BackgroundEventNames,
methodName: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: any[]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> {
const browser = (await import('webextension-polyfill')).default
const resp = await browser.runtime.sendMessage({
type: BackgroundEventNames[eventType],
method: methodName,
args: args,
})
return resp.result
}
================================================
FILE: src/common/background/services/history.ts
================================================
import {
CreateHistoryItem,
HistoryQueryOptions,
IHistoryInternalService,
UpdateHistoryPayload,
} from '../../internal-services/history'
import { HistoryItem } from '../../internal-services/db'
import { callMethod } from './base'
class BackgroundHistoryService implements IHistoryInternalService {
create(item: CreateHistoryItem): Promise<HistoryItem> {
return callMethod('historyService', 'create', [item])
}
update(id: number, payload: UpdateHistoryPayload): Promise<void> {
return callMethod('historyService', 'update', [id, payload])
}
updateFavorite(id: number, favorite: boolean): Promise<void> {
return callMethod('historyService', 'updateFavorite', [id, favorite])
}
touch(id: number): Promise<void> {
return callMethod('historyService', 'touch', [id])
}
delete(id: number): Promise<void> {
return callMethod('historyService', 'delete', [id])
}
clear(): Promise<void> {
return callMethod('historyService', 'clear', [])
}
list(options?: HistoryQueryOptions | undefined): Promise<HistoryItem[]> {
return callMethod('historyService', 'list', [options])
}
get(id: number): Promise<HistoryItem | undefined> {
return callMethod('historyService', 'get', [id])
}
}
export const backgroundHistoryService = new BackgroundHistoryService()
================================================
FILE: src/common/background/services/vocabulary.ts
================================================
import { VocabularyItem } from '../../internal-services/db'
import { IVocabularyInternalService } from '../../internal-services/vocabulary'
import { callMethod } from './base'
class BackgroundVocabularyService implements IVocabularyInternalService {
async putItem(item: VocabularyItem): Promise<void> {
return await callMethod('vocabularyService', 'putItem', [item])
}
async getItem(word: string): Promise<VocabularyItem | undefined> {
return await callMethod('vocabularyService', 'getItem', [word])
}
async deleteItem(word: string): Promise<void> {
return await callMethod('vocabularyService', 'deleteItem', [word])
}
async countItems(): Promise<number> {
return await callMethod('vocabularyService', 'countItems', [])
}
async listItems(): Promise<VocabularyItem[]> {
return await callMethod('vocabularyService', 'listItems', [])
}
async listRandomItems(limit: number): Promise<VocabularyItem[]> {
return await callMethod('vocabularyService', 'listRandomItems', [limit])
}
async listFrequencyItems(limit: number): Promise<VocabularyItem[]> {
return await callMethod('vocabularyService', 'listFrequencyItems', [limit])
}
async isCollected(word: string): Promise<boolean> {
return await callMethod('vocabularyService', 'isCollected', [word])
}
}
export const backgroundVocabularyService = new BackgroundVocabularyService()
================================================
FILE: src/common/components/ActionForm.tsx
================================================
import { useTranslation } from 'react-i18next'
import { ICreateActionOption } from '../internal-services/action'
import { Action } from '../internal-services/db'
import { createForm } from './Form'
import { Input } from 'baseui-sd/input'
import { Textarea } from 'baseui-sd/textarea'
import { Button } from 'baseui-sd/button'
import { useCallback, useEffect, useState } from 'react'
import { actionService } from '../services/action'
import { createUseStyles } from 'react-jss'
import { IThemedStyleProps } from '../types'
import { useTheme } from '../hooks/useTheme'
import { IconPicker } from './IconPicker'
import { RenderingFormatSelector } from './RenderingFormatSelector'
const useStyles = createUseStyles({
placeholder: (props: IThemedStyleProps) => ({
color: props.theme.colors.positive,
}),
promptCaptionContainer: () => ({
'lineHeight': 1.8,
'& *': {
'-ms-user-select': 'text',
'-webkit-user-select': 'text',
'user-select': 'text',
},
}),
placeholderCaptionContainer: () => ({
listStyle: 'square',
margin: 0,
padding: 0,
marginTop: 10,
paddingLeft: 20,
}),
})
export interface IActionFormProps {
action?: Action
onSubmit: (action: Action) => void
}
const { Form, FormItem } = createForm<ICreateActionOption>()
export function ActionForm(props: IActionFormProps) {
const { theme, themeType } = useTheme()
const styles = useStyles({ theme, themeType })
const { t } = useTranslation()
const [loading, setLoading] = useState(false)
const onSubmit = useCallback(
async (values: ICreateActionOption) => {
setLoading(true)
let action: Action
if (props.action) {
action = await actionService.update(props.action, values)
} else {
action = await actionService.create(values)
}
props.onSubmit(action)
setLoading(false)
},
[props]
)
const rolePlaceholdersCaption = (
<ul className={styles.placeholderCaptionContainer}>
<li>
<span className={styles.placeholder}>{'${sourceLang}'}</span> {t('represents the source language')}
</li>
<li>
<span className={styles.placeholder}>{'${targetLang}'}</span> {t('represents the target language')}
</li>
</ul>
)
const commandPlaceholdersCaption = (
<ul className={styles.placeholderCaptionContainer}>
<li>
<span className={styles.placeholder}>{'${sourceLang}'}</span> {t('represents the source language')}
</li>
<li>
<span className={styles.placeholder}>{'${targetLang}'}</span> {t('represents the target language')}
</li>
<li>
<span className={styles.placeholder}>{'${text}'}</span>{' '}
{t(
'represents the original text, which is usually not needed inside the prompt because it is automatically injected'
)}
</li>
</ul>
)
const rolePromptCaption = (
<div className={styles.promptCaptionContainer}>
<div>{t('Role prompt indicates what role the action represents.')}</div>
<div>{t('Role prompt example: You are a translator.')}</div>
<div>{t('Placeholders')}:</div>
<div>{rolePlaceholdersCaption}</div>
</div>
)
const commandPromptCaption = (
<div className={styles.promptCaptionContainer}>
<div>
{t(
'Command prompt indicates what command should be issued to the role represented by the action when the action is executed.'
)}
</div>
<div>
{t('Command prompt example: Please translate the following text from ${sourceLang} to ${targetLang}.')}
</div>
<div>{t('Placeholders')}:</div>
<div>{commandPlaceholdersCaption}</div>
</div>
)
const [values, setValues] = useState<ICreateActionOption | undefined>(props.action)
useEffect(() => {
setValues(props.action)
}, [props.action])
const handleValuesChange = useCallback((_changes: Partial<ICreateActionOption>, values: ICreateActionOption) => {
setValues(values)
}, [])
return (
<Form initialValues={values} onValuesChange={handleValuesChange} onFinish={onSubmit}>
<FormItem required name='name' label={t('Name')}>
<Input size='compact' />
</FormItem>
<FormItem required name='icon' label={t('Icon')}>
<IconPicker />
</FormItem>
<FormItem name='rolePrompt' label={`${t('Role Prompt')} (Optional)`} caption={rolePromptCaption}>
<Textarea
rows={4}
overrides={{
Root: {
style: {
width: '100%',
},
},
}}
size='compact'
resize='vertical'
/>
</FormItem>
<FormItem required name='commandPrompt' label={t('Command Prompt')} caption={commandPromptCaption}>
<Textarea
rows={4}
overrides={{
Root: {
style: {
width: '100%',
},
},
}}
size='compact'
resize='vertical'
/>
</FormItem>
<FormItem name='outputRenderingFormat' label={t('Output rendering format')}>
<RenderingFormatSelector />
</FormItem>
<div
style={{
display: 'flex',
alignItems: 'center',
flexDirection: 'row',
gap: 10,
}}
>
<div
style={{
marginRight: 'auto',
}}
/>
<Button isLoading={loading} size='compact'>
{t('Submit')}
</Button>
</div>
</Form>
)
}
================================================
FILE: src/common/components/ActionManager.tsx
================================================
import { useLiveQuery } from 'dexie-react-hooks'
import icon from '../assets/images/icon.png'
import { actionService } from '../services/action'
import { FiEdit } from 'react-icons/fi'
import { createUseStyles } from 'react-jss'
import { IThemedStyleProps } from '../types'
import { useTheme } from '../hooks/useTheme'
import { useTranslation } from 'react-i18next'
import { format } from 'date-fns'
import { Button } from 'baseui-sd/button'
import { List, arrayMove } from 'baseui-sd/dnd-list'
import { RiDeleteBinLine } from 'react-icons/ri'
import { createElement, useCallback, useReducer, useState } from 'react'
import * as mdIcons from 'react-icons/md'
import { Action } from '../internal-services/db'
import { Modal, ModalBody, ModalButton, ModalFooter, ModalHeader } from 'baseui-sd/modal'
import { ActionForm } from './ActionForm'
import { IconType } from 'react-icons'
import { isDesktopApp } from '../utils'
import { MdArrowDownward, MdArrowUpward } from 'react-icons/md'
import { useSettings } from '../hooks/useSettings'
import { emit } from '@tauri-apps/api/event'
const useStyles = createUseStyles({
root: () => ({
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: isDesktopApp() ? '40px 20px 20px 20px' : 0,
boxSizing: 'border-box',
width: isDesktopApp() ? '100%' : '600px',
}),
header: (props: IThemedStyleProps) => ({
width: '100%',
color: props.theme.colors.contentPrimary,
padding: isDesktopApp() ? '40px 20px 20px 20px' : 20,
boxSizing: 'border-box',
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
gap: 10,
position: isDesktopApp() ? 'fixed' : 'block',
backdropFilter: 'blur(10px)',
zIndex: 1,
left: 0,
top: 0,
background: props.themeType === 'dark' ? 'rgba(31, 31, 31, 0.5)' : 'rgba(255, 255, 255, 0.5)',
flexFlow: 'row nowrap',
cursor: 'move',
borderBottom: `1px solid ${props.theme.colors.borderTransparent}`,
}),
iconContainer: {
display: 'flex',
alignItems: 'center',
gap: '8px',
flexShrink: 0,
marginRight: 'auto',
},
icon: {
'display': 'block',
'width': '16px',
'height': '16px',
'-ms-user-select': 'none',
'-webkit-user-select': 'none',
'user-select': 'none',
},
iconText: (props: IThemedStyleProps) => ({
'color': props.themeType === 'dark' ? props.theme.colors.contentSecondary : props.theme.colors.contentPrimary,
'fontSize': '14px',
'fontWeight': 600,
'cursor': 'unset',
'@media screen and (max-width: 570px)': {
display: props.isDesktopApp ? 'none' : undefined,
},
}),
operationList: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
gap: 10,
},
actionList: () => ({
paddingTop: isDesktopApp() ? 70 : 0,
width: '100%',
}),
actionItem: () => ({
'width': '100%',
'display': 'flex',
'flexDirection': 'row',
'alignItems': 'center',
'gap': '20px',
'&:hover $actionOperation': {
display: 'flex',
},
}),
actionContent: () => ({
display: 'flex',
flexDirection: 'column',
gap: '2px',
width: '100%',
overflow: 'hidden',
}),
actionOperation: {
flexShrink: 0,
display: 'none',
flexDirection: 'row',
alignItems: 'center',
marginLeft: 'auto',
gap: 10,
},
name: {
fontSize: '16px',
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
gap: 10,
},
prompts: (props: IThemedStyleProps) => ({
'color': props.theme.colors.contentSecondary,
'fontSize': '12px',
'display': 'flex',
'flexDirection': 'column',
'gap': '3px',
'& > div': {
'display': '-webkit-box',
'overflow': 'hidden',
'lineHeight': '1.5',
'maxWidth': '400px',
'textOverflow': 'ellipsis',
'-webkit-line-clamp': 2,
'-webkit-box-orient': 'vertical',
},
}),
metadata: (props: IThemedStyleProps) => ({
color: props.theme.colors.contentSecondary,
fontSize: '12px',
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
gap: '6px',
}),
})
export interface IActionManagerProps {
draggable?: boolean
}
export function ActionManager({ draggable = true }: IActionManagerProps) {
const [refreshActionsFlag, changeRefreshActionsFlag] = useReducer((x: number) => x + 1, 0)
const { t } = useTranslation()
const { theme, themeType } = useTheme()
const styles = useStyles({ theme, themeType })
const actions = useLiveQuery(() => actionService.list(), [refreshActionsFlag])
const [showActionForm, setShowActionForm] = useState(false)
const [updatingAction, setUpdatingAction] = useState<Action>()
const [deletingAction, setDeletingAction] = useState<Action>()
const { settings } = useSettings()
const refreshActions = useCallback(() => {
if (!isDesktopApp()) {
changeRefreshActionsFlag()
return
}
emit('refresh-actions', {})
}, [])
return (
<div
className={styles.root}
style={{
width: !draggable ? '800px' : undefined,
}}
>
<div
className={styles.header}
data-tauri-drag-region
style={{
backgroundColor: settings.enableBackgroundBlur ? 'transparent' : undefined,
}}
>
<div className={styles.iconContainer}>
<img data-tauri-drag-region className={styles.icon} src={icon} />
<div className={styles.iconText}>{t('Action Manager')}</div>
</div>
<div
style={{
marginRight: 'auto',
}}
/>
<div className={styles.operationList}>
<Button
size='mini'
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setUpdatingAction(undefined)
setShowActionForm(true)
}}
>
{t('Create')}
</Button>
</div>
</div>
<div className={styles.actionList}>
<List
overrides={{
Item: {
style: {
backgroundColor: 'transparent',
// backgroundColor: color(theme.colors.backgroundPrimary).alpha(0.9).lighten(0.8).string(),
},
},
}}
onChange={async ({ oldIndex, newIndex }) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const newActions = arrayMove(actions!, oldIndex, newIndex)
await actionService.bulkPut(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
newActions.map((a, idx) => {
return {
...a,
idx,
}
})
)
refreshActions()
}}
items={actions?.map((action, idx) => (
<div key={action.id} className={styles.actionItem}>
<div className={styles.actionContent}>
<div className={styles.name}>
{action.icon &&
createElement((mdIcons as Record<string, IconType>)[action.icon], { size: 16 })}
{action.mode ? t(action.name) : action.name}
{action.mode && (
<div
style={{
display: 'inline-block',
fontSize: '12px',
background: theme.colors.backgroundTertiary,
padding: '1px 4px',
borderRadius: '2px',
}}
>
{t('built-in')}
</div>
)}
</div>
<div className={styles.prompts}>
<div>{action.rolePrompt}</div>
<div>{action.commandPrompt}</div>
</div>
<div className={styles.metadata}>
<div>
{t('Created at')} {format(+action?.createdAt, 'yyyy-MM-dd HH:mm:ss')}
</div>
</div>
</div>
<div className={styles.actionOperation}>
{!draggable && (
<>
<Button
size='mini'
disabled={idx === 0}
onClick={async (e) => {
e.preventDefault()
e.stopPropagation()
const newActions = arrayMove(actions, idx, idx - 1)
await actionService.bulkPut(
newActions.map((a, idx) => {
return {
...a,
idx,
}
})
)
refreshActions()
}}
>
<MdArrowUpward size={12} />
</Button>
<Button
size='mini'
disabled={idx === actions.length - 1}
onClick={async (e) => {
e.preventDefault()
e.stopPropagation()
const newActions = arrayMove(actions, idx, idx + 1)
await actionService.bulkPut(
newActions.map((a, idx) => {
return {
...a,
idx,
}
})
)
refreshActions()
}}
>
<MdArrowDownward size={12} />
</Button>
</>
)}
<Button
size='mini'
startEnhancer={<FiEdit size={12} />}
disabled={!!action.mode}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setUpdatingAction(action)
setShowActionForm(true)
}}
>
{t('Update')}
</Button>
<Button
size='mini'
startEnhancer={<RiDeleteBinLine size={12} />}
disabled={!!action.mode}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setDeletingAction(action)
}}
>
{t('Delete')}
</Button>
</div>
</div>
))}
/>
</div>
<Modal
isOpen={showActionForm}
onClose={() => {
setShowActionForm(false)
setUpdatingAction(undefined)
}}
closeable
size='default'
autoFocus
animate
role='dialog'
>
<ModalHeader>
{updatingAction ? t('Update sth', [t('Action')]) : t('Create sth', [t('Action')])}
</ModalHeader>
<ModalBody>
<ActionForm
action={updatingAction}
onSubmit={() => {
setShowActionForm(false)
refreshActions()
}}
/>
</ModalBody>
</Modal>
<Modal
isOpen={!!deletingAction}
onClose={() => {
setDeletingAction(undefined)
}}
closeable
size='default'
autoFocus
animate
role='dialog'
>
<ModalHeader>{t('Delete sth', [t('Action')])}</ModalHeader>
<ModalBody>{t('Are you sure to delete sth?', [`${t('Action')} ${deletingAction?.name}`])}</ModalBody>
<ModalFooter>
<ModalButton
size='compact'
kind='tertiary'
onClick={() => {
setDeletingAction(undefined)
}}
>
{t('Cancel')}
</ModalButton>
<ModalButton
size='compact'
onClick={async () => {
await actionService.delete(deletingAction?.id as number)
refreshActions()
setDeletingAction(undefined)
}}
>
{t('Ok')}
</ModalButton>
</ModalFooter>
</Modal>
</div>
)
}
================================================
FILE: src/common/components/CodeBlock.tsx
================================================
import { CodeBlock as BaseCodeBlock } from 'react-code-block'
import { Button } from 'baseui-sd/button'
import { themes } from 'prism-react-renderer'
import { createUseStyles } from 'react-jss'
import { useCopyToClipboard } from 'react-use'
import { useEffect, useState } from 'react'
import { useTheme } from '../hooks/useTheme'
const useStyles = createUseStyles({
selectNone: {
'user-select': 'none',
'-webkit-user-select': 'none',
'-moz-user-select': 'none',
},
})
export interface ICodeBlockProps {
code: string
language: string
}
export function CodeBlock({ code, language }: ICodeBlockProps) {
const { theme, themeType } = useTheme()
const styles = useStyles()
const [, copyToClipboard] = useCopyToClipboard()
const [isCopied, setIsCopied] = useState(false)
const copyCode = () => {
copyToClipboard(code)
setIsCopied(true)
}
useEffect(() => {
const timeout = setTimeout(() => {
setIsCopied(false)
}, 2000)
return () => clearTimeout(timeout)
}, [isCopied])
return (
<BaseCodeBlock code={code} language={language} theme={themeType === 'dark' ? themes.oneDark : themes.oneLight}>
<div
style={{
position: 'relative',
}}
>
<BaseCodeBlock.Code
style={{
margin: '0.2rem',
padding: '0.7rem',
paddingRight: '2rem',
borderRadius: '0.4rem',
boxShadow: theme.lighting.shadow400,
backgroundColor: theme.colors.backgroundSecondary,
}}
>
<div
style={{
display: 'table-row',
}}
>
{language !== 'text' && (
<BaseCodeBlock.LineNumber
style={{
display: 'table-cell',
fontSize: '0.875rem',
lineHeight: '1.25rem',
textAlign: 'right',
paddingRight: '1rem',
}}
className={styles.selectNone}
/>
)}
<BaseCodeBlock.LineContent
style={{
display: 'table-cell',
whiteSpace: 'pre-wrap',
}}
>
<BaseCodeBlock.Token />
</BaseCodeBlock.LineContent>
</div>
</BaseCodeBlock.Code>
<Button
overrides={{
Root: {
style: {
position: 'absolute',
top: '0.5rem',
right: '0.8rem',
},
},
}}
kind='tertiary'
size='mini'
onClick={copyCode}
>
<svg
xmlns='http://www.w3.org/2000/svg'
fill='none'
viewBox='0 0 24 24'
strokeWidth={2}
stroke='currentColor'
style={{
width: '1rem',
height: '1rem',
}}
>
{isCopied ? (
<path strokeLinecap='round' strokeLinejoin='round' d='M4.5 12.75l6 6 9-13.5' />
) : (
<path
strokeLinecap='round'
strokeLinejoin='round'
d='M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184'
/>
)}
</svg>
</Button>
</div>
</BaseCodeBlock>
)
}
================================================
FILE: src/common/components/CopyButton.tsx
================================================
import { Tooltip } from 'baseui-sd/tooltip'
import { CopyToClipboard } from 'react-copy-to-clipboard'
import { RxCopy } from 'react-icons/rx'
import { useTranslation } from 'react-i18next'
import toast from 'react-hot-toast/headless'
export function CopyButton({ text, styles }: { text: string; styles: { actionButton: string } }) {
const { t } = useTranslation()
return (
<Tooltip content={t('Copy to clipboard')} placement='bottom'>
<div>
<CopyToClipboard
text={text}
onCopy={() => {
toast(t('Copy to clipboard'), {
duration: 3000,
icon: '👏',
})
}}
options={{ format: 'text/plain' }}
>
<div className={styles.actionButton}>
<RxCopy size={13} />
</div>
</CopyToClipboard>
</div>
</Tooltip>
)
}
================================================
FILE: src/common/components/DurationPicker.tsx
================================================
import { useCallback, useEffect, useState } from 'react'
import NumberInput from './NumberInput'
import { Select, SelectProps } from 'baseui-sd/select'
import { useTranslation } from 'react-i18next'
type DurationUnit = 's' | 'm' | 'h'
interface IDurationPickerProps {
size?: SelectProps['size']
value?: string
onChange?: (value?: string) => void
}
export function DurationPicker({ size, value, onChange }: IDurationPickerProps) {
const [unit, setUnit] = useState<DurationUnit>()
const [duration, setDuration] = useState<number>()
useEffect(() => {
if (!value) {
setUnit('s')
setDuration(0)
return
}
const match = value.match(/(-?\d+)(s|m|h)/)
if (!match) {
setUnit('s')
setDuration(0)
return
}
const [, duration, unit] = match
setDuration(parseInt(duration, 10))
setUnit(unit as DurationUnit)
}, [value])
const handleDurationChange = useCallback(
(duration?: number) => {
if (duration === undefined) {
onChange?.(undefined)
return
}
onChange?.(`${duration}${unit}`)
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[unit]
)
const handleUnitChange = useCallback(
(unit: DurationUnit | 'forever') => {
if (unit === 'forever') {
onChange?.('-1m')
return
}
let duration_ = duration
if (duration_ !== undefined && duration_ < 0) {
duration_ = 1
}
onCh
gitextract_rd5emhhi/ ├── .eslintignore ├── .eslintrc.js ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug-report.yml │ │ ├── config.yml │ │ └── feature.yml │ ├── dependabot.yml │ └── workflows/ │ ├── lint.yaml │ ├── playwright.yml │ ├── release.yaml │ ├── test-build.yaml │ ├── unit-test.yaml │ └── winget.yml ├── .gitignore ├── .prettierrc.js ├── AGENTS.md ├── CLIP-EXTENSIONS-CN.md ├── CLIP-EXTENSIONS.md ├── LICENSE ├── Makefile ├── README-CN.md ├── README.md ├── clip-extensions/ │ ├── popclip/ │ │ ├── Config.plist │ │ └── nextai-translator.sh │ └── snipdo/ │ ├── nextai-translator.json │ └── nextai-translator.ps1 ├── docs/ │ ├── chatglm-cn.md │ ├── chatglm.md │ ├── chatgpt-cn.md │ ├── chatgpt.md │ ├── kimi-cn.md │ └── kimi.md ├── e2e/ │ ├── common.ts │ ├── fixtures.ts │ ├── hotkey.spec.ts │ ├── index.spec.ts │ ├── test.html │ └── titlebar.spec.ts ├── package.json ├── playwright.config.ts ├── scripts/ │ └── release.py ├── src/ │ ├── browser-extension/ │ │ ├── background/ │ │ │ └── index.ts │ │ ├── common.ts │ │ ├── content_script/ │ │ │ ├── InnerContainer.tsx │ │ │ ├── TitleBar.tsx │ │ │ ├── consts.ts │ │ │ ├── index.tsx │ │ │ └── utils.ts │ │ ├── enable-dev-hmr.ts │ │ ├── manifest.ts │ │ ├── options/ │ │ │ ├── index.css │ │ │ ├── index.html │ │ │ └── index.tsx │ │ └── popup/ │ │ ├── index.css │ │ ├── index.html │ │ └── index.tsx │ ├── common/ │ │ ├── __tests__/ │ │ │ └── translate.test.ts │ │ ├── analysis.ts │ │ ├── background/ │ │ │ ├── eventnames.ts │ │ │ ├── fetch.ts │ │ │ ├── local-storage.ts │ │ │ └── services/ │ │ │ ├── action.ts │ │ │ ├── base.ts │ │ │ ├── history.ts │ │ │ └── vocabulary.ts │ │ ├── components/ │ │ │ ├── ActionForm.tsx │ │ │ ├── ActionManager.tsx │ │ │ ├── CodeBlock.tsx │ │ │ ├── CopyButton.tsx │ │ │ ├── DurationPicker.tsx │ │ │ ├── ErrorFallback.tsx │ │ │ ├── Form/ │ │ │ │ ├── form.ts │ │ │ │ ├── index.module.css │ │ │ │ ├── index.ts │ │ │ │ ├── item.tsx │ │ │ │ ├── typings.ts │ │ │ │ └── validators.ts │ │ │ ├── GlobalSuspense.tsx │ │ │ ├── IconPicker.tsx │ │ │ ├── IpLocationNotification.tsx │ │ │ ├── LogoWithText.tsx │ │ │ ├── Markdown.tsx │ │ │ ├── NumberInput.tsx │ │ │ ├── ProxyTester.tsx │ │ │ ├── RenderingFormatSelector.tsx │ │ │ ├── Settings.tsx │ │ │ ├── SpeakerIcon.tsx │ │ │ ├── SpeakerMotion.tsx │ │ │ ├── SpinnerIcon.tsx │ │ │ ├── Toaster.tsx │ │ │ ├── Tooltip.tsx │ │ │ ├── TranslationHistory.tsx │ │ │ ├── Translator.tsx │ │ │ ├── Vocabulary.tsx │ │ │ └── icons/ │ │ │ ├── CerebrasIcon.tsx │ │ │ ├── ChatGLMIcon.tsx │ │ │ ├── ClaudeIcon.tsx │ │ │ ├── CohereIcon.tsx │ │ │ ├── DeepSeekIcon.tsx │ │ │ ├── GroqIcon.tsx │ │ │ ├── KimiIcon.tsx │ │ │ ├── MoonshotIcon.tsx │ │ │ └── OllamaIcon.tsx │ │ ├── constants.ts │ │ ├── engines/ │ │ │ ├── abstract-engine.ts │ │ │ ├── abstract-openai.spec.ts │ │ │ ├── abstract-openai.ts │ │ │ ├── azure.ts │ │ │ ├── cerebras.ts │ │ │ ├── chatglm.ts │ │ │ ├── chatgpt.ts │ │ │ ├── claude.ts │ │ │ ├── cohere.ts │ │ │ ├── deepseek.ts │ │ │ ├── gemini.ts │ │ │ ├── groq.ts │ │ │ ├── index.ts │ │ │ ├── interfaces.ts │ │ │ ├── kimi.ts │ │ │ ├── minimax.ts │ │ │ ├── moonshot.ts │ │ │ ├── ollama.ts │ │ │ └── openai.ts │ │ ├── geo-data.ts │ │ ├── geo.ts │ │ ├── highlight-in-textarea/ │ │ │ ├── index.css │ │ │ └── index.ts │ │ ├── hooks/ │ │ │ ├── global.ts │ │ │ ├── useCollectedWordTotal.ts │ │ │ ├── useCurrentThemeType.ts │ │ │ ├── useMemoWindow.ts │ │ │ ├── usePinned.ts │ │ │ ├── usePromotionNeverDisplay.ts │ │ │ ├── usePromotionShowed.ts │ │ │ ├── useSettings.ts │ │ │ ├── useTheme.ts │ │ │ ├── useThemeDetector.ts │ │ │ └── useThemeType.ts │ │ ├── i18n/ │ │ │ └── locales/ │ │ │ ├── en/ │ │ │ │ └── translation.json │ │ │ ├── ja/ │ │ │ │ └── translation.json │ │ │ ├── th/ │ │ │ │ └── translation.json │ │ │ ├── tr/ │ │ │ │ └── translation.json │ │ │ ├── zh-Hans/ │ │ │ │ └── translation.json │ │ │ └── zh-Hant/ │ │ │ └── translation.json │ │ ├── i18n.d.ts │ │ ├── i18n.js │ │ ├── internal-services/ │ │ │ ├── action.ts │ │ │ ├── db.ts │ │ │ ├── history.ts │ │ │ └── vocabulary.ts │ │ ├── lang/ │ │ │ ├── data.ts │ │ │ └── index.ts │ │ ├── openai-api-path.spec.ts │ │ ├── openai-api-path.ts │ │ ├── polyfills/ │ │ │ ├── electron.ts │ │ │ ├── tauri.ts │ │ │ └── userscript.ts │ │ ├── services/ │ │ │ ├── action.ts │ │ │ ├── history.ts │ │ │ ├── promotion.ts │ │ │ └── vocabulary.ts │ │ ├── store/ │ │ │ └── setting.ts │ │ ├── store.ts │ │ ├── token.ts │ │ ├── traditional-or-simplified.ts │ │ ├── translate.ts │ │ ├── tts/ │ │ │ ├── edge-tts.ts │ │ │ ├── index.ts │ │ │ └── types.ts │ │ ├── types.ts │ │ ├── universal-fetch.ts │ │ ├── usehooks.ts │ │ ├── user-event.ts │ │ └── utils.ts │ ├── index.d.ts │ └── tauri/ │ ├── App.tsx │ ├── bindings.ts │ ├── components/ │ │ └── Window.tsx │ ├── dummy.html │ ├── index.html │ ├── index.tsx │ ├── legacy-tauri-ipc.ts │ ├── utils.ts │ └── windows/ │ ├── ActionManagerWindow.tsx │ ├── HistoryWindow.tsx │ ├── ScreenshotWindow.tsx │ ├── SettingsWindow.tsx │ ├── ThumbWindow.tsx │ ├── TranslatorWindow.tsx │ └── UpdaterWindow.tsx ├── src-safari/ │ ├── .gitignore │ ├── NextAI Translator.xcodeproj/ │ │ ├── project.pbxproj │ │ └── project.xcworkspace/ │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata/ │ │ └── IDEWorkspaceChecks.plist │ ├── Shared (App)/ │ │ ├── Assets.xcassets/ │ │ │ ├── AccentColor.colorset/ │ │ │ │ └── Contents.json │ │ │ ├── AppIcon.appiconset/ │ │ │ │ └── Contents.json │ │ │ ├── Contents.json │ │ │ └── LargeIcon.imageset/ │ │ │ └── Contents.json │ │ ├── Base.lproj/ │ │ │ └── Main.html │ │ ├── Resources/ │ │ │ ├── Script.js │ │ │ └── Style.css │ │ └── ViewController.swift │ ├── Shared (Extension)/ │ │ └── SafariWebExtensionHandler.swift │ ├── iOS (App)/ │ │ ├── AppDelegate.swift │ │ ├── Base.lproj/ │ │ │ ├── LaunchScreen.storyboard │ │ │ └── Main.storyboard │ │ ├── Info.plist │ │ └── SceneDelegate.swift │ ├── iOS (Extension)/ │ │ └── Info.plist │ ├── macOS (App)/ │ │ ├── AppDelegate.swift │ │ ├── Base.lproj/ │ │ │ └── Main.storyboard │ │ ├── Info.plist │ │ └── NextAI Translator.entitlements │ └── macOS (Extension)/ │ ├── Info.plist │ └── NextAI Translator.entitlements ├── src-tauri/ │ ├── .gitignore │ ├── Cargo.toml │ ├── build.rs │ ├── capabilities/ │ │ └── migrated.json │ ├── gen/ │ │ └── schemas/ │ │ ├── acl-manifests.json │ │ ├── capabilities.json │ │ ├── desktop-schema.json │ │ ├── linux-schema.json │ │ ├── macOS-schema.json │ │ ├── plugin-manifests.json │ │ └── windows-schema.json │ ├── icons/ │ │ └── icon.icns │ ├── resources/ │ │ ├── backspace.applescript │ │ ├── bin/ │ │ │ ├── ocr_apple │ │ │ └── ocr_intel │ │ ├── copy.applescript │ │ ├── get-selected-text-by-ax.applescript │ │ ├── left.applescript │ │ ├── paste.applescript │ │ ├── right.applescript │ │ └── select-all.applescript │ ├── src/ │ │ ├── config.rs │ │ ├── fetch.rs │ │ ├── insertion.rs │ │ ├── lang.rs │ │ ├── main.rs │ │ ├── ocr.rs │ │ ├── tray.rs │ │ ├── utils.rs │ │ ├── windows.rs │ │ └── writing.rs │ └── tauri.conf.json ├── tsconfig.json ├── typos.toml ├── vite.config.chromium.ts ├── vite.config.firefox.ts ├── vite.config.tauri.ts ├── vite.config.ts └── vite.config.userscript.ts
SYMBOL INDEX (709 symbols across 130 files)
FILE: e2e/common.ts
function getOptionsPageUrl (line 3) | function getOptionsPageUrl(extensionId: string) {
function getPopupPageUrl (line 7) | function getPopupPageUrl(extensionId: string) {
function selectExampleText (line 11) | async function selectExampleText(page: Page) {
FILE: scripts/release.py
function get_current_version_from_tag (line 4) | def get_current_version_from_tag():
function generate_new_version (line 15) | def generate_new_version():
function generate_release_note (line 28) | def generate_release_note():
function create_new_tag (line 37) | def create_new_tag():
function main (line 65) | def main():
FILE: src-safari/Shared (App)/Resources/Script.js
function show (line 1) | function show(platform, enabled, useSettingsInsteadOfPreferences) {
function openPreferences (line 23) | function openPreferences() {
FILE: src-tauri/build.rs
function main (line 1) | fn main() {
FILE: src-tauri/src/config.rs
type ConfigUpdatedEvent (line 10) | pub struct ConfigUpdatedEvent;
type ProxyProtocol (line 13) | pub enum ProxyProtocol {
type BasicAuth (line 19) | pub struct BasicAuth {
type ProxyConfig (line 26) | pub struct ProxyConfig {
type Config (line 37) | pub struct Config {
function get_config (line 53) | pub fn get_config() -> Result<Config, Box<dyn std::error::Error>> {
function get_config_by_app (line 58) | pub fn get_config_by_app(app: &AppHandle) -> Result<Config, Box<dyn std:...
function _get_config_by_app (line 69) | pub fn _get_config_by_app(app: &AppHandle) -> Result<Config, Box<dyn std...
function clear_config_cache (line 81) | pub fn clear_config_cache() {
function get_config_content (line 87) | pub fn get_config_content() -> String {
function get_config_content_by_app (line 95) | pub fn get_config_content_by_app(app: &AppHandle) -> Result<String, Stri...
FILE: src-tauri/src/fetch.rs
type FetchOptions (line 17) | struct FetchOptions {
type StreamChunk (line 24) | pub(crate) struct StreamChunk {
type StreamStatusCode (line 32) | pub(crate) struct StreamStatusCode {
type AbortEventPayload (line 38) | pub(crate) struct AbortEventPayload {
function fetch_stream (line 44) | pub async fn fetch_stream(id: String, url: String, options_str: String) ...
FILE: src-tauri/src/insertion.rs
function is_translator_process (line 13) | fn is_translator_process(window: &ActiveWindow) -> bool {
function remember_active_window (line 17) | pub fn remember_active_window() {
function describe_window (line 33) | fn describe_window(window: &ActiveWindow) -> String {
function focus_window (line 41) | fn focus_window(window: &ActiveWindow) -> Result<(), String> {
function parse_hwnd (line 112) | fn parse_hwnd(window_id: &str) -> Result<windows::Win32::Foundation::HWN...
function focus_window (line 128) | fn focus_window(window: &ActiveWindow) -> Result<(), String> {
function focus_window (line 170) | fn focus_window(window: &ActiveWindow) -> Result<(), String> {
function focus_previous_window (line 214) | fn focus_previous_window() -> Result<(), String> {
function replace_input_with_text (line 232) | fn replace_input_with_text(text: &str) -> Result<(), String> {
function insert_translation_into_previous_input (line 249) | pub async fn insert_translation_into_previous_input(text: String) -> Res...
function remember_active_window_command (line 259) | pub fn remember_active_window_command() -> bool {
FILE: src-tauri/src/lang.rs
function detect_lang (line 5) | pub fn detect_lang(text: String) -> String {
FILE: src-tauri/src/main.rs
type UpdateResult (line 69) | pub struct UpdateResult {
function init_tokio_runtime (line 77) | fn init_tokio_runtime() -> &'static TokioRuntime {
function get_update_result (line 104) | fn get_update_result() -> (bool, Option<UpdateResult>) {
function query_accessibility_permissions (line 111) | fn query_accessibility_permissions() -> bool {
function query_accessibility_permissions (line 122) | fn query_accessibility_permissions() -> bool {
function launch_ipc_server (line 127) | fn launch_ipc_server(server: &Server) {
function bind_mouse_hook (line 141) | fn bind_mouse_hook() {
function main (line 317) | fn main() {
FILE: src-tauri/src/ocr.rs
function cut_image (line 11) | pub fn cut_image(left: u32, top: u32, width: u32, height: u32) {
function screenshot (line 54) | pub fn screenshot(x: i32, y: i32) {
function do_ocr (line 117) | pub fn do_ocr() -> Result<(), Box<dyn std::error::Error>> {
function do_ocr (line 122) | pub fn do_ocr() -> Result<(), Box<dyn std::error::Error>> {
function do_ocr_with_cut_file_path (line 129) | pub fn do_ocr_with_cut_file_path(image_file_path: &Path) {
function do_ocr (line 182) | pub fn do_ocr() -> Result<(), Box<dyn std::error::Error>> {
function start_ocr (line 236) | pub fn start_ocr() {
function ocr (line 240) | pub fn ocr() {
function finish_ocr (line 248) | pub fn finish_ocr() {
function do_finish_ocr (line 253) | fn do_finish_ocr() {
function do_finish_ocr (line 276) | fn do_finish_ocr() {}
function do_finish_ocr (line 279) | fn do_finish_ocr() {}
FILE: src-tauri/src/tray.rs
type PinnedFromTrayEvent (line 21) | pub struct PinnedFromTrayEvent {
type PinnedFromWindowEvent (line 26) | pub struct PinnedFromWindowEvent {
method pinned (line 31) | pub fn pinned(&self) -> &bool {
function create_tray (line 38) | pub fn create_tray<R: Runtime>(app: &tauri::AppHandle<R>) -> tauri::Resu...
FILE: src-tauri/src/utils.rs
function select_all (line 22) | pub fn select_all(enigo: &mut Enigo) {
function select_all (line 37) | pub fn select_all(_enigo: &mut Enigo) {
function left_arrow_click (line 58) | pub fn left_arrow_click(enigo: &mut Enigo, n: usize) {
function left_arrow_click (line 67) | pub fn left_arrow_click(_enigo: &mut Enigo, n: usize) {
function right_arrow_click (line 87) | pub fn right_arrow_click(enigo: &mut Enigo, n: usize) {
function right_arrow_click (line 96) | pub fn right_arrow_click(_enigo: &mut Enigo, n: usize) {
function backspace_click (line 116) | pub fn backspace_click(enigo: &mut Enigo, n: usize) {
function backspace_click (line 125) | pub fn backspace_click(_enigo: &mut Enigo, n: usize) {
function up_control_keys (line 146) | pub fn up_control_keys(enigo: &mut Enigo) {
function up_control_keys (line 156) | pub fn up_control_keys(enigo: &mut Enigo) {
function copy (line 170) | pub fn copy(enigo: &mut Enigo) {
function copy (line 185) | pub fn copy(_enigo: &mut Enigo) {
function paste (line 205) | pub fn paste(enigo: &mut Enigo) {
function paste (line 220) | pub fn paste(_enigo: &mut Enigo) {
function get_selected_text_by_clipboard (line 238) | pub fn get_selected_text_by_clipboard(
function ax_call (line 313) | unsafe fn ax_call<F, V>(f: F) -> Result<V, AXError>
function get_selected_text_frame_by_ax (line 328) | fn get_selected_text_frame_by_ax() -> Result<CGRect, Box<dyn std::error:...
function is_valid_selected_frame (line 376) | pub fn is_valid_selected_frame() -> Result<bool, Box<dyn std::error::Err...
function send_text (line 415) | pub fn send_text(text: String) {
function writing_text (line 422) | pub fn writing_text(text: String) {
function show (line 429) | pub fn show() {
FILE: src-tauri/src/windows.rs
constant TRANSLATOR_WIN_NAME (line 22) | pub const TRANSLATOR_WIN_NAME: &str = "translator";
constant SETTINGS_WIN_NAME (line 23) | pub const SETTINGS_WIN_NAME: &str = "settings";
constant ACTION_MANAGER_WIN_NAME (line 24) | pub const ACTION_MANAGER_WIN_NAME: &str = "action_manager";
constant UPDATER_WIN_NAME (line 25) | pub const UPDATER_WIN_NAME: &str = "updater";
constant THUMB_WIN_NAME (line 26) | pub const THUMB_WIN_NAME: &str = "thumb";
constant HISTORY_WIN_NAME (line 27) | pub const HISTORY_WIN_NAME: &str = "history";
constant SCREENSHOT_WIN_NAME (line 29) | pub const SCREENSHOT_WIN_NAME: &str = "screenshot";
function get_dummy_window (line 31) | fn get_dummy_window() -> tauri::WebviewWindow {
function get_current_monitor (line 53) | pub fn get_current_monitor() -> tauri::Monitor {
function get_mouse_location (line 89) | pub fn get_mouse_location() -> Result<(i32, i32), String> {
function set_translator_window_always_on_top (line 97) | pub fn set_translator_window_always_on_top() -> bool {
function get_translator_window_always_on_top (line 117) | pub fn get_translator_window_always_on_top() -> bool {
function show_translator_window_with_selected_text_command (line 123) | pub async fn show_translator_window_with_selected_text_command() {
function is_translator_foreground (line 156) | fn is_translator_foreground() -> bool {
function do_hide_translator_window (line 163) | pub fn do_hide_translator_window() {
function hide_translator_window (line 184) | pub async fn hide_translator_window() {
function delete_thumb (line 188) | pub fn delete_thumb() {
function close_thumb (line 200) | pub fn close_thumb() {
function show_thumb (line 216) | pub fn show_thumb(x: i32, y: i32) {
function get_thumb_window (line 221) | pub fn get_thumb_window(x: i32, y: i32) -> tauri::WebviewWindow {
function post_process_window (line 306) | pub fn post_process_window<R: tauri::Runtime>(window: &tauri::WebviewWin...
function build_window (line 331) | pub fn build_window<'a, R: tauri::Runtime, M: tauri::Manager<R>>(
function show_translator_window_command (line 360) | pub async fn show_translator_window_command() {
function show_translator_window (line 365) | pub fn show_translator_window(
function position_translator_window_to_cursor (line 375) | fn position_translator_window_to_cursor(window: &tauri::WebviewWindow) {
function focus_translator_window (line 422) | fn focus_translator_window(window: &tauri::WebviewWindow) {
function get_translator_window (line 447) | pub fn get_translator_window(
function show_action_manager_window (line 547) | pub async fn show_action_manager_window() {
function get_action_manager_window (line 553) | pub fn get_action_manager_window() -> tauri::WebviewWindow {
function show_history_window (line 584) | pub async fn show_history_window() {
function get_history_window (line 590) | pub fn get_history_window() -> tauri::WebviewWindow {
function show_settings_window (line 619) | pub fn show_settings_window() {
function get_settings_window (line 625) | pub fn get_settings_window() -> tauri::WebviewWindow {
type CheckUpdateResultEvent (line 655) | pub struct CheckUpdateResultEvent(UpdateResult);
type CheckUpdateEvent (line 658) | pub struct CheckUpdateEvent;
function show_updater_window (line 660) | pub fn show_updater_window() {
function get_updater_window (line 699) | pub fn get_updater_window() -> tauri::WebviewWindow {
function show_screenshot_window (line 729) | pub fn show_screenshot_window() {
function get_screenshot_window (line 735) | pub fn get_screenshot_window() -> tauri::WebviewWindow {
FILE: src-tauri/src/writing.rs
function get_input_text (line 11) | pub fn get_input_text(
type IncrementalAction (line 28) | struct IncrementalAction {
type WritingGuard (line 36) | struct WritingGuard {
method new (line 41) | fn new() -> Option<Self> {
method commit (line 50) | fn commit(&mut self) {
method drop (line 56) | fn drop(&mut self) {
function writing_command (line 66) | pub fn writing_command() {
function do_incremental_writing (line 269) | fn do_incremental_writing(incremental_action: &IncrementalAction) {
function do_write_to_input (line 294) | fn do_write_to_input(enigo: &mut Enigo, text: String, animation: bool) {
function write_to_input (line 366) | pub fn write_to_input(text: String) {
function finish_writing (line 411) | pub fn finish_writing() {
FILE: src/browser-extension/background/index.ts
function fetchWithStream (line 35) | async function fetchWithStream(
function callMethod (line 122) | async function callMethod(request: any, service: any): Promise<any> {
FILE: src/browser-extension/content_script/InnerContainer.tsx
type Props (line 17) | type Props = {
function InnerContainer (line 38) | function InnerContainer({ children, reference }: Props) {
FILE: src/browser-extension/content_script/TitleBar.tsx
type TitleBarProps (line 37) | type TitleBarProps = {
function TitleBar (line 43) | function TitleBar({ pinned = false, onClose, engine }: TitleBarProps) {
FILE: src/browser-extension/content_script/index.tsx
function popupThumbClickHandler (line 27) | async function popupThumbClickHandler(event: UserEventType) {
function removeContainer (line 37) | async function removeContainer() {
function hidePopupThumb (line 42) | async function hidePopupThumb() {
function hidePopupCard (line 50) | async function hidePopupCard() {
function createPopupCard (line 63) | async function createPopupCard() {
function showPopupCard (line 86) | async function showPopupCard(reference: ReferenceElement, text: string, ...
function showPopupThumb (line 135) | async function showPopupThumb(text: string, x: number, y: number) {
function main (line 182) | async function main() {
function bindHotKey (line 248) | async function bindHotKey(hotkey_: string | undefined) {
FILE: src/browser-extension/content_script/utils.ts
function attachEventsToContainer (line 3) | function attachEventsToContainer($container: HTMLElement) {
function getContainer (line 18) | async function getContainer(): Promise<HTMLElement> {
function queryPopupThumbElement (line 54) | async function queryPopupThumbElement(): Promise<HTMLDivElement | null> {
function queryPopupCardElement (line 59) | async function queryPopupCardElement(): Promise<HTMLDivElement | null> {
function calculateMaxXY (line 64) | function calculateMaxXY($popupCard: HTMLElement): number[] {
FILE: src/browser-extension/manifest.ts
function getManifest (line 4) | function getManifest(browser: 'firefox' | 'chromium') {
FILE: src/browser-extension/popup/index.tsx
function App (line 16) | function App() {
FILE: src/common/analysis.ts
function setupAnalysis (line 5) | async function setupAnalysis() {
function doSetupAnalysis (line 14) | async function doSetupAnalysis() {
FILE: src/common/background/eventnames.ts
type BackgroundVocabularyServiceMethodNames (line 14) | type BackgroundVocabularyServiceMethodNames = keyof IVocabularyInternalS...
type BackgroundHistoryServiceMethodNames (line 15) | type BackgroundHistoryServiceMethodNames = keyof IHistoryInternalService
FILE: src/common/background/fetch.ts
type BackgroundFetchRequestMessage (line 5) | interface BackgroundFetchRequestMessage {
type BackgroundFetchResponseMessage (line 10) | interface BackgroundFetchResponseMessage
function readText (line 17) | async function readText(stream: ReadableStream) {
function backgroundFetch (line 32) | async function backgroundFetch(input: string, options: RequestInit) {
FILE: src/common/background/local-storage.ts
function backgroundGetItem (line 5) | async function backgroundGetItem(key: string): Promise<string | null> {
function backgroundSetItem (line 14) | async function backgroundSetItem(key: string, value: string | null): Pro...
function backgroundRemoveItem (line 24) | async function backgroundRemoveItem(key: string): Promise<void> {
FILE: src/common/background/services/action.ts
class BackgroundActionService (line 5) | class BackgroundActionService implements IActionInternalService {
method create (line 6) | create(opt: ICreateActionOption): Promise<Action> {
method update (line 9) | update(action: Action, opt: IUpdateActionOption): Promise<Action> {
method bulkPut (line 12) | bulkPut(actions: Action[]): Promise<void> {
method get (line 15) | get(id: number): Promise<Action | undefined> {
method getByMode (line 18) | getByMode(mode: string): Promise<Action | undefined> {
method delete (line 21) | delete(id: number): Promise<void> {
method list (line 24) | list(): Promise<Action[]> {
method count (line 27) | count(): Promise<number> {
FILE: src/common/background/services/base.ts
function callMethod (line 3) | async function callMethod(
FILE: src/common/background/services/history.ts
class BackgroundHistoryService (line 10) | class BackgroundHistoryService implements IHistoryInternalService {
method create (line 11) | create(item: CreateHistoryItem): Promise<HistoryItem> {
method update (line 14) | update(id: number, payload: UpdateHistoryPayload): Promise<void> {
method updateFavorite (line 17) | updateFavorite(id: number, favorite: boolean): Promise<void> {
method touch (line 20) | touch(id: number): Promise<void> {
method delete (line 23) | delete(id: number): Promise<void> {
method clear (line 26) | clear(): Promise<void> {
method list (line 29) | list(options?: HistoryQueryOptions | undefined): Promise<HistoryItem[]> {
method get (line 32) | get(id: number): Promise<HistoryItem | undefined> {
FILE: src/common/background/services/vocabulary.ts
class BackgroundVocabularyService (line 5) | class BackgroundVocabularyService implements IVocabularyInternalService {
method putItem (line 6) | async putItem(item: VocabularyItem): Promise<void> {
method getItem (line 10) | async getItem(word: string): Promise<VocabularyItem | undefined> {
method deleteItem (line 14) | async deleteItem(word: string): Promise<void> {
method countItems (line 18) | async countItems(): Promise<number> {
method listItems (line 22) | async listItems(): Promise<VocabularyItem[]> {
method listRandomItems (line 26) | async listRandomItems(limit: number): Promise<VocabularyItem[]> {
method listFrequencyItems (line 30) | async listFrequencyItems(limit: number): Promise<VocabularyItem[]> {
method isCollected (line 34) | async isCollected(word: string): Promise<boolean> {
FILE: src/common/components/ActionForm.tsx
type IActionFormProps (line 37) | interface IActionFormProps {
function ActionForm (line 44) | function ActionForm(props: IActionFormProps) {
FILE: src/common/components/ActionManager.tsx
type IActionManagerProps (line 145) | interface IActionManagerProps {
function ActionManager (line 149) | function ActionManager({ draggable = true }: IActionManagerProps) {
FILE: src/common/components/CodeBlock.tsx
type ICodeBlockProps (line 17) | interface ICodeBlockProps {
function CodeBlock (line 22) | function CodeBlock({ code, language }: ICodeBlockProps) {
FILE: src/common/components/CopyButton.tsx
function CopyButton (line 7) | function CopyButton({ text, styles }: { text: string; styles: { actionBu...
FILE: src/common/components/DurationPicker.tsx
type DurationUnit (line 6) | type DurationUnit = 's' | 'm' | 'h'
type IDurationPickerProps (line 8) | interface IDurationPickerProps {
function DurationPicker (line 14) | function DurationPicker({ size, value, onChange }: IDurationPickerProps) {
FILE: src/common/components/ErrorFallback.tsx
function ErrorFallback (line 3) | function ErrorFallback({ error, resetErrorBoundary }: { error: Error; re...
FILE: src/common/components/Form/form.ts
type FormInstance (line 16) | type FormInstance<S extends {} = Store, K extends keyof S = keyof S> = {
type FormProps (line 34) | interface FormProps<S extends {} = Store, V = S>
type OmittedRcFieldProps (line 44) | type OmittedRcFieldProps = Omit<RcFieldProps, 'name' | 'dependencies' | ...
type BasicFormItemProps (line 46) | interface BasicFormItemProps<S extends {} = Store> extends OmittedRcFiel...
type Deps (line 58) | type Deps<S> = Array<NamePath<S>>
type FormItemPropsDeps (line 59) | type FormItemPropsDeps<S extends {} = Store> =
type FormItemProps (line 74) | type FormItemProps<S extends {} = Store> = BasicFormItemProps<S> & FormI...
type FormItemClassName (line 76) | interface FormItemClassName {
type Rule (line 85) | type Rule = NonNullable<RcFieldProps['rules']>[number]
function createShouldUpdate (line 90) | function createShouldUpdate(
function createForm (line 114) | function createForm<S extends {} = Store>({
FILE: src/common/components/Form/item.tsx
type IFormItemProps (line 6) | interface IFormItemProps extends FieldProps {
FILE: src/common/components/Form/typings.ts
type Cons (line 5) | type Cons<H, T> = T extends readonly any[]
type Prev (line 11) | type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15...
type Paths (line 14) | type Paths<T, D extends number = 10> = [D] extends [never]
type NextInt (line 22) | interface NextInt {
type PathType (line 31) | type PathType<T, P extends any[], Index extends keyof P & number = 0> = {
type NamePath (line 41) | type NamePath<T, D extends number = 4> = keyof T | Paths<T, D>
type Control (line 43) | interface Control<T = any> {
FILE: src/common/components/Form/validators.ts
type Validator (line 4) | type Validator = (rule: any, value: any) => Promise<void>
FILE: src/common/components/GlobalSuspense.tsx
function GlobalSuspense (line 3) | function GlobalSuspense({ children }: { children: React.ReactNode }) {
FILE: src/common/components/IconPicker.tsx
type IIconPickerProps (line 27) | interface IIconPickerProps {
function IconPicker (line 32) | function IconPicker({ value, onChange }: IIconPickerProps) {
FILE: src/common/components/IpLocationNotification.tsx
function IpLocationNotification (line 8) | function IpLocationNotification(props: { showSettings: boolean }) {
FILE: src/common/components/LogoWithText.tsx
type LogoWithTextRef (line 34) | type LogoWithTextRef = {
method hideText (line 49) | hideText() {
method showText (line 54) | showText() {
FILE: src/common/components/Markdown.tsx
type IMarkdownProps (line 6) | interface IMarkdownProps {
function Markdown (line 11) | function Markdown({ children, linkTarget }: IMarkdownProps) {
FILE: src/common/components/NumberInput.tsx
type INumberInputProps (line 4) | interface INumberInputProps {
function NumberInput (line 19) | function NumberInput({
FILE: src/common/components/ProxyTester.tsx
type IProxyTesterProps (line 12) | interface IProxyTesterProps {
function ProxyTester (line 16) | function ProxyTester(props: IProxyTesterProps) {
FILE: src/common/components/RenderingFormatSelector.tsx
type IRenderingFormatSelector (line 4) | interface IRenderingFormatSelector extends Omit<SelectProps, 'value' | '...
function RenderingFormatSelector (line 9) | function RenderingFormatSelector({ value, onChange, ...props }: IRenderi...
FILE: src/common/components/Settings.tsx
type ILanguageSelectorProps (line 86) | interface ILanguageSelectorProps {
function LanguageSelector (line 99) | function LanguageSelector({ value, onChange, onBlur }: ILanguageSelector...
type ITranslateModeSelectorProps (line 115) | interface ITranslateModeSelectorProps {
function TranslateModeSelector (line 121) | function TranslateModeSelector({ value, onChange, onBlur }: ITranslateMo...
type IThemeTypeSelectorProps (line 157) | interface IThemeTypeSelectorProps {
function ThemeTypeSelector (line 163) | function ThemeTypeSelector({ value, onChange, onBlur }: IThemeTypeSelect...
type ILanguageDetectionEngineSelectorProps (line 193) | interface ILanguageDetectionEngineSelectorProps {
function LanguageDetectionEngineSelector (line 199) | function LanguageDetectionEngineSelector({ value, onChange, onBlur }: IL...
type ISpeakerButtonProps (line 256) | interface ISpeakerButtonProps extends ButtonProps {
function SpeakerButton (line 266) | function SpeakerButton({
type ITTSVoicesSettingsProps (line 303) | interface ITTSVoicesSettingsProps {
function TTSVoicesSettings (line 317) | function TTSVoicesSettings({ value, onChange, onBlur }: ITTSVoicesSettin...
type IProxyProtocolProps (line 678) | interface IProxyProtocolProps {
function ProxyProtocolSelector (line 684) | function ProxyProtocolSelector({ value, onChange, onBlur }: IProxyProtoc...
type Ii18nSelectorProps (line 714) | interface Ii18nSelectorProps {
function Ii18nSelector (line 720) | function Ii18nSelector({ value, onChange, onBlur }: Ii18nSelectorProps) {
type APIModelSelectorProps (line 758) | interface APIModelSelectorProps {
type APIModelOption (line 767) | interface APIModelOption {
function APIModelSelector (line 772) | function APIModelSelector({ currentProvider, provider, apiKey, value, on...
type AutoTranslateCheckboxProps (line 942) | interface AutoTranslateCheckboxProps {
function AutoTranslateCheckbox (line 948) | function AutoTranslateCheckbox({ value, onChange, onBlur }: AutoTranslat...
type MyCheckboxProps (line 961) | interface MyCheckboxProps {
function MyCheckbox (line 967) | function MyCheckbox({ value, onChange, onBlur }: MyCheckboxProps) {
type RestorePreviousPositionCheckboxProps (line 980) | interface RestorePreviousPositionCheckboxProps {
function RestorePreviousPositionCheckbox (line 986) | function RestorePreviousPositionCheckbox({ value, onChange, onBlur }: Re...
type SelectInputElementsProps (line 998) | interface SelectInputElementsProps {
function SelectInputElementsCheckbox (line 1004) | function SelectInputElementsCheckbox({ value, onChange, onBlur }: Select...
type ReadSelectedWordsFromInputElementsProps (line 1017) | interface ReadSelectedWordsFromInputElementsProps {
function ReadSelectedWordsFromInputElementsCheckbox (line 1023) | function ReadSelectedWordsFromInputElementsCheckbox({
type RunAtStartupCheckboxProps (line 1040) | interface RunAtStartupCheckboxProps {
function RunAtStartupCheckbox (line 1046) | function RunAtStartupCheckbox({ value, onChange, onBlur }: RunAtStartupC...
type IHotkeyRecorderProps (line 1166) | interface IHotkeyRecorderProps {
function HotkeyRecorder (line 1173) | function HotkeyRecorder({ value, onChange, onBlur, testId }: IHotkeyReco...
type IAddProviderIconsProps (line 1264) | interface IAddProviderIconsProps {
type IProviderSelectorProps (line 1327) | interface IProviderSelectorProps {
function ProviderSelector (line 1333) | function ProviderSelector({ value, onChange, hasPromotion }: IProviderSe...
type IInnerSettingsProps (line 1415) | interface IInnerSettingsProps {
type ISettingsProps (line 1422) | interface ISettingsProps extends IInnerSettingsProps {
function Settings (line 1426) | function Settings({ engine, ...props }: ISettingsProps) {
function InnerSettings (line 1439) | function InnerSettings({
FILE: src/common/components/SpeakerIcon.tsx
type ISpeakerIconProps (line 10) | interface ISpeakerIconProps extends IconBaseProps {
function SpeakerIcon (line 20) | function SpeakerIcon({
FILE: src/common/components/SpeakerMotion.tsx
function SpeakerMotion (line 60) | function SpeakerMotion({ style, ...props }: IconBaseProps) {
FILE: src/common/components/SpinnerIcon.tsx
type ISpinnerIconProps (line 22) | interface ISpinnerIconProps extends IconBaseProps {}
function SpinnerIcon (line 24) | function SpinnerIcon(props: ISpinnerIconProps) {
FILE: src/common/components/Toaster.tsx
function Toaster (line 76) | function Toaster() {
FILE: src/common/components/Tooltip.tsx
type ITooltipProps (line 3) | interface ITooltipProps extends StatefulTooltipProps {
FILE: src/common/components/TranslationHistory.tsx
type TranslationHistoryProps (line 22) | interface TranslationHistoryProps {
constant ALL_ACTIONS_OPTION_ID (line 131) | const ALL_ACTIONS_OPTION_ID = '__all__'
function useActionOptions (line 133) | function useActionOptions(actions: Action[], t: (key: string) => string)...
function TranslationHistory (line 150) | function TranslationHistory(props: TranslationHistoryProps) {
FILE: src/common/components/Translator.tsx
function genLangOptions (line 106) | function genLangOptions(langs: [LangCode, string][]): Value {
type IActionStrItem (line 439) | interface IActionStrItem {
type TesseractResult (line 471) | interface TesseractResult extends RecognizeResult {
type MovementXY (line 475) | interface MovementXY {
type IInnerTranslatorProps (line 480) | interface IInnerTranslatorProps {
type ITranslatorProps (line 494) | interface ITranslatorProps extends IInnerTranslatorProps {
function Translator (line 498) | function Translator(props: ITranslatorProps) {
function InnerTranslator (line 516) | function InnerTranslator(props: IInnerTranslatorProps) {
FILE: src/common/components/Vocabulary.tsx
constant RANDOM_SIZE (line 29) | const RANDOM_SIZE = 10
constant MAX_WORDS (line 30) | const MAX_WORDS = 50
type IVocabularyProps (line 154) | interface IVocabularyProps {
FILE: src/common/components/icons/CerebrasIcon.tsx
function CerebrasIcon (line 13) | function CerebrasIcon(props: IconBaseProps) {
FILE: src/common/components/icons/ChatGLMIcon.tsx
function ChatGLMIcon (line 13) | function ChatGLMIcon(props: IconBaseProps) {
FILE: src/common/components/icons/ClaudeIcon.tsx
function ClaudeIcon (line 18) | function ClaudeIcon(props: IconBaseProps) {
FILE: src/common/components/icons/CohereIcon.tsx
function CohereIcon (line 13) | function CohereIcon(props: IconBaseProps) {
FILE: src/common/components/icons/DeepSeekIcon.tsx
function DeepSeekIcon (line 13) | function DeepSeekIcon(props: IconBaseProps) {
FILE: src/common/components/icons/GroqIcon.tsx
function GroqIcon (line 13) | function GroqIcon(props: IconBaseProps) {
FILE: src/common/components/icons/KimiIcon.tsx
function KimiIcon (line 13) | function KimiIcon(props: IconBaseProps) {
FILE: src/common/components/icons/MoonshotIcon.tsx
function MoonshotIcon (line 6) | function MoonshotIcon(props: IconBaseProps) {
FILE: src/common/components/icons/OllamaIcon.tsx
function OllamaIcon (line 13) | function OllamaIcon(props: IconBaseProps) {
FILE: src/common/constants.ts
constant CUSTOM_MODEL_ID (line 3) | const CUSTOM_MODEL_ID = '__custom__'
constant PREFIX (line 4) | const PREFIX = '__yetone-nextai-translator'
FILE: src/common/engines/abstract-engine.ts
method checkLogin (line 4) | async checkLogin(): Promise<boolean> {
method isLocal (line 7) | isLocal() {
method supportCustomModel (line 10) | supportCustomModel() {
FILE: src/common/engines/abstract-openai.spec.ts
class TestOpenAIEngine (line 15) | class TestOpenAIEngine extends AbstractOpenAI {
method constructor (line 16) | constructor(
method getAPIModel (line 24) | async getAPIModel(): Promise<string> {
method getAPIKey (line 28) | async getAPIKey(): Promise<string> {
method getAPIURL (line 32) | async getAPIURL(): Promise<string> {
method getAPIURLPath (line 36) | async getAPIURLPath(): Promise<string> {
type MockFetchSSEOptions (line 41) | interface MockFetchSSEOptions {
function createMessageRequest (line 46) | function createMessageRequest() {
FILE: src/common/engines/abstract-openai.ts
method isResponsesAPIPath (line 10) | private isResponsesAPIPath(apiURLPath: string): boolean {
method shouldUseResponsesAPI (line 14) | private shouldUseResponsesAPI(apiURL: string, apiURLPath: string, model:...
method extractResponseOutputText (line 29) | private extractResponseOutputText(resp: any): string {
method listModels (line 51) | async listModels(apiKey: string | undefined): Promise<IModel[]> {
method getModel (line 112) | async getModel() {
method getHeaders (line 121) | async getHeaders(): Promise<Record<string, string>> {
method isChatAPI (line 131) | async isChatAPI(): Promise<boolean> {
method getBaseRequestBody (line 136) | async getBaseRequestBody(): Promise<Record<string, any>> {
method sendMessage (line 166) | async sendMessage(req: IMessageRequest): Promise<void> {
FILE: src/common/engines/azure.ts
class Azure (line 6) | class Azure extends AbstractOpenAI {
method listModels (line 8) | async listModels(apiKey_: string | undefined): Promise<IModel[]> {
method isChatAPI (line 31) | async isChatAPI(): Promise<boolean> {
method getAPIModel (line 36) | async getAPIModel(): Promise<string> {
method getAPIKey (line 41) | async getAPIKey(): Promise<string> {
method getHeaders (line 48) | async getHeaders(): Promise<Record<string, string>> {
method getBaseRequestBody (line 57) | async getBaseRequestBody(): Promise<Record<string, any>> {
method getAPIURL (line 66) | async getAPIURL(): Promise<string> {
method getAPIURLPath (line 71) | async getAPIURLPath(): Promise<string> {
FILE: src/common/engines/cerebras.ts
class Cerebras (line 7) | class Cerebras extends AbstractEngine {
method listModels (line 9) | async listModels(apiKey: string | undefined): Promise<IModel[]> {
method getModel (line 38) | async getModel(): Promise<string> {
method sendMessage (line 43) | async sendMessage(req: IMessageRequest): Promise<void> {
FILE: src/common/engines/chatglm.ts
class ChatGLM (line 11) | class ChatGLM extends AbstractEngine {
method getModel (line 12) | async getModel(): Promise<string> {
method listModels (line 17) | async listModels(_apiKey: string | undefined): Promise<IModel[]> {
method getHeaders (line 21) | async getHeaders() {
method refreshAccessToken (line 41) | async refreshAccessToken(onStatusCode: ((statusCode: number) => void) ...
method sendMessage (line 69) | async sendMessage(req: IMessageRequest): Promise<void> {
FILE: src/common/engines/chatgpt.ts
function getArkoseToken (line 16) | async function getArkoseToken() {
function callBackendAPIWithToken (line 50) | async function callBackendAPIWithToken(token: string, method: string, en...
function getChatRequirements (line 63) | async function getChatRequirements(accessToken: string) {
function GenerateProofToken (line 70) | async function GenerateProofToken(seed: string, diff: string | number | ...
class ChatGPT (line 102) | class ChatGPT extends AbstractEngine {
method listModels (line 104) | async listModels(apiKey_: string | undefined): Promise<IModel[]> {
method getModel (line 158) | async getModel(): Promise<string> {
method sendMessage (line 163) | async sendMessage(req: IMessageRequest): Promise<void> {
FILE: src/common/engines/claude.ts
class Claude (line 8) | class Claude extends AbstractEngine {
method supportCustomModel (line 9) | supportCustomModel(): boolean {
method getModel (line 13) | async getModel(): Promise<string> {
method listModels (line 22) | async listModels(apiKey_: string | undefined): Promise<IModel[]> {
method sendMessage (line 39) | async sendMessage(req: IMessageRequest): Promise<void> {
FILE: src/common/engines/cohere.ts
class Cohere (line 7) | class Cohere extends AbstractEngine {
method listModels (line 9) | async listModels(apiKey: string | undefined): Promise<IModel[]> {
method getModel (line 42) | async getModel() {
method sendMessage (line 47) | async sendMessage(req: IMessageRequest): Promise<void> {
FILE: src/common/engines/deepseek.ts
class DeepSeek (line 6) | class DeepSeek extends AbstractOpenAI {
method listModels (line 7) | async listModels(apiKey_: string | undefined): Promise<IModel[]> {
method getAPIModel (line 46) | async getAPIModel(): Promise<string> {
method getAPIKey (line 50) | async getAPIKey(): Promise<string> {
method getAPIURL (line 54) | async getAPIURL(): Promise<string> {
method getAPIURLPath (line 57) | async getAPIURLPath(): Promise<string> {
FILE: src/common/engines/gemini.ts
constant SAFETY_SETTINGS (line 9) | const SAFETY_SETTINGS = [
class Gemini (line 28) | class Gemini extends AbstractEngine {
method listModels (line 30) | async listModels(apiKey: string | undefined): Promise<IModel[]> {
method getModel (line 60) | async getModel() {
method sendMessage (line 65) | async sendMessage(req: IMessageRequest): Promise<void> {
FILE: src/common/engines/groq.ts
class Groq (line 8) | class Groq extends AbstractOpenAI {
method supportCustomModel (line 9) | supportCustomModel(): boolean {
method listModels (line 14) | async listModels(apiKey: string | undefined): Promise<IModel[]> {
method getAPIModel (line 38) | async getAPIModel(): Promise<string> {
method getAPIKey (line 46) | async getAPIKey(): Promise<string> {
method getAPIURL (line 51) | async getAPIURL(): Promise<string> {
method getAPIURLPath (line 56) | async getAPIURLPath(): Promise<string> {
FILE: src/common/engines/index.ts
type Provider (line 31) | type Provider =
function getEngine (line 81) | function getEngine(provider: Provider): IEngine {
FILE: src/common/engines/interfaces.ts
type IModel (line 1) | interface IModel {
type IMessage (line 7) | interface IMessage {
type IMessageRequest (line 12) | interface IMessageRequest {
type IEngine (line 22) | interface IEngine {
FILE: src/common/engines/kimi.ts
class Kimi (line 10) | class Kimi extends AbstractEngine {
method checkLogin (line 11) | async checkLogin(): Promise<boolean> {
method getModel (line 24) | async getModel(): Promise<string> {
method listModels (line 29) | async listModels(_apiKey: string | undefined): Promise<IModel[]> {
method getHeaders (line 33) | async getHeaders() {
method sendMessage (line 57) | async sendMessage(req: IMessageRequest): Promise<void> {
FILE: src/common/engines/minimax.ts
class MiniMax (line 5) | class MiniMax extends AbstractOpenAI {
method listModels (line 7) | async listModels(_apiKey: string | undefined): Promise<IModel[]> {
method getAPIModel (line 14) | async getAPIModel(): Promise<string> {
method getAPIKey (line 18) | async getAPIKey(): Promise<string> {
method getAPIURL (line 22) | async getAPIURL(): Promise<string> {
method getAPIURLPath (line 25) | async getAPIURLPath(): Promise<string> {
FILE: src/common/engines/moonshot.ts
class Moonshot (line 6) | class Moonshot extends AbstractOpenAI {
method listModels (line 7) | async listModels(apiKey_: string | undefined): Promise<IModel[]> {
method getAPIModel (line 46) | async getAPIModel(): Promise<string> {
method getAPIKey (line 50) | async getAPIKey(): Promise<string> {
method getAPIURL (line 54) | async getAPIURL(): Promise<string> {
method getAPIURLPath (line 57) | async getAPIURLPath(): Promise<string> {
FILE: src/common/engines/ollama.ts
class Ollama (line 6) | class Ollama extends AbstractOpenAI {
method supportCustomModel (line 7) | supportCustomModel(): boolean {
method isLocal (line 11) | isLocal() {
method listModels (line 16) | async listModels(apiKey_: string | undefined): Promise<IModel[]> {
method getBaseRequestBody (line 37) | async getBaseRequestBody(): Promise<Record<string, any>> {
method getAPIModel (line 47) | async getAPIModel(): Promise<string> {
method getAPIKey (line 55) | async getAPIKey(): Promise<string> {
method getAPIURL (line 59) | async getAPIURL(): Promise<string> {
method getAPIURLPath (line 64) | async getAPIURLPath(): Promise<string> {
FILE: src/common/engines/openai.ts
class OpenAI (line 6) | class OpenAI extends AbstractOpenAI {
method supportCustomModel (line 7) | supportCustomModel(): boolean {
method getAPIModel (line 11) | async getAPIModel(): Promise<string> {
method getAPIKey (line 19) | async getAPIKey(): Promise<string> {
method getAPIURL (line 26) | async getAPIURL(): Promise<string> {
method getAPIURLPath (line 31) | async getAPIURLPath(): Promise<string> {
FILE: src/common/geo-data.ts
constant ALLOWED_COUNTRY_CODES (line 1) | const ALLOWED_COUNTRY_CODES = new Set([
FILE: src/common/geo.ts
type IpLocation (line 4) | interface IpLocation {
type OpenAICDNCGITraceResponse (line 9) | interface OpenAICDNCGITraceResponse {
function parseResponse (line 28) | function parseResponse(response: string): OpenAICDNCGITraceResponse {
function getIpLocationInfo (line 42) | async function getIpLocationInfo(): Promise<IpLocation> {
FILE: src/common/highlight-in-textarea/index.ts
type IConfig (line 4) | interface IConfig {
class HighlightInTextarea (line 8) | class HighlightInTextarea {
method constructor (line 17) | constructor(el: HTMLTextAreaElement, config: IConfig) {
method generate (line 30) | generate() {
method detectBrowser (line 76) | detectBrowser() {
method fixFirefox (line 93) | fixFirefox() {
method fixIOS (line 138) | fixIOS() {
method handleInput (line 150) | public handleInput() {
method getType (line 165) | getType(instance: any) {
method getRanges (line 190) | getRanges(input: string | undefined, highlight: IConfig['highlight'] |...
method getArrayRanges (line 215) | getArrayRanges(input: string | undefined, arr: any) {
method getFunctionRanges (line 220) | getFunctionRanges(input: any, func: any) {
method getRegExpRanges (line 224) | getRegExpRanges(input: any, regex: any) {
method getStringRanges (line 238) | getStringRanges(input: any, str: any) {
method getRangeRanges (line 255) | getRangeRanges(_input: any, range: any) {
method getCustomRanges (line 259) | getCustomRanges(input: any, custom: any) {
method removeStaggeredRanges (line 275) | removeStaggeredRanges(ranges: any) {
method getBoundaries (line 290) | getBoundaries(ranges: any) {
method sortBoundaries (line 308) | sortBoundaries(boundaries: any) {
method renderMarks (line 323) | renderMarks(boundaries: any) {
method handleScroll (line 369) | handleScroll() {
method blockContainerScroll (line 390) | blockContainerScroll() {
method destroy (line 397) | destroy() {
method hasActiveHighlight (line 405) | private hasActiveHighlight(): boolean {
FILE: src/common/hooks/useCollectedWordTotal.ts
function useCollectedWordTotal (line 5) | function useCollectedWordTotal() {
FILE: src/common/hooks/useMemoWindow.ts
constant POSITION_KEY_SUFFIX (line 7) | const POSITION_KEY_SUFFIX = '_position'
constant SIZE_KEY_SUFFIX (line 8) | const SIZE_KEY_SUFFIX = '_size'
type WindowMemoProps (line 10) | type WindowMemoProps = {
FILE: src/common/hooks/usePinned.ts
function usePinned (line 6) | function usePinned() {
FILE: src/common/hooks/usePromotionNeverDisplay.ts
function usePromotionNeverDisplay (line 10) | function usePromotionNeverDisplay(item?: IPromotionItem) {
FILE: src/common/hooks/usePromotionShowed.ts
function usePromotionShowed (line 10) | function usePromotionShowed(item?: IPromotionItem) {
FILE: src/common/hooks/useSettings.ts
function useSettings (line 7) | function useSettings(): {
FILE: src/common/internal-services/action.ts
type ICreateActionOption (line 5) | interface ICreateActionOption {
type IUpdateActionOption (line 14) | interface IUpdateActionOption {
type IActionInternalService (line 24) | interface IActionInternalService {
class ActionInternalService (line 35) | class ActionInternalService implements IActionInternalService {
method db (line 36) | private get db() {
method create (line 40) | async create(opt: ICreateActionOption): Promise<Action> {
method update (line 63) | async update(action: Action, opt: IUpdateActionOption): Promise<Action> {
method bulkPut (line 87) | async bulkPut(actions: Action[]): Promise<void> {
method get (line 91) | async get(id: number): Promise<Action | undefined> {
method getByMode (line 95) | async getByMode(mode: string): Promise<Action | undefined> {
method delete (line 99) | async delete(id: number): Promise<void> {
method list (line 115) | async list(): Promise<Action[]> {
method count (line 140) | async count(): Promise<number> {
FILE: src/common/internal-services/db.ts
type VocabularyItem (line 5) | interface VocabularyItem {
type ActionOutputRenderingFormat (line 14) | type ActionOutputRenderingFormat = 'text' | 'markdown' | 'latex'
type Action (line 16) | interface Action {
type HistoryItem (line 29) | interface HistoryItem {
class LocalDB (line 47) | class LocalDB extends Dexie {
method constructor (line 52) | constructor() {
FILE: src/common/internal-services/history.ts
type CreateHistoryItem (line 5) | interface CreateHistoryItem {
type UpdateHistoryPayload (line 20) | interface UpdateHistoryPayload {
type HistoryQueryOptions (line 25) | interface HistoryQueryOptions {
type IHistoryInternalService (line 35) | interface IHistoryInternalService {
class HistoryInternalService (line 46) | class HistoryInternalService implements IHistoryInternalService {
method db (line 47) | private get db() {
method create (line 51) | async create(item: CreateHistoryItem): Promise<HistoryItem> {
method update (line 64) | async update(id: number, payload: UpdateHistoryPayload): Promise<void> {
method updateFavorite (line 71) | async updateFavorite(id: number, favorite: boolean): Promise<void> {
method touch (line 78) | async touch(id: number): Promise<void> {
method delete (line 84) | async delete(id: number): Promise<void> {
method clear (line 88) | async clear(): Promise<void> {
method get (line 92) | async get(id: number): Promise<HistoryItem | undefined> {
method list (line 96) | async list(options: HistoryQueryOptions = {}): Promise<HistoryItem[]> {
FILE: src/common/internal-services/vocabulary.ts
type IVocabularyInternalService (line 3) | interface IVocabularyInternalService {
class VocabularyInternalService (line 14) | class VocabularyInternalService implements IVocabularyInternalService {
method db (line 15) | private get db() {
method putItem (line 19) | public async putItem(item: VocabularyItem): Promise<void> {
method getItem (line 23) | public async getItem(word: string): Promise<VocabularyItem | undefined> {
method deleteItem (line 27) | public async deleteItem(word: string): Promise<void> {
method listFrequencyItems (line 31) | public async listFrequencyItems(limit: number): Promise<VocabularyItem...
method countItems (line 36) | public async countItems(): Promise<number> {
method isCollected (line 40) | public async isCollected(word: string): Promise<boolean> {
method listItems (line 45) | public async listItems(): Promise<VocabularyItem[]> {
method listRandomItems (line 49) | public async listRandomItems(limit: number): Promise<VocabularyItem[]> {
FILE: src/common/lang/data.ts
type Config (line 3) | interface Config {
constant LANG_CONFIGS (line 26) | const LANG_CONFIGS: Record<LangCode, Config> = {
FILE: src/common/lang/index.ts
type LangCode (line 12) | type LangCode =
type LanguageConfig (line 84) | type LanguageConfig = Required<OptionalLangConfig>
function getLangName (line 97) | function getLangName(langCode: string): string {
function googleDetectLang (line 102) | async function googleDetectLang(text: string): Promise<LangCode> {
function bingDetectLang (line 156) | async function bingDetectLang(text: string): Promise<LangCode> {
function baiduDetectLang (line 208) | async function baiduDetectLang(text: string): Promise<LangCode> {
function localDetectLang (line 248) | async function localDetectLang(text: string): Promise<LangCode> {
function detectLang (line 342) | async function detectLang(text: string): Promise<LangCode> {
function getLangConfig (line 362) | function getLangConfig(langCode: LangCode): LanguageConfig {
function intoLangCode (line 379) | function intoLangCode(langCode: string | null): LangCode {
FILE: src/common/openai-api-path.ts
constant OPENAI_CHAT_COMPLETIONS_API_PATH (line 1) | const OPENAI_CHAT_COMPLETIONS_API_PATH = '/v1/chat/completions'
constant OPENAI_RESPONSES_API_PATH (line 2) | const OPENAI_RESPONSES_API_PATH = '/v1/responses'
constant OPENAI_PREFERRED_DEFAULT_MODEL (line 3) | const OPENAI_PREFERRED_DEFAULT_MODEL = 'gpt-5-nano'
constant RESPONSES_CAPABLE_MODEL_PATTERNS (line 5) | const RESPONSES_CAPABLE_MODEL_PATTERNS = [
function isResponsesCapableOpenAIModel (line 13) | function isResponsesCapableOpenAIModel(model: string | undefined | null)...
function getRecommendedOpenAIAPIPath (line 24) | function getRecommendedOpenAIAPIPath(model: string | undefined | null): ...
FILE: src/common/polyfills/electron.ts
class BrowserStorageSync (line 5) | class BrowserStorageSync {
method get (line 6) | async get(keys: string[]): Promise<Record<string, any>> {
method set (line 10) | async set(items: Record<string, any>): Promise<void> {
class BrowserStorage (line 21) | class BrowserStorage {
method constructor (line 24) | constructor() {
class BrowserRuntimeOnMessage (line 29) | class BrowserRuntimeOnMessage {
method addListener (line 31) | addListener(_callback: (message: any, sender: any, sendResponse: any) ...
method removeListener (line 33) | removeListener(_callback: (message: any, sender: any, sendResponse: an...
class BrowserRuntime (line 36) | class BrowserRuntime {
method constructor (line 39) | constructor() {
method sendMessage (line 44) | sendMessage(_message: any): void {}
method getURL (line 46) | getURL(path: string): string {
class BrowserI18n (line 51) | class BrowserI18n {
method detectLanguage (line 52) | detectLanguage(_text: string): Promise<{ languages: { language: string...
class Browser (line 61) | class Browser implements IBrowser {
method constructor (line 66) | constructor() {
FILE: src/common/polyfills/tauri.ts
function getSettings (line 9) | async function getSettings(): Promise<Record<string, any>> {
class BrowserStorageSync (line 14) | class BrowserStorageSync {
method get (line 15) | async get(keys: string[]): Promise<Record<string, any>> {
method set (line 25) | async set(items: Record<string, any>): Promise<void> {
class BrowserStorage (line 40) | class BrowserStorage {
method constructor (line 43) | constructor() {
class BrowserRuntimeOnMessage (line 48) | class BrowserRuntimeOnMessage {
method addListener (line 50) | addListener(_callback: (message: any, sender: any, sendResponse: any) ...
method removeListener (line 52) | removeListener(_callback: (message: any, sender: any, sendResponse: an...
class BrowserRuntime (line 55) | class BrowserRuntime {
method constructor (line 58) | constructor() {
method sendMessage (line 63) | sendMessage(_message: any): void {}
method getURL (line 65) | getURL(path: string): string {
class BrowserI18n (line 70) | class BrowserI18n {
method detectLanguage (line 71) | detectLanguage(_text: string): Promise<{ languages: { language: string...
class Browser (line 80) | class Browser implements IBrowser {
method constructor (line 85) | constructor() {
FILE: src/common/polyfills/userscript.ts
class BrowserStorageSync (line 5) | class BrowserStorageSync {
method get (line 6) | async get(keys: string[]): Promise<Record<string, any>> {
method set (line 14) | async set(items: Record<string, any>): Promise<void> {
class BrowserStorage (line 21) | class BrowserStorage {
method constructor (line 24) | constructor() {
class BrowserRuntimeOnMessage (line 29) | class BrowserRuntimeOnMessage {
method addListener (line 31) | addListener(_callback: (message: any, sender: any, sendResponse: any) ...
method removeListener (line 33) | removeListener(_callback: (message: any, sender: any, sendResponse: an...
class BrowserRuntime (line 36) | class BrowserRuntime {
method constructor (line 39) | constructor() {
method sendMessage (line 44) | sendMessage(_message: any): void {}
method getURL (line 46) | getURL(path: string): string {
class BrowserI18n (line 51) | class BrowserI18n {
method detectLanguage (line 52) | detectLanguage(_text: string): Promise<{ languages: { language: string...
class Browser (line 61) | class Browser implements IBrowser {
method constructor (line 66) | constructor() {
function getStreamText (line 75) | async function getStreamText(stream: ReadableStream) {
function userscriptFetch (line 83) | async function userscriptFetch(url: string, { body, headers, method, sig...
FILE: src/common/services/history.ts
method create (line 16) | create(item: CreateHistoryItem): Promise<HistoryItem> {
method update (line 19) | update(id: number, payload: UpdateHistoryPayload): Promise<void> {
method updateFavorite (line 22) | updateFavorite(id: number, favorite: boolean): Promise<void> {
method touch (line 25) | touch(id: number): Promise<void> {
method delete (line 28) | delete(id: number): Promise<void> {
method clear (line 31) | clear(): Promise<void> {
method list (line 34) | list(options?: HistoryQueryOptions): Promise<HistoryItem[]> {
method get (line 37) | get(id: number): Promise<HistoryItem | undefined> {
FILE: src/common/services/promotion.ts
type II18nPromotionContent (line 5) | interface II18nPromotionContent {
type PromotionFormat (line 14) | type PromotionFormat = 'markdown' | 'html' | 'text'
type II18nPromotionContentItem (line 16) | interface II18nPromotionContentItem {
type IPromotionItem (line 22) | interface IPromotionItem {
type IPromotionResponse (line 33) | interface IPromotionResponse {
function fetchPromotions (line 38) | async function fetchPromotions(): Promise<IPromotionResponse> {
function choicePromotionItem (line 55) | async function choicePromotionItem(items?: IPromotionItem[]) {
function isPromotionItemAvailable (line 79) | function isPromotionItemAvailable(item?: IPromotionItem) {
function getPromotionItemShowedKey (line 97) | function getPromotionItemShowedKey(item: IPromotionItem) {
function getPromotionItemNeverDisplayKey (line 101) | function getPromotionItemNeverDisplayKey(item: IPromotionItem) {
function checkShouldShowPromotionNotification (line 107) | async function checkShouldShowPromotionNotification() {
function isPromotionItemShowed (line 124) | async function isPromotionItemShowed(item?: IPromotionItem): Promise<boo...
function setPromotionItemShowed (line 135) | async function setPromotionItemShowed(item?: IPromotionItem) {
function unsetPromotionItemShowed (line 149) | async function unsetPromotionItemShowed(item?: IPromotionItem) {
function isPromotionItemNeverDisplay (line 161) | async function isPromotionItemNeverDisplay(item?: IPromotionItem): Promi...
function setPromotionItemNeverDisplay (line 172) | async function setPromotionItemNeverDisplay(item?: IPromotionItem) {
function unsetPromotionItemNeverDisplay (line 184) | async function unsetPromotionItemNeverDisplay(item?: IPromotionItem) {
FILE: src/common/store.ts
type ITranslatorState (line 3) | interface ITranslatorState {
FILE: src/common/token.ts
class Encoding (line 3) | class Encoding {
method constructor (line 6) | constructor(model: TiktokenModel) {
method count (line 10) | count(text: string): number {
function isTiktokenModel (line 62) | function isTiktokenModel(model: string): model is TiktokenModel {
function countTokens (line 66) | function countTokens(text: string, model = 'gpt-3.5-turbo-0613'): number {
FILE: src/common/traditional-or-simplified.ts
function isTraditional (line 11) | function isTraditional(str: string): boolean {
function isSimplified (line 15) | function isSimplified(str: string) {
type Result (line 19) | interface Result {
function detect (line 27) | function detect(str: string): Result | undefined {
function charIsS (line 59) | function charIsS(char: string) {
function charIsT (line 63) | function charIsT(char: string) {
FILE: src/common/translate.ts
type TranslateMode (line 9) | type TranslateMode = 'translate' | 'polishing' | 'summarize' | 'analyze'...
type APIModel (line 10) | type APIModel =
type BaseTranslateQuery (line 25) | interface BaseTranslateQuery {
type TranslateQueryBigBang (line 40) | type TranslateQueryBigBang = Omit<
type TranslateQuery (line 48) | type TranslateQuery = BaseTranslateQuery | TranslateQueryBigBang
type TranslateResult (line 50) | interface TranslateResult {
class QuoteProcessor (line 68) | class QuoteProcessor {
method constructor (line 75) | constructor() {
method processText (line 83) | public processText(text: string): string {
method processTextDelta (line 89) | private processTextDelta(textDelta: string): string {
function translate (line 196) | async function translate(query: TranslateQuery) {
FILE: src/common/tts/edge-tts.ts
type EdgeTTSOptions (line 138) | interface EdgeTTSOptions extends SpeakOptions {
function speak (line 144) | async function speak({
function fetchEdgeVoices (line 225) | async function fetchEdgeVoices() {
FILE: src/common/tts/index.ts
function speak (line 77) | async function speak({ text, lang, onFinish, signal }: SpeakOptions) {
function doSpeak (line 96) | async function doSpeak({
FILE: src/common/tts/types.ts
type SpeakOptions (line 3) | interface SpeakOptions {
type TTSProvider (line 11) | type TTSProvider = 'WebSpeech' | 'EdgeTTS'
type DoSpeakOptions (line 13) | interface DoSpeakOptions extends SpeakOptions {
FILE: src/common/types.ts
type ISync (line 8) | interface ISync {
type IStorage (line 13) | interface IStorage {
type IRuntimeOnMessage (line 17) | interface IRuntimeOnMessage {
type IRuntime (line 22) | interface IRuntime {
type II18n (line 28) | interface II18n {
type IBrowser (line 32) | interface IBrowser {
type BaseThemeType (line 38) | type BaseThemeType = 'light' | 'dark'
type ThemeType (line 39) | type ThemeType = BaseThemeType | 'followTheSystem'
type IThemedStyleProps (line 41) | interface IThemedStyleProps {
type LanguageDetectionEngine (line 48) | type LanguageDetectionEngine = 'google' | 'baidu' | 'bing' | 'local'
type ProxyProtocol (line 50) | type ProxyProtocol = 'HTTP' | 'HTTPS'
type ISettings (line 52) | interface ISettings {
FILE: src/common/universal-fetch.ts
function getUniversalFetch (line 6) | function getUniversalFetch() {
FILE: src/common/usehooks.ts
function useLazyEffect (line 4) | function useLazyEffect(effect: EffectCallback, deps: DependencyList = []...
FILE: src/common/user-event.ts
type UserEventType (line 1) | type UserEventType = MouseEvent | TouchEvent | PointerEvent
function getCaretNodeType (line 19) | function getCaretNodeType(event: UserEventType) {
FILE: src/common/utils.ts
function getApiKey (line 28) | async function getApiKey(): Promise<string> {
function getAzureApiKey (line 34) | async function getAzureApiKey(): Promise<string> {
function getSettings (line 120) | async function getSettings(): Promise<ISettings> {
function setSettings (line 260) | async function setSettings(settings: Partial<ISettings>) {
function getBrowser (line 265) | async function getBrowser(): Promise<IBrowser> {
function exportToCsv (line 333) | async function exportToCsv<T extends Record<string, string | number>>(fi...
type FetchSSEOptions (line 378) | interface FetchSSEOptions extends RequestInit {
function fetchSSE (line 388) | async function fetchSSE(input: string, options: FetchSSEOptions) {
function getAssetUrl (line 552) | function getAssetUrl(asset: string) {
FILE: src/tauri/App.tsx
function App (line 21) | function App() {
FILE: src/tauri/bindings.ts
method getConfigContent (line 6) | async getConfigContent(): Promise<string> {
method getUpdateResult (line 9) | async getUpdateResult(): Promise<[boolean, UpdateResult | null]> {
method clearConfigCache (line 12) | async clearConfigCache(): Promise<void> {
method showTranslatorWindowCommand (line 15) | async showTranslatorWindowCommand(): Promise<void> {
method showTranslatorWindowWithSelectedTextCommand (line 18) | async showTranslatorWindowWithSelectedTextCommand(): Promise<void> {
method showActionManagerWindow (line 21) | async showActionManagerWindow(): Promise<void> {
method showHistoryWindow (line 24) | async showHistoryWindow(): Promise<void> {
method getTranslatorWindowAlwaysOnTop (line 27) | async getTranslatorWindowAlwaysOnTop(): Promise<boolean> {
method fetchStream (line 30) | async fetchStream(id: string, url: string, optionsStr: string): Promise<...
method writingCommand (line 38) | async writingCommand(): Promise<void> {
method writeToInput (line 41) | async writeToInput(text: string): Promise<void> {
method finishWriting (line 44) | async finishWriting(): Promise<void> {
method insertTranslationIntoPreviousInput (line 47) | async insertTranslationIntoPreviousInput(text: string): Promise<Result<n...
method rememberActiveWindowCommand (line 55) | async rememberActiveWindowCommand(): Promise<boolean> {
method detectLang (line 58) | async detectLang(text: string): Promise<string> {
method screenshot (line 61) | async screenshot(x: number, y: number): Promise<void> {
method hideTranslatorWindow (line 64) | async hideTranslatorWindow(): Promise<void> {
method startOcr (line 67) | async startOcr(): Promise<void> {
method finishOcr (line 70) | async finishOcr(): Promise<void> {
method cutImage (line 73) | async cutImage(left: number, top: number, width: number, height: number)...
type CheckUpdateEvent (line 98) | type CheckUpdateEvent = null
type CheckUpdateResultEvent (line 99) | type CheckUpdateResultEvent = UpdateResult
type ConfigUpdatedEvent (line 100) | type ConfigUpdatedEvent = null
type PinnedFromTrayEvent (line 101) | type PinnedFromTrayEvent = { pinned: boolean }
type PinnedFromWindowEvent (line 102) | type PinnedFromWindowEvent = { pinned: boolean }
type UpdateResult (line 103) | type UpdateResult = { version: string; currentVersion: string; body: str...
type __EventObj__ (line 111) | type __EventObj__<T> = {
type Result (line 119) | type Result<T, E> = { status: 'ok'; data: T } | { status: 'error'; error...
function __makeEvents__ (line 121) | function __makeEvents__<T extends Record<string, any>>(mappings: Record<...
FILE: src/tauri/components/Window.tsx
type IWindowProps (line 41) | interface IWindowProps {
function Window (line 47) | function Window(props: IWindowProps) {
type ITitlebarContainerProps (line 106) | interface ITitlebarContainerProps {
function TitlebarContainer (line 111) | function TitlebarContainer(props: ITitlebarContainerProps) {
function InnerWindow (line 126) | function InnerWindow(props: IWindowProps) {
FILE: src/tauri/legacy-tauri-ipc.ts
type LegacyInvokePayload (line 1) | type LegacyInvokePayload = {
type TauriInternals (line 8) | type TauriInternals = {
type TauriWindow (line 12) | type TauriWindow = (Window & typeof globalThis) & {
FILE: src/tauri/utils.ts
function isMissingNormalKey (line 26) | function isMissingNormalKey(hotkey: string): boolean {
function bindHotkey (line 31) | async function bindHotkey(oldHotKey?: string) {
function bindDisplayWindowHotkey (line 54) | async function bindDisplayWindowHotkey(oldHotKey?: string) {
function bindOCRHotkey (line 77) | async function bindOCRHotkey(oldOCRHotKey?: string) {
function bindWritingHotkey (line 100) | async function bindWritingHotkey(oldWritingHotKey?: string) {
function onSettingsSave (line 123) | function onSettingsSave(oldSettings: ISettings) {
FILE: src/tauri/windows/ActionManagerWindow.tsx
function ActionManagerWindow (line 6) | function ActionManagerWindow() {
FILE: src/tauri/windows/HistoryWindow.tsx
function HistoryWindow (line 12) | function HistoryWindow() {
FILE: src/tauri/windows/ScreenshotWindow.tsx
function ScreenshotWindow (line 18) | function ScreenshotWindow() {
FILE: src/tauri/windows/SettingsWindow.tsx
function SettingsWindow (line 5) | function SettingsWindow() {
FILE: src/tauri/windows/ThumbWindow.tsx
function ThumbWindow (line 5) | function ThumbWindow() {
FILE: src/tauri/windows/TranslatorWindow.tsx
function TranslatorWindow (line 24) | function TranslatorWindow() {
FILE: src/tauri/windows/UpdaterWindow.tsx
function UpdaterWindow (line 32) | function UpdaterWindow() {
Condensed preview — 253 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,008K chars).
[
{
"path": ".eslintignore",
"chars": 45,
"preview": "public\ndist\nsrc/tauri/bindings.ts\nsrc-safari\n"
},
{
"path": ".eslintrc.js",
"chars": 1194,
"preview": "module.exports = {\n env: {\n browser: true,\n es2021: true,\n node: true,\n },\n extends: ['esl"
},
{
"path": ".github/ISSUE_TEMPLATE/bug-report.yml",
"chars": 5128,
"preview": "name: Bug report\ndescription: Problems with the software\ntitle: '[Bug] {{请输入标题,不要留空,并把两个花括号去掉 - Please enter a title, do"
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 240,
"preview": "blank_issues_enabled: false\ncontact_links:\n - name: Ask a question or get support\n url: https://github.com/nextai-tr"
},
{
"path": ".github/ISSUE_TEMPLATE/feature.yml",
"chars": 2185,
"preview": "name: Feature\ndescription: Add new feature, improve code, and more\nlabels: [ \"enhancement\" ]\nbody:\n - type: markdown\n "
},
{
"path": ".github/dependabot.yml",
"chars": 193,
"preview": "version: 2\nupdates:\n - package-ecosystem: github-actions\n directory: /\n schedule:\n interval: weekly\n - pack"
},
{
"path": ".github/workflows/lint.yaml",
"chars": 1711,
"preview": "name: Lint\n\non:\n push:\n branches:\n - main\n pull_request:\n branches:\n - main\n\njobs:\n typos-check:\n "
},
{
"path": ".github/workflows/playwright.yml",
"chars": 733,
"preview": "name: Playwright Tests\n\non:\n push:\n branches: \n - main\n pull_request:\n branches: \n - main\n\njobs:\n e2e"
},
{
"path": ".github/workflows/release.yaml",
"chars": 10791,
"preview": "name: Release\n\non:\n push:\n tags: [ v\\d+\\.\\d+\\.\\d+ ]\n\njobs:\n create-release:\n permissions:\n contents: write\n"
},
{
"path": ".github/workflows/test-build.yaml",
"chars": 2532,
"preview": "name: Test Build\n\non:\n workflow_dispatch:\n\njobs:\n build-tauri:\n permissions:\n contents: write\n strategy:\n "
},
{
"path": ".github/workflows/unit-test.yaml",
"chars": 495,
"preview": "name: Unit Test\n\non:\n push:\n branches:\n - main\n pull_request:\n branches:\n - main\n\njobs:\n unit-test:\n "
},
{
"path": ".github/workflows/winget.yml",
"chars": 431,
"preview": "name: Publish to WinGet\non:\n release:\n types: [released]\njobs:\n publish:\n # Action can only be run on windows\n "
},
{
"path": ".gitignore",
"chars": 204,
"preview": "npm-debug.log\nnode_modules/\ndist/\ntmp/\nrelease/\nyarn-error.log\nnpm-error.log\n.DS_Store\n*.json-e\n*.js-e\n\n.vscode\n.idea\n.e"
},
{
"path": ".prettierrc.js",
"chars": 227,
"preview": "module.exports = {\n singleQuote: true,\n jsxSingleQuote: true,\n semi: false,\n trailingComma: 'es5',\n tabWi"
},
{
"path": "AGENTS.md",
"chars": 2930,
"preview": "# Repository Guidelines\n\n## Project Structure & Module Organization\n- `src/browser-extension/` hosts extension surfaces "
},
{
"path": "CLIP-EXTENSIONS-CN.md",
"chars": 2230,
"preview": "桌面端应用全局划词插件\n----------------------\n\n<p align=\"center\">\n <br> <a href=\"CLIP-EXTENSIONS.md\">English</a> | 中文\n</p>\n\n划词翻译"
},
{
"path": "CLIP-EXTENSIONS.md",
"chars": 3062,
"preview": "Desktop Application Global Clip Extensions\n------------------------------------------\n\n<p align=\"center\">\n <br> Engli"
},
{
"path": "LICENSE",
"chars": 34523,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "Makefile",
"chars": 1016,
"preview": "VERSION ?= 0.1.0\n\nclean:\n\trm -rf dist\n\nchange-version:\n\tsed -i -e \"s/\\\"version\\\": \\\".*\\\"/\\\"version\\\": \\\"$(VERSION)\\\"/\" s"
},
{
"path": "README-CN.md",
"chars": 7134,
"preview": "# 因为收到了 OpenAI 公司的品牌名称所有权的警告,所以此项目和此产品改名为 nextai translator,望您能够理解。\n\n<p align=\"center\">\n <br> <a href=\"README.md\">Eng"
},
{
"path": "README.md",
"chars": 9111,
"preview": "# Due to receiving a trademark ownership warning from OpenAI, this project and product has been renamed to nextai transl"
},
{
"path": "clip-extensions/popclip/Config.plist",
"chars": 1322,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "clip-extensions/popclip/nextai-translator.sh",
"chars": 196,
"preview": "send_text() {\n curl -d \"$POPCLIP_TEXT\" --unix-socket /tmp/openai-translator.sock http://nextai-translator\n}\n\nif ! sen"
},
{
"path": "clip-extensions/snipdo/nextai-translator.json",
"chars": 310,
"preview": "{\n \"name\": \"NextAI Translator\",\n \"identifier\": \"xyz.yetone.apps.openai-translator.clip-extensions.snipdo\",\n \"ic"
},
{
"path": "clip-extensions/snipdo/nextai-translator.ps1",
"chars": 167,
"preview": "param(\n[string]$PLAIN_TEXT\n)\n\n$encode_text = [System.Text.Encoding]::UTF8.GetBytes($PLAIN_TEXT)\n\ncurl 127.0.0.1:62007 -M"
},
{
"path": "docs/chatglm-cn.md",
"chars": 451,
"preview": "如何获取 智谱清言(ChatGLM)的 refresh_token 和 token\n=================================================\n\n1. 去 [智谱清言官网](https://chatg"
},
{
"path": "docs/chatglm.md",
"chars": 606,
"preview": "How to obtain the `refresh_token` and `token` for ChatGLM\n=========================================================\n\n1. "
},
{
"path": "docs/chatgpt-cn.md",
"chars": 388,
"preview": "FAQ\n===\n\n# Q: 遇到了如下报错该怎么办?\n\n<img width=\"704\" alt=\"image\" src=\"https://github.com/nextai-translator/nextai-translator/ass"
},
{
"path": "docs/chatgpt.md",
"chars": 552,
"preview": "FAQ\n===\n\n# Q: What should be done when encountering the following error?\n\n<img width=\"704\" alt=\"image\" src=\"https://gith"
},
{
"path": "docs/kimi-cn.md",
"chars": 440,
"preview": "如何获取 Kimi 的 refresh_token 和 access_token\n============================================\n\n1. 去 [Kimi 官网](https://kimi.moons"
},
{
"path": "docs/kimi.md",
"chars": 584,
"preview": "How to Obtain Kimi refresh_token and access_token\n=================================================\n\n1. Go to the [Kimi "
},
{
"path": "e2e/common.ts",
"chars": 777,
"preview": "import { Page } from '@playwright/test'\n\nexport function getOptionsPageUrl(extensionId: string) {\n return `chrome-ext"
},
{
"path": "e2e/fixtures.ts",
"chars": 1053,
"preview": "import path from 'node:path'\nimport { type BrowserContext, test as base, chromium } from '@playwright/test'\n\nexport cons"
},
{
"path": "e2e/hotkey.spec.ts",
"chars": 1421,
"preview": "import path from 'node:path'\nimport { getOptionsPageUrl, selectExampleText } from './common'\nimport { expect, test } fro"
},
{
"path": "e2e/index.spec.ts",
"chars": 1208,
"preview": "import path from 'node:path'\nimport { expect, test } from './fixtures'\nimport { getOptionsPageUrl, getPopupPageUrl, sele"
},
{
"path": "e2e/test.html",
"chars": 311,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\""
},
{
"path": "e2e/titlebar.spec.ts",
"chars": 1222,
"preview": "import path from 'node:path'\nimport { expect, test } from './fixtures'\nimport { selectExampleText } from './common'\nimpo"
},
{
"path": "package.json",
"chars": 6532,
"preview": "{\n \"name\": \"nextai-translator\",\n \"version\": \"0.1.0\",\n \"description\": \"nextai-translator\",\n \"packageManager\": \"pnpm@9"
},
{
"path": "playwright.config.ts",
"chars": 221,
"preview": "/**\n * @see {@link https://playwright.dev/docs/chrome-extensions Chrome extensions | Playwright}\n */\nimport { defineConf"
},
{
"path": "scripts/release.py",
"chars": 2479,
"preview": "import os\nimport subprocess\n\ndef get_current_version_from_tag():\n subprocess.check_output(['git', 'pull', 'origin', '"
},
{
"path": "src/browser-extension/background/index.ts",
"chars": 8578,
"preview": "/* eslint-disable no-case-declarations */\nimport browser from 'webextension-polyfill'\nimport { BackgroundEventNames } fr"
},
{
"path": "src/browser-extension/common.ts",
"chars": 176,
"preview": "export const optionsPageOpenaiAPIKeyPromotionIDKey = 'optionsPage:openaiAPIKeyPromotionID'\nexport const optionsPageHeade"
},
{
"path": "src/browser-extension/content_script/InnerContainer.tsx",
"chars": 3499,
"preview": "import { computePosition, shift, flip, offset, type ReferenceElement, size } from '@floating-ui/dom'\nimport { PropsWithC"
},
{
"path": "src/browser-extension/content_script/TitleBar.tsx",
"chars": 3348,
"preview": "import { useState } from 'react'\nimport { createUseStyles } from 'react-jss'\nimport { useTranslation } from 'react-i18ne"
},
{
"path": "src/browser-extension/content_script/consts.ts",
"chars": 618,
"preview": "export const zIndex = '2147483647'\nexport const popupThumbID = '__yetone-nextai-translator-popup-thumb'\nexport const pop"
},
{
"path": "src/browser-extension/content_script/index.tsx",
"chars": 10590,
"preview": "import '../enable-dev-hmr'\nimport * as utils from '@/common/utils'\nimport React from 'react'\nimport icon from '@/common/"
},
{
"path": "src/browser-extension/content_script/utils.ts",
"chars": 2818,
"preview": "import { containerID, documentPadding, popupCardID, popupThumbID, zIndex } from './consts'\n\nfunction attachEventsToConta"
},
{
"path": "src/browser-extension/enable-dev-hmr.ts",
"chars": 448,
"preview": "// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-nocheck\nimport RefreshRuntime from '/@react-refresh"
},
{
"path": "src/browser-extension/manifest.ts",
"chars": 2710,
"preview": "/* eslint-disable camelcase */\nimport { version } from '../../package.json'\n\nexport function getManifest(browser: 'firef"
},
{
"path": "src/browser-extension/options/index.css",
"chars": 24,
"preview": "body {\n margin: 0;\n}\n"
},
{
"path": "src/browser-extension/options/index.html",
"chars": 416,
"preview": "<!DOCTYPE html>\n<html>\n<head>\n <title>NextAI Translator Options</title>\n <style>\n #root {\n height: 100vh;\n "
},
{
"path": "src/browser-extension/options/index.tsx",
"chars": 2432,
"preview": "import '../enable-dev-hmr'\nimport React, { useEffect, useState } from 'react'\nimport { createRoot } from 'react-dom/clie"
},
{
"path": "src/browser-extension/popup/index.css",
"chars": 212,
"preview": "/* @tailwind base; */\n/* @tailwind components; */\n/* @tailwind utilities; */\nhtml,\nbody {\n padding: 0;\n margin: 0;"
},
{
"path": "src/browser-extension/popup/index.html",
"chars": 694,
"preview": "<!doctype html>\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <title>NextAI Translator</title>\n <style>\n html, "
},
{
"path": "src/browser-extension/popup/index.tsx",
"chars": 928,
"preview": "import '../enable-dev-hmr'\nimport { createRoot } from 'react-dom/client'\nimport { Translator } from '../../common/compon"
},
{
"path": "src/common/__tests__/translate.test.ts",
"chars": 5219,
"preview": "import { describe, expect, it } from 'vitest'\nimport { QuoteProcessor } from '../translate'\n\ndescribe('QuoteProcessor', "
},
{
"path": "src/common/analysis.ts",
"chars": 1427,
"preview": "import * as Sentry from '@sentry/react'\nimport ReactGA from 'react-ga4'\nimport { getSettings, isDesktopApp, isUserscript"
},
{
"path": "src/common/background/eventnames.ts",
"chars": 572,
"preview": "import { IVocabularyInternalService } from '../internal-services/vocabulary'\nimport { IHistoryInternalService } from '.."
},
{
"path": "src/common/background/fetch.ts",
"chars": 3708,
"preview": "import { isFirefox } from '../utils'\nimport { BackgroundEventNames } from './eventnames'\nimport { ReadableStream as Read"
},
{
"path": "src/common/background/local-storage.ts",
"chars": 952,
"preview": "/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport { BackgroundEventNames } from './eventnames'\n\nexport asyn"
},
{
"path": "src/common/background/services/action.ts",
"chars": 1261,
"preview": "import { IActionInternalService, ICreateActionOption, IUpdateActionOption } from '../../internal-services/action'\nimport"
},
{
"path": "src/common/background/services/base.ts",
"chars": 578,
"preview": "import { BackgroundEventNames } from '../eventnames'\n\nexport async function callMethod(\n eventType: keyof typeof Back"
},
{
"path": "src/common/background/services/history.ts",
"chars": 1382,
"preview": "import {\n CreateHistoryItem,\n HistoryQueryOptions,\n IHistoryInternalService,\n UpdateHistoryPayload,\n} from '"
},
{
"path": "src/common/background/services/vocabulary.ts",
"chars": 1459,
"preview": "import { VocabularyItem } from '../../internal-services/db'\nimport { IVocabularyInternalService } from '../../internal-s"
},
{
"path": "src/common/components/ActionForm.tsx",
"chars": 6501,
"preview": "import { useTranslation } from 'react-i18next'\nimport { ICreateActionOption } from '../internal-services/action'\nimport "
},
{
"path": "src/common/components/ActionManager.tsx",
"chars": 16310,
"preview": "import { useLiveQuery } from 'dexie-react-hooks'\nimport icon from '../assets/images/icon.png'\nimport { actionService } f"
},
{
"path": "src/common/components/CodeBlock.tsx",
"chars": 4716,
"preview": "import { CodeBlock as BaseCodeBlock } from 'react-code-block'\nimport { Button } from 'baseui-sd/button'\nimport { themes "
},
{
"path": "src/common/components/CopyButton.tsx",
"chars": 1044,
"preview": "import { Tooltip } from 'baseui-sd/tooltip'\nimport { CopyToClipboard } from 'react-copy-to-clipboard'\nimport { RxCopy } "
},
{
"path": "src/common/components/DurationPicker.tsx",
"chars": 2872,
"preview": "import { useCallback, useEffect, useState } from 'react'\nimport NumberInput from './NumberInput'\nimport { Select, Select"
},
{
"path": "src/common/components/ErrorFallback.tsx",
"chars": 747,
"preview": "import React from 'react'\n\nexport function ErrorFallback({ error, resetErrorBoundary }: { error: Error; resetErrorBounda"
},
{
"path": "src/common/components/Form/form.ts",
"chars": 8790,
"preview": "/* eslint-disable @typescript-eslint/naming-convention */\n/* eslint-disable @typescript-eslint/ban-types */\n/* eslint-di"
},
{
"path": "src/common/components/Form/index.module.css",
"chars": 190,
"preview": ".formItem {\n margin-bottom: 10px;\n}\n\n.formItem:last-child {\n margin-bottom: 0;\n}\n\n.error {\n color: red;\n fon"
},
{
"path": "src/common/components/Form/index.ts",
"chars": 89,
"preview": "import * as validators from './validators'\n\nexport { validators }\nexport * from './form'\n"
},
{
"path": "src/common/components/Form/item.tsx",
"chars": 1173,
"preview": "import React from 'react'\nimport { FieldProps } from 'rc-field-form/lib/Field'\nimport { Field } from 'rc-field-form'\nimp"
},
{
"path": "src/common/components/Form/typings.ts",
"chars": 1315,
"preview": "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/naming-convention */\n/* esl"
},
{
"path": "src/common/components/Form/validators.ts",
"chars": 3584,
"preview": "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable prefer-promise-reject-errors */\n/* eslint-disa"
},
{
"path": "src/common/components/GlobalSuspense.tsx",
"chars": 212,
"preview": "import { Suspense } from 'react'\n\nexport function GlobalSuspense({ children }: { children: React.ReactNode }) {\n // T"
},
{
"path": "src/common/components/IconPicker.tsx",
"chars": 5404,
"preview": "import { IconType } from 'react-icons'\nimport * as mdIcons from 'react-icons/md'\nimport { createUseStyles } from 'react-"
},
{
"path": "src/common/components/IpLocationNotification.tsx",
"chars": 1830,
"preview": "import React, { useEffect, useState } from 'react'\nimport { Trans } from 'react-i18next'\nimport { Notification, KIND as "
},
{
"path": "src/common/components/LogoWithText.tsx",
"chars": 2179,
"preview": "import { forwardRef, useImperativeHandle, useRef } from 'react'\nimport { createUseStyles } from 'react-jss'\nimport { ITh"
},
{
"path": "src/common/components/Markdown.tsx",
"chars": 2104,
"preview": "import ReactMarkdown from 'react-markdown'\nimport { CodeBlock } from './CodeBlock'\nimport { useTheme } from '../hooks/us"
},
{
"path": "src/common/components/NumberInput.tsx",
"chars": 1428,
"preview": "import { Input, InputProps, Size } from 'baseui-sd/input'\nimport React from 'react'\n\nexport interface INumberInputProps "
},
{
"path": "src/common/components/ProxyTester.tsx",
"chars": 5087,
"preview": "import { useTranslation } from 'react-i18next'\nimport { ISettings } from '../types'\nimport { Button } from 'baseui-sd/bu"
},
{
"path": "src/common/components/RenderingFormatSelector.tsx",
"chars": 1107,
"preview": "import { Select, SelectProps } from 'baseui-sd/select'\nimport { ActionOutputRenderingFormat } from '../internal-services"
},
{
"path": "src/common/components/Settings.tsx",
"chars": 131400,
"preview": "import React, { useCallback, useEffect, useReducer, useState } from 'react'\nimport _ from 'underscore'\nimport { Tabs, Ta"
},
{
"path": "src/common/components/SpeakerIcon.tsx",
"chars": 2953,
"preview": "import { useCallback, useEffect, useRef, useState } from 'react'\nimport { LangCode } from '../lang'\nimport { defaultTTSP"
},
{
"path": "src/common/components/SpeakerMotion.tsx",
"chars": 1893,
"preview": "import React from 'react'\nimport { createUseStyles } from 'react-jss'\nimport { RxSpeakerLoud, RxSpeakerModerate, RxSpeak"
},
{
"path": "src/common/components/SpinnerIcon.tsx",
"chars": 687,
"preview": "import { IconBaseProps } from 'react-icons'\nimport { createUseStyles } from 'react-jss'\nimport { CgSpinner } from 'react"
},
{
"path": "src/common/components/Toaster.tsx",
"chars": 3975,
"preview": "import { useToaster } from 'react-hot-toast/headless'\nimport { createUseStyles } from 'react-jss'\nimport clsx from 'clsx"
},
{
"path": "src/common/components/Tooltip.tsx",
"chars": 535,
"preview": "import { StatefulTooltip, StatefulTooltipProps } from 'baseui-sd/tooltip'\n\ninterface ITooltipProps extends StatefulToolt"
},
{
"path": "src/common/components/TranslationHistory.tsx",
"chars": 24625,
"preview": "import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { Modal, ModalBody, ModalHeader "
},
{
"path": "src/common/components/Translator.tsx",
"chars": 126467,
"preview": "import React, { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from 'react'\nimport { u"
},
{
"path": "src/common/components/Vocabulary.tsx",
"chars": 19165,
"preview": "import { useCallback, useEffect, useMemo, useState, useRef } from 'react'\nimport { Button } from 'baseui-sd/button'\nimpo"
},
{
"path": "src/common/components/icons/CerebrasIcon.tsx",
"chars": 443,
"preview": "import { IconBaseProps } from 'react-icons'\nimport Logo from '@/common/assets/images/cerebras.svg?react'\nimport { create"
},
{
"path": "src/common/components/icons/ChatGLMIcon.tsx",
"chars": 441,
"preview": "import { IconBaseProps } from 'react-icons'\nimport Logo from '@/common/assets/images/chatglm.svg?react'\nimport { createU"
},
{
"path": "src/common/components/icons/ClaudeIcon.tsx",
"chars": 722,
"preview": "import { IconBaseProps } from 'react-icons'\nimport Logo from '@/common/assets/images/claude.svg?react'\nimport { createUs"
},
{
"path": "src/common/components/icons/CohereIcon.tsx",
"chars": 439,
"preview": "import { IconBaseProps } from 'react-icons'\nimport Logo from '@/common/assets/images/cohere.svg?react'\nimport { createUs"
},
{
"path": "src/common/components/icons/DeepSeekIcon.tsx",
"chars": 443,
"preview": "import { IconBaseProps } from 'react-icons'\nimport Logo from '@/common/assets/images/deepseek.svg?react'\nimport { create"
},
{
"path": "src/common/components/icons/GroqIcon.tsx",
"chars": 435,
"preview": "import { IconBaseProps } from 'react-icons'\nimport Logo from '@/common/assets/images/groq.svg?react'\nimport { createUseS"
},
{
"path": "src/common/components/icons/KimiIcon.tsx",
"chars": 435,
"preview": "import { IconBaseProps } from 'react-icons'\nimport Logo from '@/common/assets/images/kimi.svg?react'\nimport { createUseS"
},
{
"path": "src/common/components/icons/MoonshotIcon.tsx",
"chars": 514,
"preview": "import { IconBaseProps } from 'react-icons'\nimport moonshotLightSrc from '@/common/assets/images/moonshot-light.png'\nimp"
},
{
"path": "src/common/components/icons/OllamaIcon.tsx",
"chars": 558,
"preview": "import { IconBaseProps } from 'react-icons'\nimport Logo from '@/common/assets/images/ollama.svg?react'\nimport { createUs"
},
{
"path": "src/common/constants.ts",
"chars": 800,
"preview": "import { TranslateMode } from './translate'\n\nexport const CUSTOM_MODEL_ID = '__custom__'\nexport const PREFIX = '__yetone"
},
{
"path": "src/common/engines/abstract-engine.ts",
"chars": 465,
"preview": "import { IEngine, IMessageRequest, IModel } from './interfaces'\n\nexport abstract class AbstractEngine implements IEngine"
},
{
"path": "src/common/engines/abstract-openai.spec.ts",
"chars": 4488,
"preview": "import { beforeEach, describe, expect, it, vi } from 'vitest'\nimport { AbstractOpenAI } from './abstract-openai'\nimport "
},
{
"path": "src/common/engines/abstract-openai.ts",
"chars": 14369,
"preview": "/* eslint-disable camelcase */\nimport { urlJoin } from 'url-join-ts'\nimport { getRecommendedOpenAIAPIPath, OPENAI_RESPON"
},
{
"path": "src/common/engines/azure.ts",
"chars": 2952,
"preview": "/* eslint-disable camelcase */\nimport { getSettings } from '../utils'\nimport { AbstractOpenAI } from './abstract-openai'"
},
{
"path": "src/common/engines/cerebras.ts",
"chars": 5091,
"preview": "/* eslint-disable camelcase */\nimport { getUniversalFetch } from '../universal-fetch'\nimport { fetchSSE, getSettings } f"
},
{
"path": "src/common/engines/chatglm.ts",
"chars": 10530,
"preview": "/* eslint-disable camelcase */\nimport { getUniversalFetch } from '@/common/universal-fetch'\nimport { fetchSSE, getSettin"
},
{
"path": "src/common/engines/chatgpt.ts",
"chars": 12320,
"preview": "/* eslint-disable camelcase */\nimport { v4 as uuidv4 } from 'uuid'\nimport { getUniversalFetch } from '../universal-fetch"
},
{
"path": "src/common/engines/claude.ts",
"chars": 4895,
"preview": "/* eslint-disable camelcase */\nimport { urlJoin } from 'url-join-ts'\nimport { CUSTOM_MODEL_ID } from '../constants'\nimpo"
},
{
"path": "src/common/engines/cohere.ts",
"chars": 4570,
"preview": "/* eslint-disable camelcase */\nimport { getUniversalFetch } from '../universal-fetch'\nimport { fetchSSE, getSettings } f"
},
{
"path": "src/common/engines/deepseek.ts",
"chars": 1950,
"preview": "import { urlJoin } from 'url-join-ts'\nimport { getSettings } from '../utils'\nimport { AbstractOpenAI } from './abstract-"
},
{
"path": "src/common/engines/gemini.ts",
"chars": 5997,
"preview": "/* eslint-disable camelcase */\nimport { urlJoin } from 'url-join-ts'\nimport { getUniversalFetch } from '../universal-fet"
},
{
"path": "src/common/engines/groq.ts",
"chars": 1901,
"preview": "import { urlJoin } from 'url-join-ts'\nimport { CUSTOM_MODEL_ID } from '../constants'\nimport { getUniversalFetch } from '"
},
{
"path": "src/common/engines/index.ts",
"chars": 2506,
"preview": "import { RiOpenaiFill } from 'react-icons/ri'\nimport { Azure } from './azure'\nimport { ChatGPT } from './chatgpt'\nimport"
},
{
"path": "src/common/engines/interfaces.ts",
"chars": 762,
"preview": "export interface IModel {\n id: string\n name: string\n description?: string\n}\n\nexport interface IMessage {\n ro"
},
{
"path": "src/common/engines/kimi.ts",
"chars": 7108,
"preview": "/* eslint-disable camelcase */\nimport { getUniversalFetch } from '@/common/universal-fetch'\nimport { fetchSSE, getSettin"
},
{
"path": "src/common/engines/minimax.ts",
"chars": 924,
"preview": "import { getSettings } from '../utils'\nimport { AbstractOpenAI } from './abstract-openai'\nimport { IModel } from './inte"
},
{
"path": "src/common/engines/moonshot.ts",
"chars": 1949,
"preview": "import { urlJoin } from 'url-join-ts'\nimport { getSettings } from '../utils'\nimport { AbstractOpenAI } from './abstract-"
},
{
"path": "src/common/engines/ollama.ts",
"chars": 2219,
"preview": "import { CUSTOM_MODEL_ID } from '../constants'\nimport { getSettings } from '../utils'\nimport { AbstractOpenAI } from './"
},
{
"path": "src/common/engines/openai.ts",
"chars": 1052,
"preview": "/* eslint-disable camelcase */\nimport { CUSTOM_MODEL_ID } from '../constants'\nimport { getSettings } from '../utils'\nimp"
},
{
"path": "src/common/geo-data.ts",
"chars": 1680,
"preview": "export const ALLOWED_COUNTRY_CODES = new Set([\n 'AL',\n 'DZ',\n 'AD',\n 'AO',\n 'AG',\n 'AR',\n 'AM',\n "
},
{
"path": "src/common/geo.ts",
"chars": 1462,
"preview": "import { ALLOWED_COUNTRY_CODES } from './geo-data' // a separate file for bypassing spell check\nimport { getUniversalFet"
},
{
"path": "src/common/highlight-in-textarea/index.css",
"chars": 1449,
"preview": ".yetone-hit-container {\n display: inline-block;\n position: relative;\n overflow: hidden !important;\n -webkit-"
},
{
"path": "src/common/highlight-in-textarea/index.ts",
"chars": 14912,
"preview": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport styles from './index.css?inline'\n\ninterface IConfig {\n "
},
{
"path": "src/common/hooks/global.ts",
"chars": 390,
"preview": "import { createGlobalState } from 'react-hooks-global-state'\nimport { ThemeType } from '../types'\n\nconst initialState = "
},
{
"path": "src/common/hooks/useCollectedWordTotal.ts",
"chars": 453,
"preview": "import { useEffect } from 'react'\nimport { vocabularyService } from '../services/vocabulary'\nimport { useGlobalState } f"
},
{
"path": "src/common/hooks/useCurrentThemeType.ts",
"chars": 586,
"preview": "import { useMemo } from 'react'\nimport { BaseThemeType } from '../types'\nimport { useThemeDetector } from './useThemeDet"
},
{
"path": "src/common/hooks/useMemoWindow.ts",
"chars": 3503,
"preview": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { WebviewWindow } from '@tauri-apps/api/webviewWindow'\nim"
},
{
"path": "src/common/hooks/usePinned.ts",
"chars": 1099,
"preview": "import { useCallback, useEffect } from 'react'\nimport { isTauri } from '../utils'\nimport { useGlobalState } from './glob"
},
{
"path": "src/common/hooks/usePromotionNeverDisplay.ts",
"chars": 1489,
"preview": "import { useCallback, useEffect, useState } from 'react'\nimport { useGlobalState } from './global'\nimport {\n IPromoti"
},
{
"path": "src/common/hooks/usePromotionShowed.ts",
"chars": 1331,
"preview": "import { useCallback, useEffect, useState } from 'react'\nimport { useGlobalState } from './global'\nimport {\n IPromoti"
},
{
"path": "src/common/hooks/useSettings.ts",
"chars": 740,
"preview": "import useSWR from 'swr'\n\nimport { ISettings } from '../types'\nimport { getSettings } from '../utils'\nimport { useCallba"
},
{
"path": "src/common/hooks/useTheme.ts",
"chars": 355,
"preview": "import { DarkTheme, LightTheme } from 'baseui-sd/themes'\nimport { useCurrentThemeType } from './useCurrentThemeType'\nimp"
},
{
"path": "src/common/hooks/useThemeDetector.ts",
"chars": 771,
"preview": "import { useCallback, useEffect, useState } from 'react'\n\nexport const useThemeDetector = () => {\n const getCurrentTh"
},
{
"path": "src/common/hooks/useThemeType.ts",
"chars": 430,
"preview": "import useSWR from 'swr'\nimport { getSettings } from '../utils'\n\nexport const useThemeType = () => {\n const { data: t"
},
{
"path": "src/common/i18n/locales/en/translation.json",
"chars": 14002,
"preview": "{\n \"Translate\": \"Translate\",\n \"Summarize\": \"Summarize\",\n \"Polishing\": \"Polishing\",\n \"Analyze\": \"Analyze\",\n "
},
{
"path": "src/common/i18n/locales/ja/translation.json",
"chars": 10827,
"preview": "{\n \"Translate\": \"翻訳\",\n \"Summarize\": \"要約\",\n \"Polishing\": \"推敲\",\n \"Analyze\": \"分析\",\n \"Explain Code\": \"コードを説明す"
},
{
"path": "src/common/i18n/locales/th/translation.json",
"chars": 12761,
"preview": "{\n \"Translate\": \"แปล\",\n \"Summarize\": \"สรุป\",\n \"Polishing\": \"ขัดเกลา\",\n \"Analyze\": \"วิเคราะห์\",\n \"Explain "
},
{
"path": "src/common/i18n/locales/tr/translation.json",
"chars": 13779,
"preview": "{\n \"Translate\": \"Çevir\",\n \"Summarize\": \"Özetle\",\n \"Polishing\": \"Düzelt\",\n \"Analyze\": \"Analiz Et\",\n \"Expla"
},
{
"path": "src/common/i18n/locales/zh-Hans/translation.json",
"chars": 10075,
"preview": "{\n \"Translate\": \"翻译\",\n \"Summarize\": \"总结\",\n \"Polishing\": \"润色\",\n \"Analyze\": \"分析\",\n \"Explain Code\": \"解释代码\",\n"
},
{
"path": "src/common/i18n/locales/zh-Hant/translation.json",
"chars": 10182,
"preview": "{\n \"Translate\": \"翻譯\",\n \"Summarize\": \"總結\",\n \"Polishing\": \"修飾\",\n \"Analyze\": \"分析\",\n \"Explain Code\": \"解釋程式碼\","
},
{
"path": "src/common/i18n.d.ts",
"chars": 28,
"preview": "declare module 'i18next' {}\n"
},
{
"path": "src/common/i18n.js",
"chars": 1307,
"preview": "import i18n from 'i18next'\nimport { initReactI18next } from 'react-i18next'\n\nimport Backend from 'i18next-http-backend'\n"
},
{
"path": "src/common/internal-services/action.ts",
"chars": 5088,
"preview": "import { builtinActionModes } from '../constants'\nimport { TranslateMode } from '../translate'\nimport { Action, ActionOu"
},
{
"path": "src/common/internal-services/db.ts",
"chars": 2001,
"preview": "import Dexie, { Table } from 'dexie'\nimport { TranslateMode } from '../translate'\nimport { LangCode } from '../lang'\n\nex"
},
{
"path": "src/common/internal-services/history.ts",
"chars": 4070,
"preview": "import { getLocalDB, HistoryItem } from './db'\nimport { LangCode } from '../lang'\nimport { TranslateMode } from '../tran"
},
{
"path": "src/common/internal-services/vocabulary.ts",
"chars": 2644,
"preview": "import { getLocalDB, VocabularyItem } from './db'\n\nexport interface IVocabularyInternalService {\n putItem(item: Vocab"
},
{
"path": "src/common/lang/data.ts",
"chars": 9188,
"preview": "import { LangCode } from '.'\n\nexport interface Config {\n name: string\n nameEn: string\n isVariant?: boolean // w"
},
{
"path": "src/common/lang/index.ts",
"chars": 11028,
"preview": "/* eslint-disable no-control-regex */\n/* eslint-disable no-misleading-character-class */\n\nimport { isTraditional } from "
},
{
"path": "src/common/openai-api-path.spec.ts",
"chars": 930,
"preview": "import { describe, expect, it } from 'vitest'\nimport {\n getRecommendedOpenAIAPIPath,\n isResponsesCapableOpenAIMode"
},
{
"path": "src/common/openai-api-path.ts",
"chars": 888,
"preview": "export const OPENAI_CHAT_COMPLETIONS_API_PATH = '/v1/chat/completions'\nexport const OPENAI_RESPONSES_API_PATH = '/v1/res"
},
{
"path": "src/common/polyfills/electron.ts",
"chars": 2079,
"preview": "/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { "
},
{
"path": "src/common/polyfills/tauri.ts",
"chars": 4090,
"preview": "/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { "
},
{
"path": "src/common/polyfills/userscript.ts",
"chars": 4153,
"preview": "/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { "
},
{
"path": "src/common/services/action.ts",
"chars": 359,
"preview": "import { backgroundActionService } from '../background/services/action'\nimport { IActionInternalService, actionInternalS"
},
{
"path": "src/common/services/history.ts",
"chars": 1406,
"preview": "import {\n CreateHistoryItem,\n HistoryQueryOptions,\n IHistoryInternalService,\n UpdateHistoryPayload,\n hist"
},
{
"path": "src/common/services/promotion.ts",
"chars": 5473,
"preview": "import dayjs from 'dayjs'\nimport { isDesktopApp, isUserscript } from '../utils'\nimport { backgroundGetItem, backgroundRe"
},
{
"path": "src/common/services/vocabulary.ts",
"chars": 367,
"preview": "import { backgroundVocabularyService } from '../background/services/vocabulary'\nimport { IVocabularyInternalService, voc"
},
{
"path": "src/common/store/setting.ts",
"chars": 74,
"preview": "import { atom } from 'jotai'\n\nexport const showSettingsAtom = atom(false)\n"
},
{
"path": "src/common/store.ts",
"chars": 329,
"preview": "import { create } from 'zustand'\n\ninterface ITranslatorState {\n externalOriginalText?: string\n}\n\nexport const useTran"
},
{
"path": "src/common/token.ts",
"chars": 1852,
"preview": "import { encodingForModel, TiktokenModel, Tiktoken } from 'js-tiktoken'\n\nclass Encoding {\n enc: Tiktoken\n\n constru"
},
{
"path": "src/common/traditional-or-simplified.ts",
"chars": 6893,
"preview": "const S =\n '万与丑专业丛东丝丢两严丧个丬丰临为丽举么义乌乐乔习乡书买乱争于亏云亘亚产亩亲亵亸亿仅从仑仓仪们价众优伙会伛伞伟传伤伥伦伧伪伫体余佣佥侠侣侥侦侧侨侩侪侬俣俦俨俩俪俭债倾偬偻偾偿傥傧储傩儿兑兖党兰关兴兹养兽冁内冈册"
},
{
"path": "src/common/translate.ts",
"chars": 17312,
"preview": "/* eslint-disable camelcase */\nimport { v4 as uuidv4 } from 'uuid'\nimport { getLangConfig, getLangName, LangCode } from "
},
{
"path": "src/common/tts/edge-tts.ts",
"chars": 8431,
"preview": "import { langCode2TTSLang } from '.'\nimport { SpeakOptions } from './types'\nimport { EdgeTTS, listVoices } from 'edge-tt"
},
{
"path": "src/common/tts/index.ts",
"chars": 4516,
"preview": "import { DoSpeakOptions, SpeakOptions } from './types'\nimport { getSettings } from '../utils'\nimport { speak as edgeSpea"
},
{
"path": "src/common/tts/types.ts",
"chars": 401,
"preview": "import { LangCode } from '../lang'\n\nexport interface SpeakOptions {\n text: string\n lang?: LangCode\n signal: Abo"
},
{
"path": "src/common/types.ts",
"chars": 4019,
"preview": "import { Theme } from 'baseui-sd/theme'\nimport { TranslateMode } from './translate'\nimport { TTSProvider } from './tts/t"
},
{
"path": "src/common/universal-fetch.ts",
"chars": 343,
"preview": "import { backgroundFetch } from './background/fetch'\nimport { tauriFetch } from './polyfills/tauri'\nimport { userscriptF"
},
{
"path": "src/common/usehooks.ts",
"chars": 958,
"preview": "import { DependencyList, EffectCallback, useCallback, useEffect, useRef } from 'react'\nimport debounce from 'lodash.debo"
},
{
"path": "src/common/user-event.ts",
"chars": 1337,
"preview": "export type UserEventType = MouseEvent | TouchEvent | PointerEvent\n\nexport const getPageX = (event: UserEventType) => {\n"
},
{
"path": "src/common/utils.ts",
"chars": 18394,
"preview": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { createParser } from 'eventsource-parser'\nimport { IBrow"
},
{
"path": "src/index.d.ts",
"chars": 298,
"preview": "/// <reference types=\"@samrum/vite-plugin-web-extension/client\" />\n\ndeclare module '*.png'\ndeclare module '*.gif'\ndeclar"
},
{
"path": "src/tauri/App.tsx",
"chars": 915,
"preview": "/* eslint-disable camelcase */\nimport { WebviewWindow } from '@tauri-apps/api/webviewWindow'\nimport { TranslatorWindow }"
},
{
"path": "src/tauri/bindings.ts",
"chars": 6052,
"preview": "// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manu"
},
{
"path": "src/tauri/components/Window.tsx",
"chars": 8524,
"preview": "import { useCallback, useEffect, useState } from 'react'\nimport { WebviewWindow } from '@tauri-apps/api/webviewWindow'\ni"
},
{
"path": "src/tauri/dummy.html",
"chars": 407,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta\n name=\"viewport\"\n "
},
{
"path": "src/tauri/index.html",
"chars": 2419,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta\n name=\"viewport\"\n "
},
{
"path": "src/tauri/index.tsx",
"chars": 211,
"preview": "import './legacy-tauri-ipc'\nimport { createRoot } from 'react-dom/client'\nimport { App } from './App'\n\nimport '../common"
},
{
"path": "src/tauri/legacy-tauri-ipc.ts",
"chars": 1734,
"preview": "type LegacyInvokePayload = {\n cmd: string\n callback: string\n error: string\n [key: string]: unknown\n}\n\ntype T"
},
{
"path": "src/tauri/utils.ts",
"chars": 4346,
"preview": "import { isRegistered, register, unregister } from '@tauri-apps/plugin-global-shortcut'\nimport { getSettings } from '@/c"
},
{
"path": "src/tauri/windows/ActionManagerWindow.tsx",
"chars": 417,
"preview": "import { useEffect } from 'react'\nimport { ActionManager } from '../../common/components/ActionManager'\nimport { Window "
},
{
"path": "src/tauri/windows/HistoryWindow.tsx",
"chars": 1359,
"preview": "import { useCallback, useEffect } from 'react'\nimport { Window } from '../components/Window'\nimport { TranslationHistory"
},
{
"path": "src/tauri/windows/ScreenshotWindow.tsx",
"chars": 5008,
"preview": "import { trackEvent } from '@aptabase/tauri'\nimport { appCacheDir, join } from '@tauri-apps/api/path'\nimport { convertFi"
},
{
"path": "src/tauri/windows/SettingsWindow.tsx",
"chars": 341,
"preview": "import { InnerSettings } from '../../common/components/Settings'\nimport { Window } from '../components/Window'\nimport { "
},
{
"path": "src/tauri/windows/ThumbWindow.tsx",
"chars": 766,
"preview": "import icon from '@/common/assets/images/icon.png'\nimport { useTheme } from '@/common/hooks/useTheme'\nimport { BaseProvi"
},
{
"path": "src/tauri/windows/TranslatorWindow.tsx",
"chars": 8851,
"preview": "import { useCallback, useEffect, useReducer, useRef, useState } from 'react'\nimport { Translator } from '../../common/co"
},
{
"path": "src/tauri/windows/UpdaterWindow.tsx",
"chars": 14124,
"preview": "import { useEffect, useState } from 'react'\nimport { Window } from '@/tauri/components/Window'\nimport { check } from '@t"
},
{
"path": "src-safari/.gitignore",
"chars": 83,
"preview": "## User settings\nxcuserdata/\n\n## Xcode 8 and earlier\n*.xcscmblueprint\n*.xccheckout\n"
},
{
"path": "src-safari/NextAI Translator.xcodeproj/project.pbxproj",
"chars": 43222,
"preview": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 56;\n\tobjects = {\n\n/* Begin PBXBuildFile section *"
},
{
"path": "src-safari/NextAI Translator.xcodeproj/project.xcworkspace/contents.xcworkspacedata",
"chars": 135,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n version = \"1.0\">\n <FileRef\n location = \"self:\">\n </FileRef"
},
{
"path": "src-safari/NextAI Translator.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
"chars": 238,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "src-safari/Shared (App)/Assets.xcassets/AccentColor.colorset/Contents.json",
"chars": 123,
"preview": "{\n \"colors\" : [\n {\n \"idiom\" : \"universal\"\n }\n ],\n \"info\" : {\n \"author\" : \"xcode\",\n \"version\" : 1\n }"
},
{
"path": "src-safari/Shared (App)/Assets.xcassets/AppIcon.appiconset/Contents.json",
"chars": 1463,
"preview": "{\n \"images\" : [\n {\n \"size\" : \"1024x1024\",\n \"idiom\" : \"universal\",\n \"filename\" : \"universal-icon-1024@"
},
{
"path": "src-safari/Shared (App)/Assets.xcassets/Contents.json",
"chars": 63,
"preview": "{\n \"info\" : {\n \"author\" : \"xcode\",\n \"version\" : 1\n }\n}\n"
},
{
"path": "src-safari/Shared (App)/Assets.xcassets/LargeIcon.imageset/Contents.json",
"chars": 301,
"preview": "{\n \"images\" : [\n {\n \"idiom\" : \"universal\",\n \"scale\" : \"1x\",\n \"filename\" : \"icon.png\"\n },\n {\n "
},
{
"path": "src-safari/Shared (App)/Base.lproj/Main.html",
"chars": 1093,
"preview": "<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <meta http-equ"
},
{
"path": "src-safari/Shared (App)/Resources/Script.js",
"chars": 1384,
"preview": "function show(platform, enabled, useSettingsInsteadOfPreferences) {\n document.body.classList.add(`platform-${platform"
},
{
"path": "src-safari/Shared (App)/Resources/Style.css",
"chars": 954,
"preview": "* {\n -webkit-user-select: none;\n -webkit-user-drag: none;\n cursor: default;\n}\n\n:root {\n color-scheme: light "
}
]
// ... and 53 more files (download for full content)
About this extraction
This page contains the full source code of the nextai-translator/nextai-translator GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 253 files (2.7 MB), approximately 720.1k tokens, and a symbol index with 709 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.