neptune-web commited on
Commit ·
04e85f3
1
Parent(s): a27c5a5
feature(#72): improve the select item functionality and UI/UX
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Extension/LICENSEAdded+21
- Extension/build.mjsDeleted-311
- Extension/package-lock.json
- Extension/package.json+50-76
- Extension/src/_locales/en/main.jsonDeleted-125
- Extension/src/_locales/i18n-react.mjsDeleted-11
- Extension/src/_locales/i18n.mjsDeleted-7
- Extension/src/_locales/resources.mjsDeleted-7
- Extension/src/assets/desc.pngDeleted
- Extension/src/assets/img/icon-128.pngAdded
- Extension/src/assets/img/icon-34.pngAdded
- Extension/src/assets/img/logo.svgAdded
- Extension/src/background/commands.mjsDeleted-27
- Extension/src/background/index.mjsDeleted-77
- Extension/src/background/menus.mjsDeleted-75
- Extension/src/components/ConfirmButton/index.jsxDeleted-58
- Extension/src/components/ConversationCard/index.jsxDeleted-483
- Extension/src/components/ConversationItem/index.jsxDeleted-140
- Extension/src/components/CopyButton/index.jsxDeleted-38
- Extension/src/components/DecisionCard/index.jsxDeleted-125
- Extension/src/components/DeleteButton/index.jsxDeleted-59
- Extension/src/components/FeedbackForChatGPTWeb/index.jsxDeleted-68
- Extension/src/components/FloatingToolbar/index.jsxDeleted-103
- Extension/src/components/InputBox/index.jsxDeleted-117
- Extension/src/components/MarkdownRender/Hyperlink.jsxDeleted-37
- Extension/src/components/MarkdownRender/markdown-without-katex.jsxDeleted-38
- Extension/src/components/MarkdownRender/markdown.jsxDeleted-42
- Extension/src/components/NotificationForChatGPTWeb/index.jsxDeleted-90
- Extension/src/components/ReadButton/index.jsxDeleted-61
- Extension/src/components/index.mjsDeleted-10
- Extension/src/config/index.mjsDeleted-170
- Extension/src/config/language.mjsDeleted-26
- Extension/src/containers/Greetings/Greetings.jsxAdded+19
- Extension/src/content-script/index.jsxDeleted-203
- Extension/src/content-script/menu-tools/index.mjsDeleted-72
- Extension/src/content-script/site-adapters/index.jsxDeleted-23
- Extension/src/content-script/styles.scssDeleted-365
- Extension/src/fonts/SLXVc1nY6HkvangtZmpQdkhzfH5lkSscQyyS4J0.woff2Deleted
- Extension/src/fonts/SLXVc1nY6HkvangtZmpQdkhzfH5lkSscRiyS.woff2Deleted
- Extension/src/fonts/SLXVc1nY6HkvangtZmpQdkhzfH5lkSscSCyS4J0.woff2Deleted
- Extension/src/fonts/styles.cssDeleted-58
- Extension/src/hooks/use-clamp-window-size.mjsDeleted-8
- Extension/src/hooks/use-config.mjsDeleted-30
- Extension/src/hooks/use-theme.mjsDeleted-8
- Extension/src/hooks/use-window-size.mjsDeleted-16
- Extension/src/hooks/use-window-theme.mjsDeleted-21
- Extension/src/logo.pngDeleted
- Extension/src/logo1.pngDeleted
- Extension/src/manifest.json+22-69
- Extension/src/pages/Background/index.jsAdded+17
123456789101112131415161718192021The MIT License (MIT)
Copyright (c) 2019 Michael Xieyang Liu
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311import archiver from 'archiver'import fs from 'fs-extra'import path from 'path'import webpack from 'webpack'import ProgressBarPlugin from 'progress-bar-webpack-plugin'import CssMinimizerPlugin from 'css-minimizer-webpack-plugin'import MiniCssExtractPlugin from 'mini-css-extract-plugin'import TerserPlugin from 'terser-webpack-plugin'import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
const outdir = 'build'
const __dirname = path.resolve()const isProduction = process.argv[2] !== '--development' // --production and --analyze are both productionconst isAnalyzing = process.argv[2] === '--analyze'
async function deleteOldDir() { await fs.rm(outdir, { recursive: true, force: true })}
async function runWebpack(isWithoutKatex, isWithoutTiktoken, callback) { const shared = [ 'preact', 'webextension-polyfill', '@primer/octicons-react', 'react-bootstrap-icons', 'i18next', 'react-i18next', 'react-tabs', './src/utils', './src/_locales/i18n-react', ] if (isWithoutKatex) shared.push('./src/components')
const compiler = webpack({ entry: { 'content-script': { import: './src/content-script/index.jsx', dependOn: 'shared', }, background: { import: './src/background/index.mjs', }, popup: { import: './src/popup/index.jsx', dependOn: 'shared', }, IndependentPanel: { import: './src/pages/IndependentPanel/index.jsx', dependOn: 'shared', }, shared: shared, }, output: { filename: '[name].js', path: path.resolve(__dirname, outdir), }, mode: isProduction ? 'production' : 'development', devtool: isProduction ? false : 'inline-source-map', optimization: { minimizer: [ new TerserPlugin({ terserOptions: { output: { ascii_only: true }, }, }), new CssMinimizerPlugin(), ], concatenateModules: !isAnalyzing, }, plugins: [ new ProgressBarPlugin({ format: ' build [:bar] :percent (:elapsed seconds)', clear: false, }), new MiniCssExtractPlugin({ filename: '[name].css', }), new BundleAnalyzerPlugin({ analyzerMode: isAnalyzing ? 'static' : 'disable', }), ...(isWithoutKatex ? [ new webpack.NormalModuleReplacementPlugin(/markdown\.jsx/, (result) => { if (result.request) { result.request = result.request.replace( 'markdown.jsx', 'markdown-without-katex.jsx', ) } }), ] : []), ], resolve: { extensions: ['.jsx', '.mjs', '.js'], alias: { parse5: path.resolve(__dirname, 'node_modules/parse5'), }, }, module: { rules: [ { test: /\.m?jsx?$/, exclude: /(node_modules)/, resolve: { fullySpecified: false, }, use: [ { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', { plugins: ['@babel/plugin-transform-runtime'], }, ], plugins: [ [ '@babel/plugin-transform-react-jsx', { runtime: 'automatic', importSource: 'preact', }, ], ], }, }, ], }, { test: /\.s[ac]ss$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { importLoaders: 1, }, }, { loader: 'sass-loader', }, ], }, { test: /\.less$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { importLoaders: 1, }, }, { loader: 'less-loader', }, ], }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', }, ], }, { test: /\.(woff|ttf)$/, type: 'asset/resource', generator: { emit: false, }, }, { test: /\.woff2$/, type: 'asset/inline', }, { test: /\.(jpg|png|svg)$/, type: 'asset/inline', }, { test: /\.(graphql|gql)$/, loader: 'graphql-tag/loader', }, isWithoutTiktoken ? { test: /crop-text\.mjs$/, loader: 'string-replace-loader', options: { multiple: [ { search: "import { encode } from '@nem035/gpt-3-encoder'", replace: '', }, { search: 'encode(', replace: 'String(', }, ], }, } : {}, isWithoutKatex && isWithoutTiktoken ? { test: /styles\.scss$/, loader: 'string-replace-loader', options: { multiple: [ { search: "@import '../fonts/styles.css';", replace: '', }, ], }, } : {}, ], }, }) if (isProduction) compiler.run(callback) else compiler.watch({}, callback)}
async function zipFolder(dir) { const output = fs.createWriteStream(`${dir}.zip`) const archive = archiver('zip', { zlib: { level: 9 }, }) archive.pipe(output) archive.directory(dir, false) await archive.finalize()}
async function copyFiles(entryPoints, targetDir) { if (!fs.existsSync(targetDir)) await fs.mkdir(targetDir) await Promise.all( entryPoints.map(async (entryPoint) => { await fs.copy(entryPoint.src, `${targetDir}/${entryPoint.dst}`) }), )}
async function finishOutput(outputDirSuffix) { const commonFiles = [ { src: 'src/logo1.png', dst: 'logo1.png' },
{ src: 'build/shared.js', dst: 'shared.js' }, { src: 'build/content-script.css', dst: 'content-script.css' }, // shared
{ src: 'build/content-script.js', dst: 'content-script.js' },
{ src: 'build/background.js', dst: 'background.js' },
{ src: 'build/popup.js', dst: 'popup.js' }, { src: 'build/popup.css', dst: 'popup.css' }, { src: 'src/popup/index.html', dst: 'popup.html' },
{ src: 'build/IndependentPanel.js', dst: 'IndependentPanel.js' }, { src: 'src/pages/IndependentPanel/index.html', dst: 'IndependentPanel.html' }, ]
// chromium const chromiumOutputDir = `./${outdir}/chromium${outputDirSuffix}` await copyFiles( [...commonFiles, { src: 'src/manifest.json', dst: 'manifest.json' }], chromiumOutputDir, ) if (isProduction) await zipFolder(chromiumOutputDir)}
function generateWebpackCallback(finishOutputFunc) { return async function webpackCallback(err, stats) { if (err || stats.hasErrors()) { console.error(err || stats.toString()) return } // console.log(stats.toString())
await finishOutputFunc() }}
async function build() { await deleteOldDir() if (isProduction && !isAnalyzing) { await runWebpack( true, false, generateWebpackCallback(() => finishOutput('-without-katex')), ) await new Promise((r) => setTimeout(r, 5000)) await runWebpack( true, true, generateWebpackCallback(() => finishOutput('-without-katex-and-tiktoken')), ) await new Promise((r) => setTimeout(r, 5000)) } await runWebpack( false, false, generateWebpackCallback(() => finishOutput('')), )}
build()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586{"name": "RisingBrowser","scripts": {"build": "node build.mjs --production","dev": "node build.mjs --development","analyze": "node build.mjs --analyze","lint": "eslint --ext .js,.mjs,.jsx .","lint:fix": "eslint --ext .js,.mjs,.jsx . --fix","pretty": "prettier --write ./**/*.{js,mjs,jsx,json,css,scss}","stage": "run-script-os","stage:default": "git add $(git diff --name-only --cached --diff-filter=d)","stage:win32": "powershell git add $(git diff --name-only --cached --diff-filter=d)","verify": "node .github/workflows/scripts/verify-search-engine-configs.mjs"},"pre-commit": ["pretty","stage","lint"],"dependencies": {"@nem035/gpt-3-encoder": "^1.1.7","@picocss/pico": "^1.5.9","@primer/octicons-react": "^18.3.0","diff": "^5.1.0","eventsource-parser": "^1.0.0","file-saver": "^2.0.5","github-markdown-css": "^5.2.0","gpt-3-encoder": "^1.1.4","graphql": "^16.6.0","i18next": "^22.4.15","katex": "^0.16.6","lodash-es": "^4.17.21","md5": "^2.3.0","parse5": "^6.0.1","preact": "^10.13.2","prop-types": "^15.8.1","react": "npm:@preact/compat@^17.1.2","react-bootstrap-icons": "^1.10.3","react-dom": "npm:@preact/compat@^17.1.2","react-draggable": "^4.4.5","react-i18next": "^12.2.0","react-markdown": "^8.0.7","react-tabs": "^4.2.1","react-toastify": "^9.1.2","rehype-highlight": "^6.0.0","rehype-katex": "^6.0.2","rehype-raw": "^6.1.1","remark-breaks": "^3.0.2","remark-gfm": "^3.0.1","remark-math": "^5.1.1","uuid": "^9.0.0","webextension-polyfill": "^0.10.0"},"devDependencies": {"@babel/core": "^7.21.4","@babel/plugin-transform-react-jsx": "^7.21.0","@babel/plugin-transform-runtime": "^7.21.4","@babel/preset-env": "^7.21.4","@types/archiver": "^5.3.2","@types/fs-extra": "^11.0.1","@types/jsdom": "^21.1.1","@types/webextension-polyfill": "^0.10.0","archiver": "^5.3.1","babel-loader": "^9.1.2","css-loader": "^6.7.3","css-minimizer-webpack-plugin": "^5.0.0","eslint": "^8.39.0","eslint-plugin-react": "^7.32.2","fs-extra": "^11.1.1","graphql-tag": "^2.12.6","jsdom": "^21.1.1","less-loader": "^11.1.0","mini-css-extract-plugin": "^2.7.5","node-fetch": "^3.3.1","pre-commit": "^1.2.2","prettier": "^2.8.7","progress-bar-webpack-plugin": "^2.1.0","run-script-os": "^1.1.6","sass": "^1.62.0","sass-loader": "^13.2.2","string-replace-loader": "^3.1.0","terser-webpack-plugin": "^5.3.7","webpack": "^5.80.0","webpack-bundle-analyzer": "^4.8.0"}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960{"name": "rising-browser","version": "1.0.0","description": "A chatbot chrome extension was developed by Saeid Nobahari.","license": "MIT","scripts": {"build": "node utils/build.js","start": "node utils/webserver.js","prettier": "prettier --write '**/*.{js,jsx,ts,tsx,json,css,scss,md}'"},"dependencies": {"@ant-design/icons": "^5.1.4","antd": "^5.3.2","axios": "^1.4.0","react": "^18.2.0","react-dom": "^18.2.0"},"devDependencies": {"@babel/core": "^7.20.12","@babel/plugin-proposal-class-properties": "^7.18.6","@babel/preset-env": "^7.20.2","@babel/preset-react": "^7.18.6","@pmmmwh/react-refresh-webpack-plugin": "^0.5.10","@types/chrome": "^0.0.202","@types/react": "^18.0.26","@types/react-dom": "^18.0.10","babel-eslint": "^10.1.0","babel-loader": "^9.1.2","babel-preset-react-app": "^10.0.1","clean-webpack-plugin": "^4.0.0","copy-webpack-plugin": "^11.0.0","css-loader": "^6.7.3","eslint": "^8.31.0","eslint-config-react-app": "^7.0.1","eslint-plugin-flowtype": "^8.0.3","eslint-plugin-import": "^2.27.4","eslint-plugin-jsx-a11y": "^6.7.1","eslint-plugin-react": "^7.32.0","eslint-plugin-react-hooks": "^4.6.0","file-loader": "^6.2.0","fs-extra": "^11.1.0","html-loader": "^4.2.0","html-webpack-plugin": "^5.5.0","prettier": "^2.8.3","react-refresh": "^0.14.0","react-refresh-typescript": "^2.0.7","sass": "^1.57.1","sass-loader": "^13.2.0","source-map-loader": "^3.0.1","style-loader": "^3.3.1","terser-webpack-plugin": "^5.3.6","ts-loader": "^9.4.2","type-fest": "^3.5.2","typescript": "^4.9.4","webpack": "^5.75.0","webpack-cli": "^4.10.0","webpack-dev-server": "^4.11.1","zip-webpack-plugin": "^4.0.1"}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125{ "General": "General", "Selection Tools": "Selection Tools", "Sites": "Sites", "Advanced": "Advanced", "Donate": "Donate", "Triggers": "Triggers", "Theme": "Theme", "API Mode": "API Mode", "Get": "Get", "Balance": "Balance", "Preferred Language": "Preferred Language", "Insert ChatGPT at the top of search results": "Insert ChatGPT at the top of search results", "Lock scrollbar while answering": "Lock scrollbar while answering", "Current Version": "Current Version", "Latest": "Latest", "Help | Changelog ": "Help | Changelog ", "Custom ChatGPT Web API Url": "Custom ChatGPT Web API Url", "Custom ChatGPT Web API Path": "Custom ChatGPT Web API Path", "Custom OpenAI API Url": "Custom OpenAI API Url", "Custom Site Regex": "Custom Site Regex", "Exclusively use Custom Site Regex for website matching, ignoring built-in rules": "Exclusively use Custom Site Regex for website matching, ignoring built-in rules", "Input Query": "Input Query", "Append Query": "Append Query", "Prepend Query": "Prepend Query", "Wechat Pay": "Wechat Pay", "Type your question here\nEnter to send, shift + enter to break line": "Type your question here\nEnter to send\nShift + enter to break line", "Type your question here\nEnter to stop generating\nShift + enter to break line": "Type your question here\nEnter to stop generating\nShift + enter to break line", "Ask ChatGPT": "Ask ChatGPT", "No Input Found": "No Input Found", "You": "You", "Collapse": "Collapse", "Expand": "Expand", "Stop": "Stop", "Continue on official website": "Continue on official website", "Error": "Error", "Copy": "Copy", "Question": "Question", "Answer": "Answer", "Waiting for response...": "Waiting for response...", "Close the Window": "Close the Window", "Pin the Window": "Pin the Window", "Float the Window": "Float the Window", "Save Conversation": "Save Conversation", "UNAUTHORIZED": "UNAUTHORIZED", "Please login at https://chat.openai.com first": "Please login at https://chat.openai.com first", "Then open https://chat.openai.com/api/auth/session": "Then open https://chat.openai.com/api/auth/session", "And refresh this page or type you question again": "And click the retry button in the top right corner", "Consider creating an api key at https://platform.openai.com/account/api-keys": "Consider creating an api key at https://platform.openai.com/account/api-keys", "OpenAI Security Check Required": "OpenAI Security Check Required", "Please open https://chat.openai.com/api/auth/session": "Please open https://chat.openai.com/api/auth/session", "Please open https://chat.openai.com": "Please open https://chat.openai.com", "New Chat": "New Chat", "Summarize Page": "Summarize Page", "Translate": "Translate", "Translate (Bidirectional)": "Translate (Bidirectional)", "Translate (To English)": "Translate (To English)", "Summary": "Summary", "Polish": "Polish", "Sentiment Analysis": "Sentiment Analysis", "Divide Paragraphs": "Divide Paragraphs", "Code Explain": "Code Explain", "Ask": "Ask", "Always": "Always", "Manually": "Manually", "When query ends with question mark (?)": "When query ends with question mark (?)", "Light": "Light", "Dark": "Dark", "Auto": "Auto", "ChatGPT (Web)": "ChatGPT (Web)", "ChatGPT (Web, GPT-4)": "ChatGPT (Web, GPT-4)", "Bing (Web, GPT-4)": "Bing (Web, GPT-4)", "ChatGPT (GPT-3.5-turbo)": "ChatGPT (GPT-3.5-turbo)", "ChatGPT (GPT-4-8k)": "ChatGPT (GPT-4-8k)", "ChatGPT (GPT-4-32k)": "ChatGPT (GPT-4-32k)", "GPT-3.5": "GPT-3.5", "Custom Model": "Custom Model", "Balanced": "Balanced", "Creative": "Creative", "Precise": "Precise", "Fast": "Fast", "API Key": "API Key", "Model Name": "Model Name", "Custom Model API Url": "Custom Model API Url", "Loading...": "Loading...", "Feedback": "Feedback", "Confirm": "Confirm", "Clear Conversation": "Clear Conversation", "Retry": "Retry", "Exceeded maximum context length": "Exceeded maximum context length, please clear the conversation and try again", "Regenerate the answer after switching model": "Regenerate the answer after switching model", "Pin": "Pin", "Unpin": "Unpin", "Delete Conversation": "Delete Conversation", "Clear conversations": "Clear conversations", "Settings": "Settings", "Feature Pages": "Feature Pages", "Keyboard Shortcuts": "Keyboard Shortcuts", "Open Conversation Page": "Open Conversation Page", "Open Conversation Window": "Open Conversation Window", "Store to Independent Conversation Page": "Store to Independent Conversation Page", "Keep Conversation Window in Background": "Keep conversation window in background, so that you can use shortcut keys to call it up in any program", "Max Response Token Length": "Max Response Token Length", "Max Conversation Length": "Max Conversation Length", "Always pin the floating window": "Always pin the floating window", "Export": "Export", "Always Create New Conversation Window": "Always Create New Conversation Window", "Please keep this tab open. You can now use the web mode of ChatGPTBox": "Please keep this tab open. You can now use the web mode of ChatGPTBox", "Go Back": "Go Back", "Pin Tab": "Pin Tab", "Modules": "Modules", "API Params": "API Params", "API Url": "API Url", "Others": "Others", "API Modes": "API Modes", "Disable web mode history for better privacy protection, but it will result in unavailable conversations after a period of time": "Disable web mode history for better privacy protection, but it will result in unavailable conversations after a period of time", "Display selection tools next to input box to avoid blocking": "Display selection tools next to input box to avoid blocking", "Close All Chats In This Page": "Close All Chats In This Page", "When Icon Clicked": "When Icon Clicked", "Open Settings": "Open Settings", "Focus to input box after answering": "Focus to input box after answering", "Bing CaptchaChallenge": "You must pass Bing's verification. Please go to https://www.bing.com/search?q=Bing+AI&showconv=1&FORM=hpcodx and send a message", "Exceeded quota": "You exceeded your current quota, check https://platform.openai.com/account/usage", "Rate limit": "Rate limit exceeded"}1234567891011import i18n from 'i18next'import { initReactI18next } from 'react-i18next'import { resources } from './resources'
i18n.use(initReactI18next).init({ resources, fallbackLng: 'en', interpolation: { escapeValue: false, // not needed for react as it escapes by default },})1234567import i18n from 'i18next'import { resources } from './resources'
i18n.init({ resources, fallbackLng: 'en',})1234567import en from './en/main.json'
export const resources = { en: { translation: en, },}123456789101112131415161718192021222324252627import Browser from 'webextension-polyfill'import { config as menuConfig } from '../content-script/menu-tools/index.mjs'
export function registerCommands() { Browser.commands.onCommand.addListener(async (command) => { const message = { itemId: command, selectionText: '', useMenuPosition: false, } console.debug('command triggered', message)
if (command in menuConfig) { if (menuConfig[command].action) { menuConfig[command].action(true) }
if (menuConfig[command].genPrompt) { const currentTab = (await Browser.tabs.query({ active: true, currentWindow: true }))[0] Browser.tabs.sendMessage(currentTab.id, { type: 'CREATE_CHAT', data: message, }) } } })}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import Browser from 'webextension-polyfill'import { getUserConfig, setUserConfig } from '../config/index.mjs'import '../_locales/i18n'import { openUrl } from '../utils/open-url'import { registerPortListener } from '../services/wrappers.mjs'import { refreshMenu } from './menus.mjs'import { registerCommands } from './commands.mjs'import { getManagementBrowser } from '../services/apis/rising-api.mjs'
async function executeApi(session, port, config) { // ### the part for integrating with backend ### console.debug('config', config) await getManagementBrowser(port, session.question, session, '')}
Browser.runtime.onMessage.addListener(async (message, sender) => { switch (message.type) { case 'NEW_URL': { const newTab = await Browser.tabs.create({ url: message.data.url, pinned: message.data.pinned, }) if (message.data.saveAsChatgptConfig) { await setUserConfig({ chatgptTabId: newTab.id, chatgptJumpBackTabId: sender.tab.id, }) } break } case 'SET_CHATGPT_TAB': { await setUserConfig({ chatgptTabId: sender.tab.id, }) break } case 'ACTIVATE_URL': await Browser.tabs.update(message.data.tabId, { active: true }) break case 'OPEN_URL': openUrl(message.data.url) break case 'OPEN_CHAT_WINDOW': { const config = await getUserConfig() const url = Browser.runtime.getURL('IndependentPanel.html') const tabs = await Browser.tabs.query({ url: url, windowType: 'popup' }) if (!config.alwaysCreateNewConversationWindow && tabs.length > 0) await Browser.windows.update(tabs[0].windowId, { focused: true }) else await Browser.windows.create({ url: url, type: 'popup', width: 500, height: 650, }) break } case 'REFRESH_MENU': refreshMenu() break case 'PIN_TAB': { let tabId if (message.data.tabId) tabId = message.data.tabId else tabId = sender.tab.id
await Browser.tabs.update(tabId, { pinned: true }) if (message.data.saveAsChatgptConfig) { await setUserConfig({ chatgptTabId: tabId }) } break } }})
registerPortListener(async (session, port, config) => await executeApi(session, port, config))registerCommands()refreshMenu()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import Browser from 'webextension-polyfill'import { defaultConfig, getPreferredLanguageKey } from '../config/index.mjs'import { changeLanguage, t } from 'i18next'import { config as menuConfig } from '../content-script/menu-tools/index.mjs'
export function refreshMenu() { Browser.contextMenus.removeAll().then(async () => { await getPreferredLanguageKey().then((lang) => { changeLanguage(lang) }) const menuId = 'ChatGPTBox-Menu' Browser.contextMenus.create({ id: menuId, title: 'RisingBrowser', contexts: ['all'], })
for (const [k, v] of Object.entries(menuConfig)) { Browser.contextMenus.create({ id: menuId + k, parentId: menuId, title: t(v.label), contexts: ['all'], }) }
Browser.contextMenus.create({ id: menuId + 'separator1', parentId: menuId, contexts: ['selection'], type: 'separator', })
for (const index in defaultConfig.selectionTools) { const key = defaultConfig.selectionTools[index] const desc = defaultConfig.selectionToolsDesc[index] Browser.contextMenus.create({ id: menuId + key, parentId: menuId, title: t(desc), contexts: ['selection'], }) }
Browser.contextMenus.onClicked.addListener((info, tab) => { Browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => { const currentTab = tabs[0] const message = { itemId: info.menuItemId.replace(menuId, ''), selectionText: info.selectionText, useMenuPosition: tab.id === currentTab.id, } console.debug('menu clicked', message)
if (defaultConfig.selectionTools.includes(message.itemId)) { Browser.tabs.sendMessage(currentTab.id, { type: 'CREATE_CHAT', data: message, }) } else if (message.itemId in menuConfig) { if (menuConfig[message.itemId].action) { menuConfig[message.itemId].action(true) }
if (menuConfig[message.itemId].genPrompt) { Browser.tabs.sendMessage(currentTab.id, { type: 'CREATE_CHAT', data: message, }) } } }) }) })}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import { useTranslation } from 'react-i18next'import { useEffect, useRef, useState } from 'react'import PropTypes from 'prop-types'
ConfirmButton.propTypes = { onConfirm: PropTypes.func.isRequired, text: PropTypes.string.isRequired,}
function ConfirmButton({ onConfirm, text }) { const { t } = useTranslation() const [waitConfirm, setWaitConfirm] = useState(false) const confirmRef = useRef(null)
useEffect(() => { if (waitConfirm) confirmRef.current.focus() }, [waitConfirm])
return ( <span> <button ref={confirmRef} type="button" className="normal-button" style={{ ...(waitConfirm ? {} : { display: 'none' }), }} onMouseDown={(e) => { e.preventDefault() e.stopPropagation() }} onBlur={() => { setWaitConfirm(false) }} onClick={() => { setWaitConfirm(false) onConfirm() }} > {t('Confirm')} </button> <button type="button" className="normal-button" style={{ ...(waitConfirm ? { display: 'none' } : {}), }} onClick={() => { setWaitConfirm(true) }} > {text} </button> </span> )}
export default ConfirmButton123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483import { memo, useEffect, useRef, useState } from 'react'import PropTypes from 'prop-types'import Browser from 'webextension-polyfill'import InputBox from '../InputBox'import ConversationItem from '../ConversationItem'import { createElementAtPosition } from '../../utils'import { DownloadIcon, LinkExternalIcon, ArchiveIcon } from '@primer/octicons-react'import { WindowDesktop, XLg, Pin } from 'react-bootstrap-icons'import FileSaver from 'file-saver'import { render } from 'preact'import FloatingToolbar from '../FloatingToolbar'import { useClampWindowSize } from '../../hooks/use-clamp-window-size'import { ModelMode, Models } from '../../config/index.mjs'import { useTranslation } from 'react-i18next'import DeleteButton from '../DeleteButton'import { useConfig } from '../../hooks/use-config.mjs'import { createSession } from '../../services/local-session.mjs'import { v4 as uuidv4 } from 'uuid'import { initSession } from '../../services/init-session.mjs'import { findLastIndex } from 'lodash-es'
const logo = Browser.runtime.getURL('logo1.png')
class ConversationItemData extends Object { /** * @param {'question'|'answer'|'error'} type * @param {string} content * @param {bool} done */ constructor(type, content, done = false) { super() this.type = type this.content = content this.done = done }}
function ConversationCard(props) { const { t } = useTranslation() const [isReady, setIsReady] = useState(!props.question) const [port, setPort] = useState(() => Browser.runtime.connect()) const [session, setSession] = useState(props.session) const windowSize = useClampWindowSize([750, 1500], [250, 1100]) const bodyRef = useRef(null)
/** * @type {[ConversationItemData[], (conversationItemData: ConversationItemData[]) => void]} */ const [conversationItemData, setConversationItemData] = useState( (() => { if (session.conversationRecords.length === 0) if (props.question) return [ new ConversationItemData( 'answer', `<p class="gpt-loading">${t(`Waiting for response...`)}</p>`, ), ] else return [] else { const ret = [] for (const record of session.conversationRecords) { ret.push(new ConversationItemData('question', record.question, true)) ret.push(new ConversationItemData('answer', record.answer, true)) } return ret } })(), ) const config = useConfig()
useEffect(() => { if (props.onUpdate) props.onUpdate(port, session, conversationItemData) }, [session, conversationItemData])
useEffect(() => { bodyRef.current.scrollTop = bodyRef.current.scrollHeight }, [session])
useEffect(() => { if (config.lockWhenAnswer) bodyRef.current.scrollTop = bodyRef.current.scrollHeight }, [conversationItemData])
useEffect(() => { // when the page is responsive, session may accumulate redundant data and needs to be cleared after remounting and before making a new request if (props.question) { const newSession = initSession({ question: props.question }) setSession(newSession) port.postMessage({ session: newSession }) } }, [props.question]) // usually only triggered once
/** * @param {string} value * @param {boolean} appended * @param {'question'|'answer'|'error'} newType * @param {boolean} done */ const updateAnswer = (value, appended, newType, done = false) => { setConversationItemData((old) => { const copy = [...old] const index = findLastIndex(copy, (v) => v.type === 'answer' || v.type === 'error') if (index === -1) return copy copy[index] = new ConversationItemData( newType, appended ? copy[index].content + value : value, ) copy[index].done = done return copy }) }
useEffect(() => { const portListener = () => { setPort(Browser.runtime.connect()) setIsReady(true) }
const closeChatsListener = (message) => { if (message.type === 'CLOSE_CHATS') { port.disconnect() if (props.onClose) props.onClose() } }
if (props.closeable) Browser.runtime.onMessage.addListener(closeChatsListener) port.onDisconnect.addListener(portListener) return () => { if (props.closeable) Browser.runtime.onMessage.removeListener(closeChatsListener) port.onDisconnect.removeListener(portListener) } }, [port])
useEffect(() => { const listener = (msg) => { let answer = {} if (msg.answer) answer = JSON.parse(msg.answer?.replace(/'/g, '"'))
if (answer?.program) { /** * Tab and Page Manage - Open, Search, Close, Next/Previous Page, Scroll */ const search = answer?.content let page = 0 const currentUrl = window.location.href
switch (answer.program) { case 'open_tab': window.open('https://google.com/search?q=', '_blank', 'noreferrer') break case 'open_tab_search': window.open('https://google.com/search?q=' + search, '_blank', 'noreferrer') break case 'close_tab': //window.focus() window.close() break case 'previous_page': if (page === 0) { page = 0 } else { page -= 10 }
window.location.assign(currentUrl + '&start=' + page) break case 'next_page': page += 10
window.location.assign(currentUrl + '&start=' + page) break case 'scroll_up': window.scrollBy(0, -300) break case 'scroll_down': window.scrollBy(0, 300) break case 'scroll_top': window.scrollTo(0, 0) break case 'scroll_bottom': window.scrollTo(0, document.body.scrollHeight) break default: break }
updateAnswer(answer.program, false, 'answer') }
if (msg.session) { if (msg.done) msg.session = { ...msg.session, isRetry: false } setSession(msg.session) }
if (msg.done) { updateAnswer('', true, 'answer', true) setIsReady(true) }
if (msg.error) { switch (msg.error) { case 'UNAUTHORIZED': updateAnswer( `${t('UNAUTHORIZED')}<br>${t('Please login at https://chat.openai.com first')} <br>${t('And refresh this page or type you question again')}` + `<br><br>${t( 'Consider creating an api key at https://platform.openai.com/account/api-keys', )}`, false, 'error', ) break case 'CLOUDFLARE': updateAnswer( `${t('OpenAI Security Check Required')}<br><br>${t( 'And refresh this page or type you question again', )}` + `<br><br>${t( 'Consider creating an api key at https://platform.openai.com/account/api-keys', )}`, false, 'error', ) break default: if ( conversationItemData[conversationItemData.length - 1].content.includes('gpt-loading') ) updateAnswer(msg.error, false, 'error') else setConversationItemData([ ...conversationItemData, new ConversationItemData('error', msg.error), ]) break } setIsReady(true) } } port.onMessage.addListener(listener) return () => { port.onMessage.removeListener(listener) } }, [conversationItemData])
const getRetryFn = (session) => () => { updateAnswer(`<p class="gpt-loading">${t('Waiting for response...')}</p>`, false, 'answer') setIsReady(false)
const newSession = { ...session, isRetry: true } setSession(newSession) try { port.postMessage({ stop: true }) port.postMessage({ session: newSession }) } catch (e) { updateAnswer(e, false, 'error') } }
return ( <div className="gpt-inner"> <div className={props.draggable ? 'gpt-header draggable' : 'gpt-header'} style="padding:15px;user-select:none;" > <span className="gpt-util-group" style={props.notClampSize ? {} : { flexGrow: 1 }}> {props.closeable ? ( <XLg className="gpt-util-icon" title={t('Close the Window')} size={16} onClick={() => { port.disconnect() if (props.onClose) props.onClose() }} /> ) : props.dockable ? ( <Pin className="gpt-util-icon" title={t('Pin the Window')} size={16} onClick={() => { if (props.onDock) props.onDock() }} /> ) : ( <img src={logo} style="user-select:none;width:20px;height:20px;" alt="no image" /> )} <select style={props.notClampSize ? {} : { width: 0, flexGrow: 1 }} className="normal-button" required onChange={(e) => { const modelName = e.target.value const newSession = { ...session, modelName, aiName: Models[modelName].desc } if (config.autoRegenAfterSwitchModel && conversationItemData.length > 0) getRetryFn(newSession)() else setSession(newSession) }} > {config.activeApiModes.map((modelName) => { let desc if (modelName.includes('-')) { const splits = modelName.split('-') if (splits[0] in Models) desc = `${t(Models[splits[0]].desc)} (${t(ModelMode[splits[1]])})` } else { if (modelName in Models) desc = t(Models[modelName].desc) } if (desc) return ( <option value={modelName} key={modelName} selected={modelName === session.modelName} > {desc} </option> ) })} </select> </span> <span className="gpt-util-group" style={{ flexGrow: 1, justifyContent: 'flex-end' }}> {session && session.conversationId && ( <a title={t('Continue on official website')} href={'https://chat.openai.com/chat/' + session.conversationId} target="_blank" rel="nofollow noopener noreferrer" className="gpt-util-icon" style="color: inherit;" > <LinkExternalIcon size={16} /> </a> )} <WindowDesktop className="gpt-util-icon" title={t('Float the Window')} size={16} onClick={() => { const position = { x: window.innerWidth / 2 - 300, y: window.innerHeight / 2 - 200 } const toolbarContainer = createElementAtPosition(position.x, position.y) toolbarContainer.className = 'chatgptbox-toolbar-container-not-queryable' render( <FloatingToolbar session={session} selection="" container={toolbarContainer} closeable={true} triggered={true} />, toolbarContainer, ) }} /> <DeleteButton size={16} text={t('Clear Conversation')} onConfirm={() => { port.postMessage({ stop: true }) Browser.runtime.sendMessage({ type: 'DELETE_CONVERSATION', data: { conversationId: session.conversationId, }, }) setConversationItemData([]) const newSession = initSession({ ...session, question: null, conversationRecords: [], }) newSession.sessionId = session.sessionId setSession(newSession) }} /> {!props.pageMode && ( <span title={t('Store to Independent Conversation Page')} className="gpt-util-icon" onClick={() => { const newSession = { ...session, sessionName: new Date().toLocaleString(), autoClean: false, sessionId: uuidv4(), } setSession(newSession) createSession(newSession).then(() => Browser.runtime.sendMessage({ type: 'OPEN_URL', data: { url: Browser.runtime.getURL('IndependentPanel.html'), }, }), ) }} > <ArchiveIcon size={16} /> </span> )} <span title={t('Save Conversation')} className="gpt-util-icon" onClick={() => { let output = '' session.conversationRecords.forEach((data) => { output += `${t('Question')}:\n\n${data.question}\n\n${t('Answer')}:\n\n${ data.answer }\n\n<hr/>\n\n` }) const blob = new Blob([output], { type: 'text/plain;charset=utf-8' }) FileSaver.saveAs(blob, 'conversation.md') }} > <DownloadIcon size={16} /> </span> </span> </div> <hr /> <div ref={bodyRef} className="markdown-body" style={ props.notClampSize ? { flexGrow: 1 } : { maxHeight: windowSize[1] * 0.55 + 'px', resize: 'vertical' } } > {conversationItemData.map((data, idx) => ( <ConversationItem content={data.content} key={idx} type={data.type} session={session} done={data.done} port={port} onRetry={idx === conversationItemData.length - 1 ? getRetryFn(session) : null} /> ))} </div> <InputBox enabled={isReady} port={port} reverseResizeDir={props.pageMode} onSubmit={(question) => { console.log('new quetion------------->', question) const newQuestion = new ConversationItemData('question', question) const newAnswer = new ConversationItemData( 'answer', `<p class="gpt-loading">${t('Waiting for response...')}</p>`, ) setConversationItemData([...conversationItemData, newQuestion, newAnswer]) setIsReady(false)
const newSession = { ...session, question, isRetry: false } setSession(newSession) try { port.postMessage({ session: newSession }) } catch (e) { updateAnswer(e, false, 'error') } }} /> </div> )}
ConversationCard.propTypes = { session: PropTypes.object.isRequired, question: PropTypes.string.isRequired, onUpdate: PropTypes.func, draggable: PropTypes.bool, closeable: PropTypes.bool, onClose: PropTypes.func, dockable: PropTypes.bool, onDock: PropTypes.func, notClampSize: PropTypes.bool, pageMode: PropTypes.bool,}
export default memo(ConversationCard)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import { useState } from 'react'import { ChevronDownIcon, XCircleIcon, SyncIcon } from '@primer/octicons-react'import CopyButton from '../CopyButton'import ReadButton from '../ReadButton'import PropTypes from 'prop-types'import MarkdownRender from '../MarkdownRender/markdown.jsx'import { useTranslation } from 'react-i18next'
export function ConversationItem({ type, content, session, done, port, onRetry }) { const { t } = useTranslation() const [collapsed, setCollapsed] = useState(false)
switch (type) { case 'question': return ( <div className={type} dir="auto"> <div className="gpt-header"> <p>{t('You')}:</p> <div className="gpt-util-group"> <CopyButton contentFn={() => content.replace(/\n<hr\/>$/, '')} size={14} /> <ReadButton contentFn={() => content} size={14} /> {!collapsed ? ( <span title={t('Collapse')} className="gpt-util-icon" onClick={() => setCollapsed(true)} > <XCircleIcon size={14} /> </span> ) : ( <span title={t('Expand')} className="gpt-util-icon" onClick={() => setCollapsed(false)} > <ChevronDownIcon size={14} /> </span> )} </div> </div> {!collapsed && <MarkdownRender>{content}</MarkdownRender>} </div> ) case 'answer': return ( <div className={type} dir="auto"> <div className="gpt-header"> <p style="white-space: nowrap;"> {session && session.aiName ? `${t(session.aiName)}` : t('Loading...')} </p> <div className="gpt-util-group"> {!done && ( <button type="button" className="normal-button" onClick={() => { port.postMessage({ stop: true }) }} > {t('Stop')} </button> )} {onRetry && ( <span title={t('Retry')} className="gpt-util-icon" onClick={onRetry}> <SyncIcon size={14} /> </span> )} {session && ( <CopyButton contentFn={() => content.replace(/\n<hr\/>$/, '')} size={14} /> )} {session && <ReadButton contentFn={() => content} size={14} />} {!collapsed ? ( <span title={t('Collapse')} className="gpt-util-icon" onClick={() => setCollapsed(true)} > <XCircleIcon size={14} /> </span> ) : ( <span title={t('Expand')} className="gpt-util-icon" onClick={() => setCollapsed(false)} > <ChevronDownIcon size={14} /> </span> )} </div> </div> {!collapsed && <MarkdownRender>{content}</MarkdownRender>} </div> ) case 'error': return ( <div className={type} dir="auto"> <div className="gpt-header"> <p>{t('Error')}:</p> <div className="gpt-util-group"> {onRetry && ( <span title={t('Retry')} className="gpt-util-icon" onClick={onRetry}> <SyncIcon size={14} /> </span> )} <CopyButton contentFn={() => content.replace(/\n<hr\/>$/, '')} size={14} /> {!collapsed ? ( <span title={t('Collapse')} className="gpt-util-icon" onClick={() => setCollapsed(true)} > <XCircleIcon size={14} /> </span> ) : ( <span title={t('Expand')} className="gpt-util-icon" onClick={() => setCollapsed(false)} > <ChevronDownIcon size={14} /> </span> )} </div> </div> {!collapsed && <MarkdownRender>{content}</MarkdownRender>} </div> ) }}
ConversationItem.propTypes = { type: PropTypes.oneOf(['question', 'answer', 'error']).isRequired, content: PropTypes.string.isRequired, session: PropTypes.object.isRequired, done: PropTypes.bool.isRequired, port: PropTypes.object.isRequired, onRetry: PropTypes.func,}
export default ConversationItem1234567891011121314151617181920212223242526272829303132333435363738import { useState } from 'react'import { CheckIcon, CopyIcon } from '@primer/octicons-react'import PropTypes from 'prop-types'import { useTranslation } from 'react-i18next'
CopyButton.propTypes = { contentFn: PropTypes.func.isRequired, size: PropTypes.number.isRequired, className: PropTypes.string,}
function CopyButton({ className, contentFn, size }) { const { t } = useTranslation() const [copied, setCopied] = useState(false)
const onClick = () => { navigator.clipboard .writeText(contentFn()) .then(() => setCopied(true)) .then(() => setTimeout(() => { setCopied(false) }, 600), ) }
return ( <span title={t('Copy')} className={`gpt-util-icon ${className ? className : ''}`} onClick={onClick} > {copied ? <CheckIcon size={size} /> : <CopyIcon size={size} />} </span> )}
export default CopyButton123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import { LightBulbIcon, SearchIcon } from '@primer/octicons-react'import { useState, useEffect } from 'react'import PropTypes from 'prop-types'import ConversationCard from '../ConversationCard'import { getPossibleElementByQuerySelector, endsWithQuestionMark } from '../../utils'import { useTranslation } from 'react-i18next'import { useConfig } from '../../hooks/use-config.mjs'
function DecisionCard(props) { const { t } = useTranslation() const [triggered, setTriggered] = useState(false) const [render, setRender] = useState(false) const config = useConfig(() => { setRender(true) })
const question = props.question
const updatePosition = () => { if (!render) return
const container = props.container const siteConfig = props.siteConfig container.classList.remove('chatgptbox-sidebar-free')
if (config.appendQuery) { const appendContainer = getPossibleElementByQuerySelector([config.appendQuery]) if (appendContainer) { appendContainer.appendChild(container) return } }
if (config.prependQuery) { const prependContainer = getPossibleElementByQuerySelector([config.prependQuery]) if (prependContainer) { prependContainer.prepend(container) return } }
if (!siteConfig) return
if (config.insertAtTop) { const resultsContainerQuery = getPossibleElementByQuerySelector( siteConfig.resultsContainerQuery, ) if (resultsContainerQuery) resultsContainerQuery.prepend(container) } else { const sidebarContainer = getPossibleElementByQuerySelector(siteConfig.sidebarContainerQuery) if (sidebarContainer) { sidebarContainer.prepend(container) } else { const appendContainer = getPossibleElementByQuerySelector(siteConfig.appendContainerQuery) if (appendContainer) { container.classList.add('chatgptbox-sidebar-free') appendContainer.appendChild(container) } else { const resultsContainerQuery = getPossibleElementByQuerySelector( siteConfig.resultsContainerQuery, ) if (resultsContainerQuery) resultsContainerQuery.prepend(container) } } } }
useEffect(() => updatePosition(), [config])
return ( render && ( <div data-theme={config.themeMode}> {(() => { if (question) switch (config.triggerMode) { case 'always': return <ConversationCard session={props.session} question={question} /> case 'manually': if (triggered) { return <ConversationCard session={props.session} question={question} /> } return ( <p className="gpt-inner manual-btn" onClick={() => setTriggered(true)}> <span className="icon-and-text"> <SearchIcon size="small" /> {t('Ask RisingBrowser')} </span> </p> ) case 'questionMark': if (endsWithQuestionMark(question.trim())) { return <ConversationCard session={props.session} question={question} /> } if (triggered) { return <ConversationCard session={props.session} question={question} /> } return ( <p className="gpt-inner manual-btn" onClick={() => setTriggered(true)}> <span className="icon-and-text"> <SearchIcon size="small" /> {t('Ask RisingBrowser')} </span> </p> ) } else return ( <p className="gpt-inner"> <span className="icon-and-text"> <LightBulbIcon size="small" /> {t('No Input Found')} </span> </p> ) })()} </div> ) )}
DecisionCard.propTypes = { session: PropTypes.object.isRequired, question: PropTypes.string.isRequired, siteConfig: PropTypes.object.isRequired, container: PropTypes.object.isRequired,}
export default DecisionCard1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import { useEffect, useRef, useState } from 'react'import PropTypes from 'prop-types'import { useTranslation } from 'react-i18next'import { TrashIcon } from '@primer/octicons-react'
DeleteButton.propTypes = { onConfirm: PropTypes.func.isRequired, size: PropTypes.number.isRequired, text: PropTypes.string.isRequired,}
function DeleteButton({ onConfirm, size, text }) { const { t } = useTranslation() const [waitConfirm, setWaitConfirm] = useState(false) const confirmRef = useRef(null)
useEffect(() => { if (waitConfirm) confirmRef.current.focus() }, [waitConfirm])
return ( <span> <button ref={confirmRef} type="button" className="normal-button" style={{ fontSize: '10px', ...(waitConfirm ? {} : { display: 'none' }), }} onMouseDown={(e) => { e.preventDefault() e.stopPropagation() }} onBlur={() => { setWaitConfirm(false) }} onClick={() => { setWaitConfirm(false) onConfirm() }} > {t('Confirm')} </button> <span title={text} className="gpt-util-icon" style={waitConfirm ? { display: 'none' } : {}} onClick={() => { setWaitConfirm(true) }} > <TrashIcon size={size} /> </span> </span> )}
export default DeleteButton1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import PropTypes from 'prop-types'import { memo, useCallback, useState } from 'react'import { ThumbsupIcon, ThumbsdownIcon } from '@primer/octicons-react'import Browser from 'webextension-polyfill'import { useTranslation } from 'react-i18next'
const FeedbackForChatGPTWeb = (props) => { const { t } = useTranslation() const [action, setAction] = useState(null)
const clickThumbsUp = useCallback(async () => { if (action) { return } setAction('thumbsUp') await Browser.runtime.sendMessage({ type: 'FEEDBACK', data: { conversation_id: props.conversationId, message_id: props.messageId, rating: 'thumbsUp', }, }) }, [props, action])
const clickThumbsDown = useCallback(async () => { if (action) { return } setAction('thumbsDown') await Browser.runtime.sendMessage({ type: 'FEEDBACK', data: { conversation_id: props.conversationId, message_id: props.messageId, rating: 'thumbsDown', text: '', tags: [], }, }) }, [props, action])
return ( <div title={t('Feedback')} className="gpt-feedback"> <span onClick={clickThumbsUp} className={action === 'thumbsUp' ? 'gpt-feedback-selected gpt-util-icon' : 'gpt-util-icon'} > <ThumbsupIcon size={14} /> </span> <span onClick={clickThumbsDown} className={ action === 'thumbsDown' ? 'gpt-feedback-selected gpt-util-icon' : 'gpt-util-icon' } > <ThumbsdownIcon size={14} /> </span> </div> )}
FeedbackForChatGPTWeb.propTypes = { messageId: PropTypes.string.isRequired, conversationId: PropTypes.string.isRequired,}
export default memo(FeedbackForChatGPTWeb)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import ConversationCard from '../ConversationCard'import { useState } from 'react'import PropTypes from 'prop-types'import { getClientPosition, setElementPositionInViewport } from '../../utils'import Draggable from 'react-draggable'import { useClampWindowSize } from '../../hooks/use-clamp-window-size'import { useConfig } from '../../hooks/use-config.mjs'
function FloatingToolbar(props) { const [render, setRender] = useState(false) const [closeable, setCloseable] = useState(props.closeable) const [position, setPosition] = useState(getClientPosition(props.container)) const [virtualPosition, setVirtualPosition] = useState({ x: 0, y: 0 }) const windowSize = useClampWindowSize([750, 1500], [0, Infinity]) const config = useConfig(() => { setRender(true) if (!props.triggered) { props.container.style.position = 'absolute' setTimeout(() => { const left = Math.min( Math.max(0, window.innerWidth - props.container.offsetWidth - 30), Math.max(0, position.x), ) props.container.style.left = left + 'px' }) } })
if (!render) return <div />
if (props.triggered) { const updatePosition = () => { const newPosition = setElementPositionInViewport(props.container, position.x, position.y) if (position.x !== newPosition.x || position.y !== newPosition.y) setPosition(newPosition) // clear extra virtual position offset }
const dragEvent = { onDrag: (e, ui) => { setVirtualPosition({ x: virtualPosition.x + ui.deltaX, y: virtualPosition.y + ui.deltaY }) }, onStop: () => { setPosition({ x: position.x + virtualPosition.x, y: position.y + virtualPosition.y }) setVirtualPosition({ x: 0, y: 0 }) }, }
if (virtualPosition.x === 0 && virtualPosition.y === 0) { updatePosition() // avoid jitter }
const onDock = () => { props.container.className = 'chatgptbox-toolbar-container-not-queryable' setCloseable(true) }
if (config.alwaysPinWindow) onDock()
return ( <div data-theme={config.themeMode}> <Draggable handle=".draggable" onDrag={dragEvent.onDrag} onStop={dragEvent.onStop} position={virtualPosition} > <div className="chatgptbox-selection-window" style={{ width: windowSize[0] * 0.4 + 'px' }} > <div className="chatgptbox-container"> <ConversationCard session={props.session} question={props.prompt} draggable={true} closeable={closeable} onClose={() => { props.container.remove() }} dockable={props.dockable} onDock={onDock} onUpdate={() => { updatePosition() }} /> </div> </div> </Draggable> </div> ) }}
FloatingToolbar.propTypes = { session: PropTypes.object.isRequired, selection: PropTypes.string.isRequired, container: PropTypes.object.isRequired, triggered: PropTypes.bool, closeable: PropTypes.bool, dockable: PropTypes.bool, prompt: PropTypes.string,}
export default FloatingToolbar123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import { useEffect, useRef, useState } from 'react'import PropTypes from 'prop-types'import { updateRefHeight } from '../../utils'import { useTranslation } from 'react-i18next'import { getUserConfig } from '../../config/index.mjs'
export function InputBox({ onSubmit, enabled, port, reverseResizeDir }) { const { t } = useTranslation() const [value, setValue] = useState('') const reverseDivRef = useRef(null) const inputRef = useRef(null) const resizedRef = useRef(false)
const virtualInputRef = reverseResizeDir ? reverseDivRef : inputRef
useEffect(() => { inputRef.current.focus()
const onResizeY = () => { if (virtualInputRef.current.h !== virtualInputRef.current.offsetHeight) { virtualInputRef.current.h = virtualInputRef.current.offsetHeight if (!resizedRef.current) { resizedRef.current = true virtualInputRef.current.style.maxHeight = '' } } } virtualInputRef.current.h = virtualInputRef.current.offsetHeight virtualInputRef.current.addEventListener('mousemove', onResizeY) }, [])
useEffect(() => { if (!resizedRef.current) { if (!reverseResizeDir) { updateRefHeight(inputRef) virtualInputRef.current.h = virtualInputRef.current.offsetHeight virtualInputRef.current.style.maxHeight = '160px' } } })
useEffect(() => { if (enabled) getUserConfig().then((config) => { if (config.focusAfterAnswer) inputRef.current.focus() }) }, [enabled])
const handleKeyDownOrClick = (e) => { e.stopPropagation() if (e.type === 'click' || (e.keyCode === 13 && e.shiftKey === false)) { if (enabled) { e.preventDefault() if (!value) return onSubmit(value) setValue('') } else { e.preventDefault() port.postMessage({ stop: true }) } } }
return ( <div className="input-box"> <div ref={reverseDivRef} style={ reverseResizeDir && { transform: 'rotateX(180deg)', resize: 'vertical', overflow: 'hidden', minHeight: '160px', } } > <textarea dir="auto" ref={inputRef} disabled={false} className="interact-input" style={ reverseResizeDir ? { transform: 'rotateX(180deg)', resize: 'none' } : { resize: 'vertical', minHeight: '70px' } } placeholder={ enabled ? t('Type your question here\nEnter to send, shift + enter to break line') : t('Type your question here\nEnter to stop generating\nShift + enter to break line') } value={value} onChange={(e) => setValue(e.target.value)} onKeyDown={handleKeyDownOrClick} /> </div> <button className="submit-button" style={{ backgroundColor: enabled ? '#30a14e' : '#cf222e', }} onClick={handleKeyDownOrClick} > {enabled ? t('Ask') : t('Stop')} </button> </div> )}
InputBox.propTypes = { onSubmit: PropTypes.func.isRequired, enabled: PropTypes.bool.isRequired, reverseResizeDir: PropTypes.bool, port: PropTypes.object.isRequired,}
export default InputBox12345678910111213141516171819202122232425262728293031323334353637import PropTypes from 'prop-types'import Browser from 'webextension-polyfill'
export function Hyperlink({ href, children }) { const linkProperties = { target: '_blank', style: 'color: #8ab4f8; cursor: pointer;', rel: 'nofollow noopener noreferrer', }
return href.includes('chat.openai.com') ? ( <span {...linkProperties} onClick={() => { Browser.runtime.sendMessage({ type: 'NEW_URL', data: { url: href, pinned: false, saveAsChatgptConfig: true, }, }) }} > {children} </span> ) : ( <a href={href} {...linkProperties}> {children} </a> )}
Hyperlink.propTypes = { href: PropTypes.string.isRequired, children: PropTypes.object.isRequired,}1234567891011121314151617181920212223242526272829303132333435363738import ReactMarkdown from 'react-markdown'import rehypeRaw from 'rehype-raw'import rehypeHighlight from 'rehype-highlight'import remarkGfm from 'remark-gfm'import remarkBreaks from 'remark-breaks'import { Hyperlink } from './Hyperlink'
export function MarkdownRender(props) { return ( <div dir="auto"> <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={[ rehypeRaw, [ rehypeHighlight, { detect: true, ignoreMissing: true, }, ], ]} components={{ a: Hyperlink, }} {...props} > {props.children} </ReactMarkdown> </div> )}
MarkdownRender.propTypes = { ...ReactMarkdown.propTypes,}
export default MarkdownRender123456789101112131415161718192021222324252627282930313233343536373839404142import 'katex/dist/katex.min.css'import ReactMarkdown from 'react-markdown'import rehypeRaw from 'rehype-raw'import rehypeHighlight from 'rehype-highlight'import rehypeKatex from 'rehype-katex'import remarkMath from 'remark-math'import remarkGfm from 'remark-gfm'import remarkBreaks from 'remark-breaks'import { Hyperlink } from './Hyperlink'
export function MarkdownRender(props) { return ( <div dir="auto"> <ReactMarkdown remarkPlugins={[remarkMath, remarkGfm, remarkBreaks]} rehypePlugins={[ rehypeKatex, rehypeRaw, [ rehypeHighlight, { detect: true, ignoreMissing: true, }, ], ]} components={{ a: Hyperlink, }} {...props} > {props.children} </ReactMarkdown> </div> )}
MarkdownRender.propTypes = { ...ReactMarkdown.propTypes,}
export default MarkdownRender123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import { useTranslation } from 'react-i18next'import PropTypes from 'prop-types'import Browser from 'webextension-polyfill'import { toast, ToastContainer } from 'react-toastify'import { useEffect } from 'react'import 'react-toastify/dist/ReactToastify.css'import { useTheme } from '../../hooks/use-theme.mjs'import { getUserConfig } from '../../config/index.mjs'
const NotificationForChatGPTWeb = () => { const { t } = useTranslation() const [theme, config] = useTheme()
const buttonStyle = { padding: '0 8px', border: '1px solid', borderRadius: '4px', whiteSpace: 'nowrap', cursor: 'pointer', }
useEffect(() => { toast( <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: '4px', }} > <div>{t('Please keep this tab open. You can now use the web mode of ChatGPTBox')}</div> <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}> <button style={buttonStyle} onClick={() => { Browser.runtime.sendMessage({ type: 'PIN_TAB', data: { saveAsChatgptConfig: true, }, }) }} > {t('Pin Tab')} </button> <button style={buttonStyle} onClick={async () => { Browser.runtime.sendMessage({ type: 'ACTIVATE_URL', data: { tabId: (await getUserConfig()).chatgptJumpBackTabId, }, }) }} > {t('Go Back')} </button> </div> </div>, { toastId: 0, updateId: 0, }, ) }, [config.themeMode, config.preferredLanguage])
return ( <ToastContainer style={{ width: '440px', }} position="top-right" autoClose={7000} newestOnTop={false} closeOnClick={false} rtl={false} pauseOnFocusLoss={true} draggable={false} theme={theme} /> )}
NotificationForChatGPTWeb.propTypes = { container: PropTypes.object.isRequired,}
export default NotificationForChatGPTWeb12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import { useState } from 'react'import { MuteIcon, UnmuteIcon } from '@primer/octicons-react'import PropTypes from 'prop-types'import { useTranslation } from 'react-i18next'import { useConfig } from '../../hooks/use-config.mjs'
ReadButton.propTypes = { contentFn: PropTypes.func.isRequired, size: PropTypes.number.isRequired, className: PropTypes.string,}
const synth = window.speechSynthesis
function ReadButton({ className, contentFn, size }) { const { t } = useTranslation() const [speaking, setSpeaking] = useState(false) const config = useConfig()
const startSpeak = () => { synth.cancel()
const text = contentFn() const utterance = new SpeechSynthesisUtterance(text) const voices = synth.getVoices()
let voice if (config.preferredLanguage.includes('en') && navigator.language.includes('en')) voice = voices.find((v) => v.name.toLowerCase().includes('microsoft aria')) if (!voice) voice = voices.find((v) => v.lang.substring(0, 2) === config.preferredLanguage) if (!voice) voice = voices.find((v) => v.lang === navigator.language)
Object.assign(utterance, { rate: 1, volume: 1, onend: () => setSpeaking(false), onerror: () => setSpeaking(false), voice: voice, })
synth.speak(utterance) setSpeaking(true) }
const stopSpeak = () => { synth.cancel() setSpeaking(false) }
return ( <span title={t('Read Aloud')} className={`gpt-util-icon ${className ? className : ''}`} onClick={speaking ? stopSpeak : startSpeak} > {speaking ? <MuteIcon size={size} /> : <UnmuteIcon size={size} />} </span> )}
export default ReadButton12345678910export * from './ConfirmButton'export * from './ConversationCard'export * from './ConversationItem'export * from './CopyButton'export * from './DecisionCard'export * from './DeleteButton'export * from './FeedbackForChatGPTWeb'export * from './FloatingToolbar'export * from './InputBox'export * from './ReadButton'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170import { defaults } from 'lodash-es'import Browser from 'webextension-polyfill'
export const TriggerMode = { always: 'Always', questionMark: 'When query ends with question mark (?)', manually: 'Manually',}
export const ThemeMode = { light: 'Light', dark: 'Dark', auto: 'Auto',}
export const ModelMode = { balanced: 'Balanced', creative: 'Creative', precise: 'Precise', fast: 'Fast',}
export const chatgptWebModelKeys = ['chatgptFree35', 'chatgptPlus4']export const bingWebModelKeys = ['bingFree4', 'bingFreeSydney']export const gptApiModelKeys = ['gptApiDavinci']export const chatgptApiModelKeys = ['chatgptApi35', 'chatgptApi4_8k', 'chatgptApi4_32k']export const customApiModelKeys = ['customModel']export const azureOpenAiApiModelKeys = ['azureOpenAi']export const githubThirdPartyApiModelKeys = ['waylaidwandererApi']
/** * @typedef {object} Model * @property {string} value * @property {string} desc *//** * @type {Object.<string,Model>} */export const Models = { chatgptFree35: { value: 'text-davinci-002-render-sha', desc: 'ChatGPT (Web)' }, chatgptPlus4: { value: 'gpt-4', desc: 'ChatGPT (Web, GPT-4)' }, chatgptApi35: { value: 'gpt-3.5-turbo', desc: 'ChatGPT (GPT-3.5-turbo)' },}
/** * @typedef {typeof defaultConfig} UserConfig */export const defaultConfig = { // general
/** @type {keyof TriggerMode}*/ triggerMode: 'manually', /** @type {keyof ThemeMode}*/ themeMode: 'auto', /** @type {keyof Models}*/ modelName: 'chatgptApi35',
preferredLanguage: getNavigatorLanguage(), clickIconAction: 'popup', insertAtTop: false, lockWhenAnswer: false, autoRegenAfterSwitchModel: false, selectionToolsNextToInputBox: false, alwaysPinWindow: false, focusAfterAnswer: true,
apiKey: '', // openai ApiKey
azureApiKey: '', azureEndpoint: '', azureDeploymentName: '',
/** @type {keyof ModelMode}*/ modelMode: 'balanced',
customModelApiUrl: 'https://smartphone.herokuapp.com/sendNotification', risingApiUrlForChat: 'https://smartphone.herokuapp.com/chat_rising',
// advanced
maxResponseTokenLength: 1000, maxConversationContextLength: 9, temperature: 1, siteRegex: 'match nothing', useSiteRegexOnly: false, inputQuery: '', appendQuery: '', prependQuery: '',
// others
alwaysCreateNewConversationWindow: false, activeApiModes: ['chatgptFree35', 'chatgptPlus4', 'chatgptApi35'], activeSiteAdapters: [], accessToken: '', tokenSavedOn: 0, chatgptJumpBackTabId: 0, chatgptTabId: 0,
// unchangeable
userLanguage: getNavigatorLanguage(), apiModes: Object.keys(Models), selectionTools: [ 'translate', 'translateToEn', 'translateBidi', 'summary', 'polish', 'sentiment', 'divide', 'code', 'ask', ], selectionToolsDesc: [ 'Translate', 'Translate (To English)', 'Translate (Bidirectional)', 'Summary', 'Polish', 'Sentiment Analysis', 'Divide Paragraphs', 'Code Explain', 'Ask', ], // importing configuration will result in gpt-3-encoder being packaged into the output file siteAdapters: [],}
export function getNavigatorLanguage() { const l = navigator.language.toLowerCase() if (['zh-hk', 'zh-mo', 'zh-tw', 'zh-cht', 'zh-hant'].includes(l)) return 'zhHant' return navigator.language.substring(0, 2)}
export async function getPreferredLanguageKey() { const config = await getUserConfig() if (config.preferredLanguage === 'auto') return config.userLanguage return config.preferredLanguage}
/** * get user config from local storage * @returns {Promise<UserConfig>} */export async function getUserConfig() { const options = await Browser.storage.local.get(Object.keys(defaultConfig)) return defaults(options, defaultConfig)}
/** * set user config to local storage * @param {Partial<UserConfig>} value */export async function setUserConfig(value) { await Browser.storage.local.set(value)}
export async function setAccessToken(accessToken) { await setUserConfig({ accessToken, tokenSavedOn: Date.now() })}
const TOKEN_DURATION = 30 * 24 * 3600 * 1000
export async function clearOldAccessToken() { const duration = Date.now() - (await getUserConfig()).tokenSavedOn if (duration > TOKEN_DURATION) { await setAccessToken('') }}1234567891011121314151617181920212223242526import { defaultConfig, getUserConfig } from './index.mjs'
export const languageList = { auto: { name: 'Auto', native: 'Auto' }, en: { name: 'en-US', native: 'en-US' },}
export async function getUserLanguage() { return languageList[defaultConfig.userLanguage].name}
export async function getUserLanguageNative() { return languageList[defaultConfig.userLanguage].native}
export async function getPreferredLanguage() { const config = await getUserConfig() if (config.preferredLanguage === 'auto') return await getUserLanguage() return languageList[config.preferredLanguage].name}
export async function getPreferredLanguageNative() { const config = await getUserConfig() if (config.preferredLanguage === 'auto') return await getUserLanguageNative() return languageList[config.preferredLanguage].native}12345678910111213141516171819import React, { Component } from 'react';import icon from '../../assets/img/icon-128.png';
class GreetingComponent extends Component { state = { name: 'dev', };
render() { return ( <div> <p>Hello, {this.state.name}!</p> <img src={icon} alt="extension icon" /> </div> ); }}
export default GreetingComponent;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203import './styles.scss'import { unmountComponentAtNode } from 'react-dom'import { render } from 'preact'import DecisionCard from '../components/DecisionCard'import { config as siteConfig } from './site-adapters'import { config as menuConfig } from './menu-tools'import { getUserConfig, setAccessToken } from '../config/index.mjs'import { createElementAtPosition, cropText, getPossibleElementByQuerySelector } from '../utils'import FloatingToolbar from '../components/FloatingToolbar'import Browser from 'webextension-polyfill'import { getPreferredLanguage } from '../config/language.mjs'import '../_locales/i18n-react'import { initSession } from '../services/init-session.mjs'import { registerPortListener } from '../services/wrappers.mjs'import { generateAnswersWithCustomApi } from '../services/apis/rising-api.mjs'
/** * @param {SiteConfig} siteConfig * @param {UserConfig} userConfig */async function mountComponent(siteConfig, userConfig) { const retry = 10 let oldUrl = location.href for (let i = 1; i <= retry; i++) { if (location.href !== oldUrl) { console.log(`SiteAdapters Retry ${i}/${retry}: stop`) return } const e = (siteConfig && (getPossibleElementByQuerySelector(siteConfig.sidebarContainerQuery) || getPossibleElementByQuerySelector(siteConfig.appendContainerQuery) || getPossibleElementByQuerySelector(siteConfig.resultsContainerQuery))) || getPossibleElementByQuerySelector([userConfig.prependQuery]) || getPossibleElementByQuerySelector([userConfig.appendQuery]) if (e) { console.log(`SiteAdapters Retry ${i}/${retry}: found`) console.log(e) break } else { console.log(`SiteAdapters Retry ${i}/${retry}: not found`) if (i === retry) return else await new Promise((r) => setTimeout(r, 500)) } }
document.querySelectorAll('.chatgptbox-container,#chatgptbox-container').forEach((e) => { unmountComponentAtNode(e) e.remove() })
let question if (userConfig.inputQuery) question = await getInput([userConfig.inputQuery]) if (!question && siteConfig) question = await getInput(siteConfig.inputQuery)
document.querySelectorAll('.chatgptbox-container,#chatgptbox-container').forEach((e) => { unmountComponentAtNode(e) e.remove() }) const container = document.createElement('div') container.id = 'chatgptbox-container' render( <DecisionCard session={initSession()} question={question} siteConfig={siteConfig} container={container} />, container, )}
/** * @param {string[]|function} inputQuery * @returns {Promise<string>} */async function getInput(inputQuery) { let input if (typeof inputQuery === 'function') { input = await inputQuery() if (input) return `Reply in ${await getPreferredLanguage()}.\n` + input return input } const searchInput = getPossibleElementByQuerySelector(inputQuery) if (searchInput) { if (searchInput.value) input = searchInput.value else if (searchInput.textContent) input = searchInput.textContent if (input) return ( `Reply in ${await getPreferredLanguage()}.\nThe following is a search input in a search engine, ` + `giving useful content or solutions and as much information as you can related to it, ` + `use markdown syntax to make your answer more readable, such as code blocks, bold, list:\n` + input ) }}
let menuX, menuY
async function prepareForRightClickMenu() { document.addEventListener('contextmenu', (e) => { menuX = e.clientX menuY = e.clientY })
Browser.runtime.onMessage.addListener(async (message) => { if (message.type === 'CREATE_CHAT') { const data = message.data let prompt = '' if (data.itemId in menuConfig) { const menuItem = menuConfig[data.itemId] if (!menuItem.genPrompt) return else prompt = await menuItem.genPrompt() if (prompt) prompt = cropText(`Reply in ${await getPreferredLanguage()}.\n` + prompt) }
const position = data.useMenuPosition ? { x: menuX, y: menuY } : { x: window.innerWidth / 2 - 300, y: window.innerHeight / 2 - 200 } const container = createElementAtPosition(position.x, position.y) container.className = 'chatgptbox-toolbar-container-not-queryable' render( <FloatingToolbar session={initSession({ modelName: (await getUserConfig()).modelName })} selection={data.selectionText} container={container} triggered={true} closeable={true} prompt={prompt} />, container, ) } })}
async function prepareForStaticCard() { const userConfig = await getUserConfig() let siteRegex if (userConfig.useSiteRegexOnly) siteRegex = userConfig.siteRegex else siteRegex = new RegExp( (userConfig.siteRegex && userConfig.siteRegex + '|') + Object.keys(siteConfig).join('|'), )
const matches = location.hostname.match(siteRegex) if (matches) { const siteName = matches[0]
if ( userConfig.siteAdapters.includes(siteName) && !userConfig.activeSiteAdapters.includes(siteName) ) return
if (siteName in siteConfig) { const siteAction = siteConfig[siteName].action if (siteAction && siteAction.init) { await siteAction.init(location.hostname, userConfig, getInput, mountComponent) } }
mountComponent(siteConfig[siteName], userConfig) }}
async function overwriteAccessToken() { if (location.hostname !== 'chat.openai.com') return
let data if (location.pathname === '/api/auth/session') { const response = document.querySelector('pre').textContent try { data = JSON.parse(response) } catch (error) { console.error('json error', error) } } else { const resp = await fetch('https://chat.openai.com/api/auth/session') data = await resp.json().catch(() => ({})) } if (data && data.accessToken) { await setAccessToken(data.accessToken) console.log(data.accessToken) }}
async function prepareForForegroundRequests() { const userConfig = await getUserConfig() registerPortListener(async (session, port) => { await generateAnswersWithCustomApi(port, session.question, session, '', userConfig.modelName) })}
async function run() { await overwriteAccessToken() await prepareForForegroundRequests()
prepareForStaticCard() prepareForRightClickMenu()}
run()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import { getCoreContentText } from '../../utils/get-core-content-text'import Browser from 'webextension-polyfill'import { getUserConfig } from '../../config/index.mjs'import { openUrl } from '../../utils/open-url'
export const config = { newChat: { label: 'New Chat', genPrompt: async () => { return '' }, }, summarizePage: { label: 'Summarize Page', genPrompt: async () => { return `The following is the text content of a web page, analyze the core content and summarize:\n${getCoreContentText()}` }, }, openConversationPage: { label: 'Open Conversation Page', action: async (fromBackground) => { console.debug('action is from background', fromBackground) if (fromBackground) { openUrl(Browser.runtime.getURL('IndependentPanel.html')) } else { Browser.runtime.sendMessage({ type: 'OPEN_URL', data: { url: Browser.runtime.getURL('IndependentPanel.html'), }, }) } }, }, openConversationWindow: { label: 'Open Conversation Window', action: async (fromBackground) => { console.debug('action is from background', fromBackground) if (fromBackground) { const config = await getUserConfig() const url = Browser.runtime.getURL('IndependentPanel.html') const tabs = await Browser.tabs.query({ url: url, windowType: 'popup' }) if (!config.alwaysCreateNewConversationWindow && tabs.length > 0) await Browser.windows.update(tabs[0].windowId, { focused: true }) else await Browser.windows.create({ url: url, type: 'popup', width: 500, height: 650, }) } else { Browser.runtime.sendMessage({ type: 'OPEN_CHAT_WINDOW', data: {}, }) } }, }, closeAllChats: { label: 'Close All Chats In This Page', action: async (fromBackground) => { console.debug('action is from background', fromBackground) Browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => { Browser.tabs.sendMessage(tabs[0].id, { type: 'CLOSE_CHATS', data: {}, }) }) }, },}1234567891011121314151617181920212223/** * @typedef {object} SiteConfigAction * @property {function} init *//** * @typedef {object} SiteConfig * @property {string[]|function} inputQuery - for search box * @property {string[]} sidebarContainerQuery - prepend child to * @property {string[]} appendContainerQuery - if sidebarContainer not exists, append child to * @property {string[]} resultsContainerQuery - prepend child to if insertAtTop is true * @property {SiteConfigAction} action *//** * @type {Object.<string,SiteConfig>} */export const config = { google: { inputQuery: ["input[name='q']", "textarea[name='q']"], sidebarContainerQuery: ['#rhs'], appendContainerQuery: ['#rcnt'], resultsContainerQuery: ['#rso'], },}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365@import '../fonts/styles.css';@import '../pages/styles.scss';
[data-theme='auto'] { @import 'github-markdown-css/github-markdown.css'; @media screen and (prefers-color-scheme: dark) { @import 'highlight.js/scss/github-dark.scss'; --font-color: #c9d1d9; --theme-color: #202124; --question-bg-color: #2d2e33; --theme-border-color: #3c4043; --dragbar-color: #3c4043; --color-neutral-muted: rgba(110, 118, 129, 0.4); --code-background-color: rgb(13, 17, 23); } @media screen and (prefers-color-scheme: light) { @import 'highlight.js/scss/github.scss'; --font-color: #24292f; --theme-color: #eaecf0; --question-bg-color: #e2e4e8; --theme-border-color: #aeafb2; --dragbar-color: #dfe0e1; --color-neutral-muted: rgba(150, 160, 170, 0.3); --code-background-color: rgb(255, 255, 255); }}
[data-theme='dark'] { @import 'highlight.js/scss/github-dark.scss'; @import 'github-markdown-css/github-markdown-dark.css';
--font-color: #c9d1d9; --theme-color: #202124; --question-bg-color: #2d2e33; --theme-border-color: #3c4043; --dragbar-color: #3c4043; --color-neutral-muted: rgba(110, 118, 129, 0.4); --code-background-color: rgb(13, 17, 23);}
[data-theme='light'] { @import 'highlight.js/scss/github.scss'; @import 'github-markdown-css/github-markdown-light.css';
--font-color: #24292f; --theme-color: #eaecf0; --question-bg-color: #e2e4e8; --theme-border-color: #aeafb2; --dragbar-color: #ccced0; --color-neutral-muted: rgba(150, 160, 170, 0.3); --code-background-color: rgb(255, 255, 255);}
.chatgptbox-sidebar-free { margin-left: 60px;}
.chatgptbox-container,#chatgptbox-container * { font-family: 'Cairo', sans-serif; font-size: 14px;}
.chatgptbox-container,#chatgptbox-container { width: 100%; flex-basis: 0; flex-grow: 1; margin-bottom: 20px;
.gpt-inner { height: 100%; display: flex; position: relative; flex-direction: column; border-radius: 8px; border: 1px solid; overflow: hidden; border-color: var(--theme-border-color); background-color: var(--theme-color); margin: 0;
hr { height: 1px; background-color: var(--theme-border-color); border: none; margin: 0; } }
.markdown-body { background-color: var(--theme-color); color: var(--font-color); overflow-y: auto;
::-webkit-scrollbar { background-color: var(--theme-color); width: 9px; } ::-webkit-scrollbar-thumb { background-color: var(--theme-border-color); border-radius: 20px; border: transparent; } ::-webkit-scrollbar-corner { background: transparent; } &::-webkit-scrollbar { background-color: var(--theme-color); width: 9px; } &::-webkit-scrollbar-thumb { background-color: var(--theme-border-color); border-radius: 20px; border: transparent; } &::-webkit-scrollbar-corner { background: transparent; } p { color: var(--font-color); }
ul, ol { padding-left: 1.5em; }
ol { list-style: none; counter-reset: item;
li { counter-increment: item;
&::marker { content: counter(item) '. '; } } } }
.icon-and-text { color: var(--font-color); display: flex; align-items: center; padding: 15px; gap: 6px; }
.manual-btn { cursor: pointer; }
.gpt-loading { color: var(--font-color); animation: chatgptbox-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
.code-corner-util { color: inherit; position: absolute; right: 10px; top: 3px; transition: opacity 0.3s; opacity: 0.2; }
.code-corner-util:hover { opacity: 1; }
.gpt-util-group { display: flex; gap: 15px; align-items: center; }
.gpt-util-icon { display: flex; cursor: pointer; align-items: center; }
.normal-button { padding: 1px 6px; border: 1px solid; border-color: var(--theme-border-color); background-color: var(--theme-color); color: var(--font-color); border-radius: 5px; cursor: pointer; white-space: nowrap; }
.question { background: var(--question-bg-color); }
:is(.answer, .question, .error) { font-size: 15px; line-height: 1.6; padding: 4px 15px; word-break: break-word;
pre { margin-top: 10px; padding: 0;
code { background-color: var(--code-background-color); font-size: 14px; } }
p { margin: 0 0 10px; }
code { padding: 0 0.4em; margin: 0; white-space: pre-wrap; word-break: break-word; border-radius: 8px; background-color: var(--color-neutral-muted); font-size: 11px;
.hljs { padding: 0; } } }
.gpt-header { display: flex; flex-direction: row; justify-content: space-between; align-items: center; margin-bottom: 5px; color: var(--font-color);
p { font-weight: bold; margin: 0; }
.gpt-feedback { display: flex; gap: 6px; }
.gpt-feedback-selected { color: #f08080; } }
.error { p { color: #ec4336; }
color: #ec4336; }
.input-box { display: contents; }
.interact-input { box-sizing: border-box; padding: 5px 15px; padding-right: 1em; border: 0; border-top: 1px solid var(--theme-border-color); width: 100%; height: 100%; background-color: var(--theme-color); color: var(--font-color);
&:focus { outline: none; }
&::-webkit-scrollbar { background-color: var(--theme-color); width: 9px; } &::-webkit-scrollbar-thumb { background-color: var(--theme-border-color); border-radius: 20px; border: transparent; } &::-webkit-scrollbar-corner { background: transparent; } }
.submit-button { position: absolute; right: 1.1em; bottom: 0.4em; padding: 1px 6px; cursor: pointer; background-color: #30a14e; color: white; border: 1px solid; border-radius: 6px; border-color: rgba(31, 35, 40, 0.15); font-size: 1em; box-shadow: 0 1px 0 rgba(31, 35, 40, 0.1); }
.draggable { cursor: move; }
.dragbar { cursor: move; width: 42%; height: 12px; border-radius: 10px; background-color: var(--dragbar-color); }}
@keyframes chatgptbox-pulse { 0%, 100% { opacity: 1; }
50% { opacity: 0.5; }}
.chatgptbox-selection-toolbar { display: flex; align-items: center; border-radius: 15px; padding: 2px; background-color: #ffffff; box-shadow: 4px 2px 4px rgba(0, 0, 0, 0.2);}
.chatgptbox-selection-toolbar-button { margin: 0 2px 0 0; padding: 2px; border-radius: 30px; background-color: #ffffff; color: #24292f; cursor: pointer;}
.chatgptbox-selection-toolbar-button:hover { background-color: #d4d5da;}
.chatgptbox-selection-window { height: auto; border-radius: 8px; background-color: var(--theme-color); box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.2);}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758/* arabic */@font-face { font-family: 'Cairo'; font-style: normal; font-weight: 400; font-display: swap; src: url(SLXVc1nY6HkvangtZmpQdkhzfH5lkSscQyyS4J0.woff2) format('woff2'); unicode-range: U+0600-06FF, U+200C-200E, U+2010-2011, U+204F, U+2E41, U+FB50-FDFF, U+FE80-FEFC;}/* latin-ext */@font-face { font-family: 'Cairo'; font-style: normal; font-weight: 400; font-display: swap; src: url(SLXVc1nY6HkvangtZmpQdkhzfH5lkSscSCyS4J0.woff2) format('woff2'); unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;}/* latin */@font-face { font-family: 'Cairo'; font-style: normal; font-weight: 400; font-display: swap; src: url(SLXVc1nY6HkvangtZmpQdkhzfH5lkSscRiyS.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}/* arabic */@font-face { font-family: 'Cairo'; font-style: normal; font-weight: 700; font-display: swap; src: url(SLXVc1nY6HkvangtZmpQdkhzfH5lkSscQyyS4J0.woff2) format('woff2'); unicode-range: U+0600-06FF, U+200C-200E, U+2010-2011, U+204F, U+2E41, U+FB50-FDFF, U+FE80-FEFC;}/* latin-ext */@font-face { font-family: 'Cairo'; font-style: normal; font-weight: 700; font-display: swap; src: url(SLXVc1nY6HkvangtZmpQdkhzfH5lkSscSCyS4J0.woff2) format('woff2'); unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;}/* latin */@font-face { font-family: 'Cairo'; font-style: normal; font-weight: 700; font-display: swap; src: url(SLXVc1nY6HkvangtZmpQdkhzfH5lkSscRiyS.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}12345678import { useWindowSize } from './use-window-size.mjs'
export function useClampWindowSize(widthRange = [0, Infinity], heightRange = [0, Infinity]) { const windowSize = useWindowSize() windowSize[0] = Math.min(widthRange[1], Math.max(windowSize[0], widthRange[0])) windowSize[1] = Math.min(heightRange[1], Math.max(windowSize[1], heightRange[0])) return windowSize}123456789101112131415161718192021222324252627282930import { useEffect, useState } from 'react'import { defaultConfig, getUserConfig } from '../config/index.mjs'import Browser from 'webextension-polyfill'
export function useConfig(initFn, ignoreSession = true) { const [config, setConfig] = useState(defaultConfig) useEffect(() => { getUserConfig().then((config) => { setConfig(config) if (initFn) initFn() }) }, []) useEffect(() => { const listener = (changes) => { if (ignoreSession) if (Object.keys(changes).length === 1 && 'sessions' in changes) return
const changedItems = Object.keys(changes) let newConfig = {} for (const key of changedItems) { newConfig[key] = changes[key].newValue } setConfig({ ...config, ...newConfig }) } Browser.storage.local.onChanged.addListener(listener) return () => { Browser.storage.local.onChanged.removeListener(listener) } }, [config]) return config}12345678import { useConfig } from './use-config.mjs'import { useWindowTheme } from './use-window-theme.mjs'
export function useTheme() { const config = useConfig() const theme = useWindowTheme() return [config.themeMode === 'auto' ? theme : config.themeMode, config]}12345678910111213141516// https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react
import { useLayoutEffect, useState } from 'react'
export function useWindowSize() { const [size, setSize] = useState([0, 0]) useLayoutEffect(() => { function updateSize() { setSize([window.innerWidth, window.innerHeight]) } window.addEventListener('resize', updateSize) updateSize() return () => window.removeEventListener('resize', updateSize) }, []) return size}123456789101112131415161718192021import { useEffect, useState } from 'react'
export function useWindowTheme() { const [theme, setTheme] = useState( window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : 'light', ) useEffect(() => { if (!window.matchMedia) return const listener = (e) => { setTheme(e.matches ? 'dark' : 'light') } window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', listener) return () => window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', listener) }, []) return theme}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293{"name": "Rising Browser","description": "Integrating GPT funtionality into your browser deeply, everything you need is here","version": "0.0.1","manifest_version": 3,"icons": {"16": "logo1.png","32": "logo1.png","48": "logo1.png","128": "logo1.png"},"host_permissions": ["https://*.openai.com/","https://*.bing.com/","https://*.poe.com/"],"permissions": ["commands","cookies","storage","contextMenus","unlimitedStorage","tabs"],"optional_permissions": ["background"],"background": {"service_worker": "background.js"},"action": {"default_popup": "popup.html"},"options_ui": {"page": "popup.html","open_in_tab": true},"content_scripts": [{"matches": ["https://*/*","http://*/*","file://*/*"],"js": ["shared.js","content-script.js"],"css": ["content-script.css"]}],"web_accessible_resources": [{"resources": ["logo1.png"],"matches": ["<all_urls>"]}],"commands": {"newChat": {"suggested_key": {"default": "Ctrl+B","mac": "MacCtrl+B"},"description": "Create a new chat"},"summarizePage": {"suggested_key": {"default": "Alt+B","mac": "Alt+B"},"description": "Summarize this page"},"openConversationPage": {"suggested_key": {"default": "Ctrl+Shift+H","mac": "MacCtrl+Shift+H"},"description": "Open the independent conversation page"},"openConversationWindow": {"description": "Open the independent conversation window"},"closeAllChats": {"description": "Close all chats in this page"}}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546{"manifest_version": 3,"name": "Chatbot Chrome Extension","description": "A chrome extension to implement the chatbot using OpenAI by Saeid Nobahari.","options_page": "options.html","permissions": ["activeTab", "tabs", "windows", "contextMenus", "storage"],"background": {"service_worker": "background.bundle.js"},"action": {"default_popup": "popup.html","default_icon": "icon-34.png"},"chrome_url_overrides": {"newtab": "newtab.html"},"icons": {"128": "icon-128.png"},"content_scripts": [{"matches": ["http://*/*","https://*/*","<all_urls>"],"js": ["contentScript.bundle.js"],"css": ["content.styles.css"]}],"devtools_page": "devtools.html","web_accessible_resources": [{"resources": ["content.styles.css","icon-128.png","icon-34.png"],"matches": []}]}
1234567891011121314151617// Create the context menu itemchrome.runtime.onInstalled.addListener(function() { chrome.contextMenus.create({ id: 'risingExtension', title: 'rising extension', contexts: ['page'], });});
// Handle the context menu item clickchrome.contextMenus.onClicked.addListener(function(info, tab) { if (info.menuItemId === 'risingExtension') { chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { chrome.tabs.sendMessage(tabs[0].id, { action: "open-modal" }); }); }});Extension/LICENSEAdded+21
Extension/build.mjsDeleted-311
Extension/package-lock.json
Extension/package.json+50-76
Extension/src/_locales/en/main.jsonDeleted-125
Extension/src/_locales/i18n-react.mjsDeleted-11
Extension/src/_locales/i18n.mjsDeleted-7
Extension/src/_locales/resources.mjsDeleted-7
Extension/src/assets/desc.pngDeleted
Extension/src/assets/img/icon-128.pngAdded
Extension/src/assets/img/icon-34.pngAdded
Extension/src/assets/img/logo.svgAdded
Extension/src/background/commands.mjsDeleted-27
Extension/src/background/index.mjsDeleted-77
Extension/src/background/menus.mjsDeleted-75
Extension/src/components/ConfirmButton/index.jsxDeleted-58
Extension/src/components/ConversationCard/index.jsxDeleted-483
Extension/src/components/ConversationItem/index.jsxDeleted-140
Extension/src/components/CopyButton/index.jsxDeleted-38
Extension/src/components/DecisionCard/index.jsxDeleted-125
Extension/src/components/DeleteButton/index.jsxDeleted-59
Extension/src/components/FeedbackForChatGPTWeb/index.jsxDeleted-68
Extension/src/components/FloatingToolbar/index.jsxDeleted-103
Extension/src/components/InputBox/index.jsxDeleted-117
Extension/src/components/MarkdownRender/Hyperlink.jsxDeleted-37
Extension/src/components/MarkdownRender/markdown-without-katex.jsxDeleted-38
Extension/src/components/MarkdownRender/markdown.jsxDeleted-42
Extension/src/components/NotificationForChatGPTWeb/index.jsxDeleted-90
Extension/src/components/ReadButton/index.jsxDeleted-61
Extension/src/components/index.mjsDeleted-10
Extension/src/config/index.mjsDeleted-170
Extension/src/config/language.mjsDeleted-26
Extension/src/containers/Greetings/Greetings.jsxAdded+19
Extension/src/content-script/index.jsxDeleted-203
Extension/src/content-script/menu-tools/index.mjsDeleted-72
Extension/src/content-script/site-adapters/index.jsxDeleted-23
Extension/src/content-script/styles.scssDeleted-365
Extension/src/fonts/SLXVc1nY6HkvangtZmpQdkhzfH5lkSscQyyS4J0.woff2Deleted
Extension/src/fonts/SLXVc1nY6HkvangtZmpQdkhzfH5lkSscRiyS.woff2Deleted
Extension/src/fonts/SLXVc1nY6HkvangtZmpQdkhzfH5lkSscSCyS4J0.woff2Deleted
Extension/src/fonts/styles.cssDeleted-58
Extension/src/hooks/use-clamp-window-size.mjsDeleted-8
Extension/src/hooks/use-config.mjsDeleted-30
Extension/src/hooks/use-theme.mjsDeleted-8
Extension/src/hooks/use-window-size.mjsDeleted-16
Extension/src/hooks/use-window-theme.mjsDeleted-21
Extension/src/logo.pngDeleted
Extension/src/logo1.pngDeleted
Extension/src/manifest.json+22-69
Extension/src/pages/Background/index.jsAdded+17