mirror of
https://github.com/lencx/ChatGPT.git
synced 2024-10-01 01:06:13 -04:00
Merge pull request #912 from lencx/dev
This commit is contained in:
commit
76c10e3662
9
.github/workflows/release.yml
vendored
9
.github/workflows/release.yml
vendored
@ -54,10 +54,6 @@ jobs:
|
||||
with:
|
||||
key: ${{ matrix.target }}
|
||||
|
||||
- name: Install xattr (macos only)
|
||||
if: matrix.os == 'macos-latest'
|
||||
run: pip install xattr
|
||||
|
||||
- name: Install dependencies (ubuntu only)
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: |
|
||||
@ -110,11 +106,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Install xattr
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xattr
|
||||
|
||||
- name: Query version number
|
||||
run: echo "version=${GITHUB_REF:11}" >> $GITHUB_ENV
|
||||
|
||||
|
1495
Cargo.lock
generated
1495
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -32,7 +32,7 @@
|
||||
|
||||
### Windows
|
||||
|
||||
- [ChatGPT_0.12.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_windows_x86_64.msi)
|
||||
- [ChatGPT_1.0.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_windows_x86_64.msi)
|
||||
- 使用 [winget](https://winstall.app/apps/lencx.ChatGPT):
|
||||
|
||||
```bash
|
||||
@ -43,12 +43,12 @@
|
||||
winget install --id=lencx.ChatGPT -e --version 0.10.0
|
||||
```
|
||||
|
||||
**注意:如果安装路径和应用名称相同,会导致冲突 ([#142](https://github.com/lencx/ChatGPT/issues/142#issuecomment-0.12.0))**
|
||||
**注意:如果安装路径和应用名称相同,会导致冲突 ([#142](https://github.com/lencx/ChatGPT/issues/142))**
|
||||
|
||||
### Mac
|
||||
|
||||
- [ChatGPT_0.12.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_macos_aarch64.dmg)
|
||||
- [ChatGPT_0.12.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_macos_x86_64.dmg)
|
||||
- [ChatGPT_1.0.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_macos_aarch64.dmg)
|
||||
- [ChatGPT_1.0.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_macos_x86_64.dmg)
|
||||
- Homebrew \
|
||||
_[Homebrew 快捷安装](https://brew.sh) ([Cask](https://docs.brew.sh/Cask-Cookbook)):_
|
||||
```sh
|
||||
@ -70,8 +70,8 @@ sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
|
||||
|
||||
### Linux
|
||||
|
||||
- [ChatGPT_0.12.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_linux_x86_64.deb)
|
||||
- [ChatGPT_0.12.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_linux_x86_64.AppImage.tar.gz): **工作可靠,`.deb` 运行失败时可以尝试它**
|
||||
- [ChatGPT_1.0.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_linux_x86_64.deb)
|
||||
- [ChatGPT_1.0.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_linux_x86_64.AppImage.tar.gz): **工作可靠,`.deb` 运行失败时可以尝试它**
|
||||
|
||||
<!-- tr-download-end -->
|
||||
|
||||
@ -97,7 +97,6 @@ sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
|
||||
|
||||
- 跨平台: `macOS` `Linux` `Windows`
|
||||
- 导出 ChatGPT 聊天记录 (支持 PNG, PDF 和生成分享链接)
|
||||
- 主窗口和系统托盘支持自定义 URL,将任意网站包装成一个桌面应用
|
||||
- 应用自动升级通知
|
||||
- 丰富的快捷键
|
||||
- 系统托盘悬浮窗
|
||||
@ -112,17 +111,14 @@ sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
|
||||
- `Theme` - `Light`, `Dark`, `System` (仅支持 macOS 和 Windows)
|
||||
- `Stay On Top`: 窗口置顶
|
||||
- `Titlebar`: 是否显示 `Titlebar`,仅 macOS 支持
|
||||
- `Inject Script`: 用于修改网站的用户自定义脚本
|
||||
- `Hide Dock Icon` ([#35](https://github.com/lencx/ChatGPT/issues/35)): 隐藏 Dock 中的应用图标 (仅 macOS 支持)
|
||||
- 系统图盘右键单击打开菜单,然后在菜单项中点击 `Show Dock Icon` 可以重新将应用图标显示在 Dock(`SystemTrayMenu -> Show Dock Icon`)
|
||||
- `Control Center`: ChatGPT 应用的控制中心,它将为应用提供无限的可能
|
||||
- 设置 `Theme`,`Stay On Top`,`Titlebar` 等
|
||||
- `User Agent` ([#17](https://github.com/lencx/ChatGPT/issues/17)): 自定义 `user agent` 防止网站安全检测,默认值为空
|
||||
- `Switch Origin` ([#14](https://github.com/lencx/ChatGPT/issues/14)): 切换网站源地址,默认为 `https://chat.openai.com`。需要注意的是镜像网站的 UI 需要和原网站一致,否则可能会导致某些功能不工作
|
||||
- `Go to Config`: 打开 ChatGPT 配置目录 (`path: ~/.chatgpt/*`)
|
||||
- `Clear Config`: 清除 ChatGPT 配置数据 (`path: ~/.chatgpt/*`), 这是危险操作,请提前备份数据
|
||||
- `Restart ChatGPT`: 重启应用。如果注入脚本编辑完成,或者应用可卡死可以通过此菜单重新启动应用
|
||||
- `Awesome ChatGPT`: 一个很棒的 ChatGPT 推荐列表
|
||||
- **Edit** - `Undo`, `Redo`, `Cut`, `Copy`, `SelectAll`, ...
|
||||
- **View** - `Go Back`, `Go Forward`, `Scroll to Top of Screen`, `Scroll to Bottom of Screen`, `Refresh the Screen`, ...
|
||||
- **Help**
|
||||
@ -140,13 +136,13 @@ sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
|
||||
|
||||
- `[.chatgpt]` - 应用配置根路径
|
||||
- `chat.conf.json` - 应用喜好配置
|
||||
- `chat.awesome.json` - 自定义 URL 列表,类似于浏览器书签。可以将任意 URL 作为主窗口或托盘窗口 (**Control Conter -> Awesome**)
|
||||
- `chat.model.json` - ChatGPT 输入提示,通过斜杠命令来快速完成输入,主要包含三部分:
|
||||
- `user_custom` - 需要手动录入 (**Control Conter -> Language Model -> User Custom**)
|
||||
- `sync_prompts` - 从 [f/awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) 同步数据 (**Control Conter -> Language Model -> Sync Prompts**)
|
||||
- `sync_custom` - 同步自定义的 json 或 csv 文件数据,支持本地和远程 (**Control Conter -> Language Model -> Sync Custom**)
|
||||
- `chat.model.cmd.json` - 过滤(是否启用)和排序处理后的斜杠命令数据
|
||||
- `[cache_model]` - 缓存同步或录入的数据
|
||||
<!-- - `chat.awesome.json` - 自定义 URL 列表,类似于浏览器书签。可以将任意 URL 作为主窗口或托盘窗口 (**Control Conter -> Awesome**) -->
|
||||
- `chat.prompt.json` - ChatGPT 输入提示,通过斜杠命令来快速完成输入,主要包含三部分:
|
||||
- `user_custom` - 需要手动录入 (**Control Conter -> Prompts -> User Custom**)
|
||||
- `sync_prompts` - 从 [f/awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) 同步数据 (**Control Conter -> Prompts -> Sync Prompts**)
|
||||
- `sync_custom` - 同步自定义的 json 或 csv 文件数据,支持本地和远程 (**Control Conter -> Prompts -> Sync Custom**)
|
||||
- `chat.prompt.cmd.json` - 过滤(是否启用)和排序处理后的斜杠命令数据
|
||||
- `[cache_prompts]` - 缓存同步或录入的数据
|
||||
- `chatgpt_prompts.json` - 缓存 `sync_prompts` 数据
|
||||
- `user_custom.json` - 缓存 `user_custom` 数据
|
||||
- `ae6cf32a6f8541b499d6bfe549dbfca3.json` - 随机生成的文件名,缓存 `sync_custom` 数据
|
||||
|
22
README.md
22
README.md
@ -6,21 +6,12 @@
|
||||
|
||||
[![English badge](https://img.shields.io/badge/%E8%8B%B1%E6%96%87-English-blue)](./README.md)
|
||||
[![简体中文 badge](https://img.shields.io/badge/%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-Simplified%20Chinese-blue)](./README-ZH_CN.md)\
|
||||
![visitor](https://visitor-badge.glitch.me/badge?page_id=lencx.chatgpt)
|
||||
[![ChatGPT downloads](https://img.shields.io/github/downloads/lencx/ChatGPT/total.svg?style=flat-square)](https://github.com/lencx/ChatGPT/releases)
|
||||
[![chat](https://img.shields.io/badge/chat-discord-blue?style=flat&logo=discord)](https://discord.gg/aPhCRf4zZr)
|
||||
[![lencx](https://img.shields.io/badge/follow-lencx__-blue?style=flat&logo=Twitter)](https://twitter.com/lencx_)
|
||||
|
||||
<!-- [![lencx](https://img.shields.io/twitter/follow/lencx_.svg?style=social)](https://twitter.com/lencx_) -->
|
||||
|
||||
<!-- [![中文版 badge](https://img.shields.io/badge/%E4%B8%AD%E6%96%87-Traditional%20Chinese-blue)](./README-ZH.md) -->
|
||||
|
||||
<a href="https://www.buymeacoffee.com/lencx" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 145px !important;" ></a>
|
||||
|
||||
**🛑 URGENT NOTICE: A hacker has been found to take advantage of the heat of `lencx/ChatGPT` to plant a Trojan horse after the fork project and rebuild the installer. If you have friends around you who are using this desktop application, please remind them not to download unknown links freely. Now the project will remove other installation ways and only provide this download link https://github.com/lencx/ChatGPT/releases**
|
||||
|
||||
**🛑 紧急通知:目前发现有黑客利用 `lencx/ChatGPT` 的热度,在 fork 项目后植入木马,重新构建安装程序。如果你身边有朋友正在使用此桌面应用,请提醒 TA 们不要随意下载不明链接。现在项目将删除其他安装途径,仅提供此下载链接 https://github.com/lencx/ChatGPT/releases**
|
||||
|
||||
---
|
||||
|
||||
**It is an unofficial project intended for personal learning and research purposes only. During the time that the ChatGPT desktop application was open-sourced, it received a lot of attention, and I would like to thank everyone for their support. However, as things have developed, there are two issues that seriously affect the project's next development plan:**
|
||||
@ -41,7 +32,7 @@
|
||||
|
||||
### Windows
|
||||
|
||||
- [ChatGPT_0.12.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_windows_x86_64.msi): Direct download installer
|
||||
- [ChatGPT_1.0.0_windows_x86_64.msi](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_windows_x86_64.msi): Direct download installer
|
||||
- Use [winget](https://winstall.app/apps/lencx.ChatGPT):
|
||||
|
||||
```bash
|
||||
@ -52,12 +43,12 @@
|
||||
winget install --id=lencx.ChatGPT -e --version 0.10.0
|
||||
```
|
||||
|
||||
**Note: If the installation path and application name are the same, it will lead to conflict ([#142](https://github.com/lencx/ChatGPT/issues/142#issuecomment-0.12.0))**
|
||||
**Note: If the installation path and application name are the same, it will lead to conflict ([#142](https://github.com/lencx/ChatGPT/issues/142))**
|
||||
|
||||
### Mac
|
||||
|
||||
- [ChatGPT_0.12.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_macos_aarch64.dmg): Direct download installer
|
||||
- [ChatGPT_0.12.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_macos_x86_64.dmg): Direct download installer
|
||||
- [ChatGPT_1.0.0_macos_aarch64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_macos_aarch64.dmg): Direct download installer
|
||||
- [ChatGPT_1.0.0_macos_x86_64.dmg](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_macos_x86_64.dmg): Direct download installer
|
||||
- Homebrew \
|
||||
Or you can install with _[Homebrew](https://brew.sh) ([Cask](https://docs.brew.sh/Cask-Cookbook)):_
|
||||
```sh
|
||||
@ -79,8 +70,8 @@ sudo xattr -r -d com.apple.quarantine /YOUR_PATH/ChatGPT.app
|
||||
|
||||
### Linux
|
||||
|
||||
- [ChatGPT_0.12.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_linux_x86_64.deb): Download `.deb` installer, advantage small size, disadvantage poor compatibility
|
||||
- [ChatGPT_0.12.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v0.12.0/ChatGPT_0.12.0_linux_x86_64.AppImage.tar.gz): Works reliably, you can try it if `.deb` fails to run
|
||||
- [ChatGPT_1.0.0_linux_x86_64.deb](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_linux_x86_64.deb): Download `.deb` installer, advantage small size, disadvantage poor compatibility
|
||||
- [ChatGPT_1.0.0_linux_x86_64.AppImage.tar.gz](https://github.com/lencx/ChatGPT/releases/download/v1.0.0/ChatGPT_1.0.0_linux_x86_64.AppImage.tar.gz): Works reliably, you can try it if `.deb` fails to run
|
||||
|
||||
<!-- tr-download-end -->
|
||||
|
||||
@ -95,7 +86,6 @@ You can look at **[awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt
|
||||
- Multi-platform: `macOS` `Linux` `Windows`
|
||||
- Text-to-Speech
|
||||
- Export ChatGPT history (PNG, PDF and Markdown)
|
||||
- The main window and system tray support custom URLs to wrap any website into a desktop application
|
||||
- Automatic application upgrade notification
|
||||
- Common shortcut keys
|
||||
- System tray hover window
|
||||
|
@ -13,6 +13,21 @@
|
||||
|
||||
**New repository: https://github.com/lencx/nofwl**
|
||||
|
||||
## v1.0.0
|
||||
|
||||
Note: This version modifies some configuration files. It is recommended to backup the `~/.chatgpt` folder in advance to avoid loss of important configurations.
|
||||
|
||||
Feat:
|
||||
|
||||
- The synchronization method for prompts has been optimized, now supporting local file uploads
|
||||
- Scripts have been externalized, allowing for editing and synchronization
|
||||
- Removed the `Awesome` menu from `Control Center`
|
||||
|
||||
Fix:
|
||||
|
||||
- Chat history export is blank
|
||||
- Change the export files location to the `Download` directory
|
||||
|
||||
## v0.12.0
|
||||
|
||||
Feat:
|
||||
|
@ -11,7 +11,7 @@
|
||||
"fix:conf": "tr override --json.tauri_updater_active=false",
|
||||
"fix:tray": "tr override --json.tauri_systemTray_iconPath=\"icons/tray-icon-light.png\" --json.tauri_systemTray_iconAsTemplate=false",
|
||||
"fix:tray:mac": "tr override --json.tauri_systemTray_iconPath=\"icons/tray-icon.png\" --json.tauri_systemTray_iconAsTemplate=true",
|
||||
"download": "tr download --mdfile=README.md,README-ZH_CN.md --f1=52 --f2=43",
|
||||
"download": "tr download --mdfile=README.md,README-ZH_CN.md --f1=43 --f2=43",
|
||||
"fmt:rs": "cargo fmt",
|
||||
"tr": "tr",
|
||||
"tauri": "tauri",
|
||||
@ -58,7 +58,7 @@
|
||||
"uuid": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^1.2.2",
|
||||
"@tauri-apps/cli": "^1.3.1",
|
||||
"@tauri-release/cli": "^0.2.5",
|
||||
"@types/lodash": "^4.14.191",
|
||||
"@types/node": "^18.7.10",
|
||||
|
1455
pnpm-lock.yaml
1455
pnpm-lock.yaml
File diff suppressed because it is too large
Load Diff
BIN
public/bmc.png
Normal file
BIN
public/bmc.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 4.6 KiB |
BIN
public/wxp.png
Normal file
BIN
public/wxp.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 248 KiB |
@ -1,3 +1,5 @@
|
||||
# ChatGPT Scripts
|
||||
|
||||
ChatGPT Desktop Application Core Extension Scripts.
|
||||
> ChatGPT Desktop Application Core Extension Scripts.
|
||||
|
||||
[ChatGPT/scripts](https://github.com/lencx/ChatGPT/tree/main/scripts)
|
||||
|
223
scripts/chat.js
vendored
223
scripts/chat.js
vendored
@ -4,125 +4,122 @@
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/chat.js
|
||||
*/
|
||||
|
||||
async function init() {
|
||||
new MutationObserver(function (mutationsList) {
|
||||
for (const mutation of mutationsList) {
|
||||
if (mutation.target.closest('form')) {
|
||||
chatBtns();
|
||||
}
|
||||
}
|
||||
}).observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
document.addEventListener('visibilitychange', () =>
|
||||
document.getElementsByTagName('textarea')[0]?.focus(),
|
||||
);
|
||||
}
|
||||
|
||||
async function chatBtns() {
|
||||
const chatConf = (await invoke('get_app_conf')) || {};
|
||||
const synth = window.speechSynthesis;
|
||||
let currentUtterance = null;
|
||||
let currentIndex = -1;
|
||||
const list = Array.from(document.querySelectorAll('main >div>div>div>div>div'));
|
||||
list.forEach((i, idx) => {
|
||||
// if (i.querySelector('.chat-item-copy')) return;
|
||||
if (i.querySelector('.chat-item-voice')) return;
|
||||
if (!i.querySelector('button.rounded-md')) return;
|
||||
if (!i.querySelector('.self-end')) return;
|
||||
// const cpbtn = i.querySelector('button.rounded-md').cloneNode(true);
|
||||
// cpbtn.classList.add('chat-item-copy');
|
||||
// cpbtn.title = 'Copy to clipboard';
|
||||
// cpbtn.innerHTML = setIcon('copy');
|
||||
// i.querySelector('.self-end').appendChild(cpbtn);
|
||||
// cpbtn.onclick = () => {
|
||||
// copyToClipboard(i?.innerText?.trim() || '', cpbtn);
|
||||
// }
|
||||
|
||||
const saybtn = i.querySelector('button.rounded-md').cloneNode(true);
|
||||
saybtn.classList.add('chat-item-voice');
|
||||
saybtn.title = 'Say';
|
||||
saybtn.innerHTML = setIcon('voice');
|
||||
i.querySelector('.self-end').appendChild(saybtn);
|
||||
saybtn.onclick = () => {
|
||||
if (currentUtterance && currentIndex !== -1) {
|
||||
synth.cancel();
|
||||
if (idx === currentIndex) {
|
||||
saybtn.innerHTML = setIcon('voice');
|
||||
currentUtterance = null;
|
||||
currentIndex = -1;
|
||||
return;
|
||||
} else if (list[currentIndex].querySelector('.chat-item-voice')) {
|
||||
list[currentIndex].querySelector('.chat-item-voice').innerHTML = setIcon('voice');
|
||||
list[idx].querySelector('.chat-item-voice').innerHTML = setIcon('speaking');
|
||||
}
|
||||
}
|
||||
const txt = i?.innerText?.trim() || '';
|
||||
if (!txt) return;
|
||||
const utterance = new SpeechSynthesisUtterance(txt);
|
||||
const voices = speechSynthesis.getVoices();
|
||||
let voice = voices.find((voice) => voice.voiceURI === chatConf.speech_lang);
|
||||
if (!voice) {
|
||||
voice = voices.find((voice) => voice.lang === 'en-US');
|
||||
}
|
||||
utterance.voice = voice;
|
||||
currentIndex = idx;
|
||||
utterance.lang = voice.lang;
|
||||
// utterance.rate = 0.7;
|
||||
// utterance.pitch = 1.1;
|
||||
// utterance.volume = 1;
|
||||
synth.speak(utterance);
|
||||
amISpeaking = synth.speaking;
|
||||
saybtn.innerHTML = setIcon('speaking');
|
||||
currentUtterance = utterance;
|
||||
currentIndex = idx;
|
||||
utterance.onend = () => {
|
||||
saybtn.innerHTML = setIcon('voice');
|
||||
currentUtterance = null;
|
||||
currentIndex = -1;
|
||||
};
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// function copyToClipboard(text, btn) {
|
||||
// window.clearTimeout(window.__cpTimeout);
|
||||
// btn.innerHTML = setIcon('cpok');
|
||||
// if (navigator.clipboard) {
|
||||
// navigator.clipboard.writeText(text);
|
||||
// } else {
|
||||
// var textarea = document.createElement('textarea');
|
||||
// document.body.appendChild(textarea);
|
||||
// textarea.style.position = 'fixed';
|
||||
// textarea.style.clip = 'rect(0 0 0 0)';
|
||||
// textarea.style.top = '10px';
|
||||
// textarea.value = text;
|
||||
// textarea.select();
|
||||
// document.execCommand('copy', true);
|
||||
// document.body.removeChild(textarea);
|
||||
// }
|
||||
// window.__cpTimeout = setTimeout(() => {
|
||||
// btn.innerHTML = setIcon('copy');
|
||||
// }, 1000);
|
||||
// }
|
||||
|
||||
function focusOnInput() {
|
||||
// This currently works because there is only a single `<textarea>` element on the ChatGPT UI page.
|
||||
document.getElementsByTagName('textarea')[0].focus();
|
||||
}
|
||||
|
||||
function setIcon(type) {
|
||||
return {
|
||||
function chatInit() {
|
||||
const ICONS = {
|
||||
copy: `<svg class="chatappico copy" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg>`,
|
||||
cpok: `<svg class="chatappico cpok" viewBox="0 0 24 24"><g fill="none" stroke="#10a37f" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2M16 4h2a2 2 0 0 1 2 2v4m1 4H11"/><path d="m15 10l-4 4l4 4"/></g></svg>`,
|
||||
voice: `<svg class="chatappico voice" viewBox="0 0 1024 1024"><path d="M542.923802 202.113207c-5.110391 0-10.717086 1.186012-16.572444 3.739161L360.043634 312.714188l-83.057671 0c-46.109154 0-83.433224 36.917818-83.433224 83.121116l0 166.646438c0 45.952588 36.950564 83.153862 83.433224 83.153862l83.057671 0 166.307723 106.829074c23.550369 10.218736 41.745776-0.717338 41.745776-23.898293L568.097134 229.687216C568.096111 212.426087 557.753555 202.113207 542.923802 202.113207z" fill="currentColor"></path><path d="M794.154683 314.39548c-16.758686-28.537963-33.771151-48.258097-45.610804-58.882062-3.986801-3.489474-8.972349-5.233188-13.833053-5.233188-5.79396 0-11.464099 2.337231-15.57779 6.91448-7.662517 8.631588-6.976902 21.808702 1.620917 29.410843 1.994424 1.744737 5.856381 5.700839 11.154038 11.777231 9.033747 10.437723 18.006096 22.774703 26.419719 37.072337 24.235984 41.033555 38.755676 89.011266 38.755676 143.688563 0 54.705949-14.519692 102.651938-38.755676 143.810337-8.414647 14.20656-17.448394 26.668383-26.484188 37.07336-5.234211 6.076392-9.096169 10.033517-11.149944 11.778254-8.538467 7.603165-9.224082 20.717857-1.683339 29.40982 7.599072 8.473999 20.807908 9.222035 29.40982 1.650593 11.900028-10.562567 28.910447-30.252001 45.732577-58.850339 27.79095-47.078225 44.490284-102.3122 44.490284-164.872025C838.708412 416.646282 821.946656 361.470635 794.154683 314.39548z" fill="currentColor"></path><path d="M690.846806 377.360534c-8.723685-17.790178-17.698081-30.2827-24.301476-37.260625-4.111644-4.3951-9.595542-6.544043-15.139815-6.544043-5.110391 0-10.159384 1.774413-14.270005 5.54632-8.350179 7.881504-8.847505 20.99722-0.997724 29.471219 3.927449 4.112668 10.468422 13.304004 17.448394 27.199479 11.587919 23.77038 18.567891 51.559283 18.567891 83.370803 0 31.80845-6.978948 59.72322-18.567891 83.400478-6.978948 13.892405-13.520945 23.052019-17.448394 27.259854-7.850805 8.410554-7.353478 21.559015 0.997724 29.440519 8.473999 7.882528 21.559015 7.353478 29.474288-1.025353 6.53995-7.011694 15.513322-19.440771 24.238031-37.356816 14.393825-29.189809 22.992667-63.243393 22.992667-101.781104C713.839473 440.603927 705.241654 406.583089 690.846806 377.360534z" fill="currentColor"></path></svg>`,
|
||||
speaking: `<svg class="chatappico voice" viewBox="0 0 1024 1024"><path d="M542.923802 202.113207c-5.110391 0-10.717086 1.186012-16.572444 3.739161L360.043634 312.714188l-83.057671 0c-46.109154 0-83.433224 36.917818-83.433224 83.121116l0 166.646438c0 45.952588 36.950564 83.153862 83.433224 83.153862l83.057671 0 166.307723 106.829074c23.550369 10.218736 41.745776-0.717338 41.745776-23.898293L568.097134 229.687216C568.096111 212.426087 557.753555 202.113207 542.923802 202.113207z" fill="#10a37f"></path><path d="M794.154683 314.39548c-16.758686-28.537963-33.771151-48.258097-45.610804-58.882062-3.986801-3.489474-8.972349-5.233188-13.833053-5.233188-5.79396 0-11.464099 2.337231-15.57779 6.91448-7.662517 8.631588-6.976902 21.808702 1.620917 29.410843 1.994424 1.744737 5.856381 5.700839 11.154038 11.777231 9.033747 10.437723 18.006096 22.774703 26.419719 37.072337 24.235984 41.033555 38.755676 89.011266 38.755676 143.688563 0 54.705949-14.519692 102.651938-38.755676 143.810337-8.414647 14.20656-17.448394 26.668383-26.484188 37.07336-5.234211 6.076392-9.096169 10.033517-11.149944 11.778254-8.538467 7.603165-9.224082 20.717857-1.683339 29.40982 7.599072 8.473999 20.807908 9.222035 29.40982 1.650593 11.900028-10.562567 28.910447-30.252001 45.732577-58.850339 27.79095-47.078225 44.490284-102.3122 44.490284-164.872025C838.708412 416.646282 821.946656 361.470635 794.154683 314.39548z" fill="#10a37f"></path><path d="M690.846806 377.360534c-8.723685-17.790178-17.698081-30.2827-24.301476-37.260625-4.111644-4.3951-9.595542-6.544043-15.139815-6.544043-5.110391 0-10.159384 1.774413-14.270005 5.54632-8.350179 7.881504-8.847505 20.99722-0.997724 29.471219 3.927449 4.112668 10.468422 13.304004 17.448394 27.199479 11.587919 23.77038 18.567891 51.559283 18.567891 83.370803 0 31.80845-6.978948 59.72322-18.567891 83.400478-6.978948 13.892405-13.520945 23.052019-17.448394 27.259854-7.850805 8.410554-7.353478 21.559015 0.997724 29.440519 8.473999 7.882528 21.559015 7.353478 29.474288-1.025353 6.53995-7.011694 15.513322-19.440771 24.238031-37.356816 14.393825-29.189809 22.992667-63.243393 22.992667-101.781104C713.839473 440.603927 705.241654 406.583089 690.846806 377.360534z" fill="#10a37f"></path></svg>`,
|
||||
}[type];
|
||||
};
|
||||
|
||||
let currentUtterance = null;
|
||||
let currentIndex = -1;
|
||||
let chatConf = {};
|
||||
|
||||
async function init() {
|
||||
chatConf = (await invoke('get_app_conf')) || {};
|
||||
|
||||
new MutationObserver(observeMutations).observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
|
||||
document.addEventListener('visibilitychange', focusOnInput);
|
||||
}
|
||||
|
||||
function observeMutations(mutationsList) {
|
||||
for (const mutation of mutationsList) {
|
||||
if (mutation.target.closest('form')) {
|
||||
addChatButtons();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function focusOnInput() {
|
||||
const textArea = document.getElementsByTagName('textarea')[0];
|
||||
if (textArea) {
|
||||
textArea.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function addChatButtons() {
|
||||
const list = Array.from(document.querySelectorAll('main >div>div>div>div>div'));
|
||||
|
||||
list.forEach((item, idx) => {
|
||||
if (shouldSkip(item)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const saybtn = item.querySelector('button.rounded-md').cloneNode(true);
|
||||
saybtn.classList.add('chat-item-voice');
|
||||
saybtn.title = 'Say';
|
||||
saybtn.innerHTML = ICONS.voice;
|
||||
|
||||
item.querySelector('.self-end').appendChild(saybtn);
|
||||
|
||||
saybtn.onclick = () => handleClick(item, idx, saybtn);
|
||||
});
|
||||
}
|
||||
|
||||
function shouldSkip(item) {
|
||||
return (
|
||||
item.querySelector('.chat-item-voice') ||
|
||||
!item.querySelector('button.rounded-md') ||
|
||||
!item.querySelector('.self-end')
|
||||
);
|
||||
}
|
||||
|
||||
function handleClick(item, idx, saybtn) {
|
||||
const synth = window.speechSynthesis;
|
||||
const list = Array.from(document.querySelectorAll('main >div>div>div>div>div'));
|
||||
|
||||
if (currentUtterance && currentIndex !== -1) {
|
||||
synth.cancel();
|
||||
|
||||
if (idx === currentIndex) {
|
||||
saybtn.innerHTML = ICONS.voice;
|
||||
currentUtterance = null;
|
||||
currentIndex = -1;
|
||||
return;
|
||||
} else if (list[currentIndex].querySelector('.chat-item-voice')) {
|
||||
list[currentIndex].querySelector('.chat-item-voice').innerHTML = ICONS.voice;
|
||||
list[idx].querySelector('.chat-item-voice').innerHTML = ICONS.speaking;
|
||||
}
|
||||
}
|
||||
|
||||
const txt = item?.innerText?.trim() || '';
|
||||
if (!txt) return;
|
||||
|
||||
const utterance = new SpeechSynthesisUtterance(txt);
|
||||
const voices = speechSynthesis.getVoices();
|
||||
let voice = voices.find((voice) => voice.voiceURI === chatConf.speech_lang);
|
||||
|
||||
if (!voice) {
|
||||
voice = voices.find((voice) => voice.lang === 'en-US');
|
||||
}
|
||||
|
||||
utterance.voice = voice;
|
||||
currentIndex = idx;
|
||||
utterance.lang = voice.lang;
|
||||
|
||||
synth.speak(utterance);
|
||||
saybtn.innerHTML = ICONS.speaking;
|
||||
|
||||
currentUtterance = utterance;
|
||||
currentIndex = idx;
|
||||
|
||||
utterance.onend = () => {
|
||||
saybtn.innerHTML = ICONS.voice;
|
||||
currentUtterance = null;
|
||||
currentIndex = -1;
|
||||
};
|
||||
}
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
init();
|
||||
chatInit();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
document.addEventListener('DOMContentLoaded', chatInit);
|
||||
}
|
||||
|
384
scripts/cmd.js
vendored
384
scripts/cmd.js
vendored
@ -4,41 +4,41 @@
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/cmd.js
|
||||
*/
|
||||
|
||||
function init() {
|
||||
function cmdInit() {
|
||||
const styleDom = document.createElement('style');
|
||||
styleDom.innerHTML = `form {
|
||||
position: relative;
|
||||
}
|
||||
.chat-model-cmd-list {
|
||||
.chat-prompt-cmd-list {
|
||||
position: absolute;
|
||||
bottom: 60px;
|
||||
max-height: 100px;
|
||||
overflow: auto;
|
||||
z-index: 9999;
|
||||
}
|
||||
.chat-model-cmd-list>div {
|
||||
.chat-prompt-cmd-list>div {
|
||||
border: solid 2px rgba(80,80,80,.3);
|
||||
border-radius: 5px;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
html.dark .chat-model-cmd-list>div {
|
||||
html.dark .chat-prompt-cmd-list>div {
|
||||
background-color: #4a4a4a;
|
||||
}
|
||||
html.dark .chat-model-cmd-list .cmd-item {
|
||||
html.dark .chat-prompt-cmd-list .cmd-item {
|
||||
border-color: #666;
|
||||
}
|
||||
html.dark .chat-model-cmd-list .cmd-item b {
|
||||
html.dark .chat-prompt-cmd-list .cmd-item b {
|
||||
color: #e8e8e8;
|
||||
}
|
||||
html.dark .chat-model-cmd-list .cmd-item i {
|
||||
html.dark .chat-prompt-cmd-list .cmd-item i {
|
||||
color: #999;
|
||||
}
|
||||
html.dark .chat-model-cmd-list .cmd-item.selected {
|
||||
html.dark .chat-prompt-cmd-list .cmd-item.selected {
|
||||
background: rgba(59,130,246,.5);
|
||||
}
|
||||
|
||||
.chat-model-cmd-list .cmd-item {
|
||||
.chat-prompt-cmd-list .cmd-item {
|
||||
font-size: 12px;
|
||||
border-bottom: solid 1px rgba(80,80,80,.2);
|
||||
padding: 2px 4px;
|
||||
@ -46,13 +46,13 @@ function init() {
|
||||
user-select: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-model-cmd-list .cmd-item:last-child {
|
||||
.chat-prompt-cmd-list .cmd-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.chat-model-cmd-list .cmd-item.selected {
|
||||
.chat-prompt-cmd-list .cmd-item.selected {
|
||||
background: rgba(59,130,246,.3);
|
||||
}
|
||||
.chat-model-cmd-list .cmd-item b {
|
||||
.chat-prompt-cmd-list .cmd-item b {
|
||||
display: inline-block;
|
||||
width: 100px;
|
||||
overflow: hidden;
|
||||
@ -62,7 +62,7 @@ function init() {
|
||||
margin-right: 10px;
|
||||
color: #2a2a2a;
|
||||
}
|
||||
.chat-model-cmd-list .cmd-item i {
|
||||
.chat-prompt-cmd-list .cmd-item i {
|
||||
width: 100%;
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
@ -119,9 +119,9 @@ function init() {
|
||||
initDom();
|
||||
cmdTip();
|
||||
}
|
||||
if (mutation.target.getAttribute('class') === 'chat-model-cmd-list') {
|
||||
if (mutation.target.getAttribute('class') === 'chat-prompt-cmd-list') {
|
||||
// The `chatgpt prompt` fill can be done by clicking on the event.
|
||||
const searchDom = document.querySelector('form .chat-model-cmd-list>div');
|
||||
const searchDom = document.querySelector('form .chat-prompt-cmd-list>div');
|
||||
const searchInput = document.querySelector('form textarea');
|
||||
if (!searchDom) return;
|
||||
searchDom.addEventListener('click', (event) => {
|
||||
@ -140,203 +140,203 @@ function init() {
|
||||
subtree: true,
|
||||
});
|
||||
}, 300);
|
||||
}
|
||||
|
||||
async function cmdTip() {
|
||||
initDom();
|
||||
const chatModelJson = (await invoke('get_chat_model_cmd')) || {};
|
||||
const data = chatModelJson.data;
|
||||
if (data.length <= 0) return;
|
||||
async function cmdTip() {
|
||||
initDom();
|
||||
const chatPromptJson = (await invoke('get_chat_prompt_cmd')) || {};
|
||||
const data = chatPromptJson.data;
|
||||
if (data.length <= 0) return;
|
||||
|
||||
let modelDom = document.querySelector('.chat-model-cmd-list');
|
||||
if (!modelDom) {
|
||||
const dom = document.createElement('div');
|
||||
dom.classList.add('chat-model-cmd-list');
|
||||
document.querySelector('form').appendChild(dom);
|
||||
modelDom = document.querySelector('.chat-model-cmd-list');
|
||||
let promptDom = document.querySelector('.chat-prompt-cmd-list');
|
||||
if (!promptDom) {
|
||||
const dom = document.createElement('div');
|
||||
dom.classList.add('chat-prompt-cmd-list');
|
||||
document.querySelector('form').appendChild(dom);
|
||||
promptDom = document.querySelector('.chat-prompt-cmd-list');
|
||||
|
||||
// fix: tray window
|
||||
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
modelDom.style.bottom = '54px';
|
||||
}
|
||||
|
||||
const itemDom = (v) =>
|
||||
`<div class="cmd-item" title="${v.prompt}" data-cmd="${
|
||||
v.cmd
|
||||
}" data-prompt="${encodeURIComponent(v.prompt)}"><b title="${v.cmd}">/${v.cmd}</b><i>${
|
||||
v.act
|
||||
}</i></div>`;
|
||||
const renderList = (v) => {
|
||||
initDom();
|
||||
modelDom.innerHTML = `<div>${v.map(itemDom).join('')}</div>`;
|
||||
window.__CHAT_MODEL_CMD_PROMPT__ = v[0]?.prompt.trim();
|
||||
window.__CHAT_MODEL_CMD__ = v[0]?.cmd.trim();
|
||||
window.__cmd_list = modelDom.querySelectorAll('.cmd-item');
|
||||
window.__cmd_index = 0;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
};
|
||||
const setPrompt = (v = '') => {
|
||||
if (v.trim()) {
|
||||
window.__CHAT_MODEL_CMD_PROMPT__ = window.__CHAT_MODEL_CMD_PROMPT__?.replace(
|
||||
/\{([^{}]*)\}/,
|
||||
`{${v.trim()}}`,
|
||||
);
|
||||
// fix: tray window
|
||||
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
promptDom.style.bottom = '54px';
|
||||
}
|
||||
};
|
||||
const searchInput = document.querySelector('form textarea');
|
||||
|
||||
// Enter a command starting with `/` and press a space to automatically fill `chatgpt prompt`.
|
||||
// If more than one command appears in the search results, the first one will be used by default.
|
||||
function cmdKeydown(event) {
|
||||
if (!window.__CHAT_MODEL_CMD_PROMPT__) {
|
||||
if (
|
||||
!event.shiftKey &&
|
||||
event.keyCode === 13 &&
|
||||
__TAURI_METADATA__.__currentWindow.label === 'tray'
|
||||
) {
|
||||
const btn = document.querySelector('form button');
|
||||
if (btn) btn.click();
|
||||
const itemDom = (v) =>
|
||||
`<div class="cmd-item" title="${v.prompt}" data-cmd="${
|
||||
v.cmd
|
||||
}" data-prompt="${encodeURIComponent(v.prompt)}"><b title="${v.cmd}">/${v.cmd}</b><i>${
|
||||
v.act
|
||||
}</i></div>`;
|
||||
const renderList = (v) => {
|
||||
initDom();
|
||||
promptDom.innerHTML = `<div>${v.map(itemDom).join('')}</div>`;
|
||||
window.__CHAT_CMD_PROMPT__ = v[0]?.prompt.trim();
|
||||
window.__CHAT_CMD__ = v[0]?.cmd.trim();
|
||||
window.__cmd_list = promptDom.querySelectorAll('.cmd-item');
|
||||
window.__cmd_index = 0;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
};
|
||||
const setPrompt = (v = '') => {
|
||||
if (v.trim()) {
|
||||
window.__CHAT_CMD_PROMPT__ = window.__CHAT_CMD_PROMPT__?.replace(
|
||||
/\{([^{}]*)\}/,
|
||||
`{${v.trim()}}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
const searchInput = document.querySelector('form textarea');
|
||||
|
||||
// Enter a command starting with `/` and press a space to automatically fill `chatgpt prompt`.
|
||||
// If more than one command appears in the search results, the first one will be used by default.
|
||||
function cmdKeydown(event) {
|
||||
if (!window.__CHAT_CMD_PROMPT__) {
|
||||
if (
|
||||
!event.shiftKey &&
|
||||
event.keyCode === 13 &&
|
||||
__TAURI_METADATA__.__currentWindow.label === 'tray'
|
||||
) {
|
||||
const btn = document.querySelector('form button');
|
||||
if (btn) btn.click();
|
||||
event.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ------------------ Keyboard scrolling (ArrowUp | ArrowDown) --------------------------
|
||||
if (event.keyCode === 38 && window.__cmd_index > 0) {
|
||||
// ArrowUp
|
||||
window.__cmd_list[window.__cmd_index].classList.remove('selected');
|
||||
window.__cmd_index = window.__cmd_index - 1;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
window.__CHAT_CMD_PROMPT__ = decodeURIComponent(
|
||||
window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'),
|
||||
);
|
||||
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (event.keyCode === 40 && window.__cmd_index < window.__cmd_list.length - 1) {
|
||||
// ArrowDown
|
||||
window.__cmd_list[window.__cmd_index].classList.remove('selected');
|
||||
window.__cmd_index = window.__cmd_index + 1;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
window.__CHAT_CMD_PROMPT__ = decodeURIComponent(
|
||||
window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'),
|
||||
);
|
||||
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
const containerHeight = promptDom.offsetHeight;
|
||||
const itemHeight = window.__cmd_list[0].offsetHeight + 1;
|
||||
|
||||
const itemTop = window.__cmd_list[window.__cmd_index].offsetTop;
|
||||
const itemBottom = itemTop + itemHeight;
|
||||
if (itemTop < promptDom.scrollTop || itemBottom > promptDom.scrollTop + containerHeight) {
|
||||
promptDom.scrollTop = itemTop;
|
||||
}
|
||||
|
||||
// ------------------ TAB key replaces `{q}` tag content -------------------------------
|
||||
// feat: https://github.com/lencx/ChatGPT/issues/54
|
||||
if (event.keyCode === 9 && !window.__CHAT_STATUS__) {
|
||||
const strGroup = window.__CHAT_CMD_PROMPT__.match(/\{([^{}]*)\}/) || [];
|
||||
|
||||
if (strGroup[1]) {
|
||||
searchInput.value = `/${window.__CHAT_CMD__}` + ` {${strGroup[1]}}` + ' |-> ';
|
||||
window.__CHAT_STATUS__ = 1;
|
||||
} else {
|
||||
searchInput.value = window.__CHAT_CMD_PROMPT__;
|
||||
initDom();
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (window.__CHAT_STATUS__ === 1 && event.keyCode === 9) {
|
||||
// TAB
|
||||
const data = searchInput.value.split('|->');
|
||||
if (data[1]?.trim()) {
|
||||
setPrompt(data[1]);
|
||||
window.__CHAT_STATUS__ = 2;
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// input text
|
||||
if (window.__CHAT_STATUS__ === 2 && event.keyCode === 9) {
|
||||
// TAB
|
||||
searchInput.value = window.__CHAT_CMD_PROMPT__;
|
||||
promptDom.innerHTML = '';
|
||||
delete window.__CHAT_STATUS__;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// ------------------ type in a space to complete the fill ------------------------------------
|
||||
if (event.keyCode === 32) {
|
||||
searchInput.value = window.__CHAT_CMD_PROMPT__;
|
||||
promptDom.innerHTML = '';
|
||||
delete window.__CHAT_CMD_PROMPT__;
|
||||
}
|
||||
|
||||
// ------------------ send --------------------------------------------------------------------
|
||||
if (event.keyCode === 13 && window.__CHAT_CMD_PROMPT__) {
|
||||
// Enter
|
||||
const data = searchInput.value.split('|->');
|
||||
setPrompt(data[1]);
|
||||
|
||||
searchInput.value = window.__CHAT_CMD_PROMPT__;
|
||||
|
||||
initDom();
|
||||
|
||||
event.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
searchInput.removeEventListener('keydown', cmdKeydown, { capture: true });
|
||||
searchInput.addEventListener('keydown', cmdKeydown, { capture: true });
|
||||
|
||||
// ------------------ Keyboard scrolling (ArrowUp | ArrowDown) --------------------------
|
||||
if (event.keyCode === 38 && window.__cmd_index > 0) {
|
||||
// ArrowUp
|
||||
window.__cmd_list[window.__cmd_index].classList.remove('selected');
|
||||
window.__cmd_index = window.__cmd_index - 1;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
window.__CHAT_MODEL_CMD_PROMPT__ = decodeURIComponent(
|
||||
window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'),
|
||||
);
|
||||
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (event.keyCode === 40 && window.__cmd_index < window.__cmd_list.length - 1) {
|
||||
// ArrowDown
|
||||
window.__cmd_list[window.__cmd_index].classList.remove('selected');
|
||||
window.__cmd_index = window.__cmd_index + 1;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
window.__CHAT_MODEL_CMD_PROMPT__ = decodeURIComponent(
|
||||
window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'),
|
||||
);
|
||||
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
const containerHeight = modelDom.offsetHeight;
|
||||
const itemHeight = window.__cmd_list[0].offsetHeight + 1;
|
||||
|
||||
const itemTop = window.__cmd_list[window.__cmd_index].offsetTop;
|
||||
const itemBottom = itemTop + itemHeight;
|
||||
if (itemTop < modelDom.scrollTop || itemBottom > modelDom.scrollTop + containerHeight) {
|
||||
modelDom.scrollTop = itemTop;
|
||||
}
|
||||
|
||||
// ------------------ TAB key replaces `{q}` tag content -------------------------------
|
||||
// feat: https://github.com/lencx/ChatGPT/issues/54
|
||||
if (event.keyCode === 9 && !window.__CHAT_MODEL_STATUS__) {
|
||||
const strGroup = window.__CHAT_MODEL_CMD_PROMPT__.match(/\{([^{}]*)\}/) || [];
|
||||
|
||||
if (strGroup[1]) {
|
||||
searchInput.value = `/${window.__CHAT_MODEL_CMD__}` + ` {${strGroup[1]}}` + ' |-> ';
|
||||
window.__CHAT_MODEL_STATUS__ = 1;
|
||||
} else {
|
||||
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
function cmdInput() {
|
||||
if (searchInput.value === '') {
|
||||
initDom();
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (window.__CHAT_MODEL_STATUS__ === 1 && event.keyCode === 9) {
|
||||
// TAB
|
||||
const data = searchInput.value.split('|->');
|
||||
if (data[1]?.trim()) {
|
||||
setPrompt(data[1]);
|
||||
window.__CHAT_MODEL_STATUS__ = 2;
|
||||
if (window.__CHAT_STATUS__) return;
|
||||
|
||||
const query = searchInput.value;
|
||||
if (!query || !/^\//.test(query)) {
|
||||
initDom();
|
||||
return;
|
||||
}
|
||||
|
||||
// all cmd result
|
||||
if (query === '/') {
|
||||
renderList(data);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = data.filter((i) => new RegExp(query.substring(1)).test(i.cmd));
|
||||
if (result.length > 0) {
|
||||
renderList(result);
|
||||
} else {
|
||||
initDom();
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// input text
|
||||
if (window.__CHAT_MODEL_STATUS__ === 2 && event.keyCode === 9) {
|
||||
// TAB
|
||||
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
modelDom.innerHTML = '';
|
||||
delete window.__CHAT_MODEL_STATUS__;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// ------------------ type in a space to complete the fill ------------------------------------
|
||||
if (event.keyCode === 32) {
|
||||
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
modelDom.innerHTML = '';
|
||||
delete window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
}
|
||||
|
||||
// ------------------ send --------------------------------------------------------------------
|
||||
if (event.keyCode === 13 && window.__CHAT_MODEL_CMD_PROMPT__) {
|
||||
// Enter
|
||||
const data = searchInput.value.split('|->');
|
||||
setPrompt(data[1]);
|
||||
|
||||
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
|
||||
initDom();
|
||||
|
||||
event.preventDefault();
|
||||
}
|
||||
searchInput.removeEventListener('input', cmdInput);
|
||||
searchInput.addEventListener('input', cmdInput);
|
||||
}
|
||||
searchInput.removeEventListener('keydown', cmdKeydown, { capture: true });
|
||||
searchInput.addEventListener('keydown', cmdKeydown, { capture: true });
|
||||
}
|
||||
|
||||
function cmdInput() {
|
||||
if (searchInput.value === '') {
|
||||
initDom();
|
||||
}
|
||||
|
||||
if (window.__CHAT_MODEL_STATUS__) return;
|
||||
|
||||
const query = searchInput.value;
|
||||
if (!query || !/^\//.test(query)) {
|
||||
initDom();
|
||||
return;
|
||||
}
|
||||
|
||||
// all cmd result
|
||||
if (query === '/') {
|
||||
renderList(data);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = data.filter((i) => new RegExp(query.substring(1)).test(i.cmd));
|
||||
if (result.length > 0) {
|
||||
renderList(result);
|
||||
} else {
|
||||
initDom();
|
||||
}
|
||||
function initDom() {
|
||||
const promptDom = document.querySelector('.chat-prompt-cmd-list');
|
||||
if (promptDom) {
|
||||
promptDom.innerHTML = '';
|
||||
}
|
||||
searchInput.removeEventListener('input', cmdInput);
|
||||
searchInput.addEventListener('input', cmdInput);
|
||||
delete window.__CHAT_CMD_PROMPT__;
|
||||
delete window.__CHAT_CMD__;
|
||||
delete window.__CHAT_STATUS__;
|
||||
delete window.__cmd_list;
|
||||
delete window.__cmd_index;
|
||||
}
|
||||
}
|
||||
|
||||
function initDom() {
|
||||
const modelDom = document.querySelector('.chat-model-cmd-list');
|
||||
if (modelDom) {
|
||||
modelDom.innerHTML = '';
|
||||
}
|
||||
delete window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
delete window.__CHAT_MODEL_CMD__;
|
||||
delete window.__CHAT_MODEL_STATUS__;
|
||||
delete window.__cmd_list;
|
||||
delete window.__cmd_index;
|
||||
}
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
init();
|
||||
cmdInit();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
document.addEventListener('DOMContentLoaded', cmdInit);
|
||||
}
|
||||
|
392
scripts/core.js
vendored
392
scripts/core.js
vendored
@ -4,198 +4,234 @@
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/core.js
|
||||
*/
|
||||
|
||||
const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0];
|
||||
function transformCallback(callback = () => {}, once = false) {
|
||||
const identifier = uid();
|
||||
const prop = `_${identifier}`;
|
||||
Object.defineProperty(window, prop, {
|
||||
value: (result) => {
|
||||
if (once) {
|
||||
Reflect.deleteProperty(window, prop);
|
||||
}
|
||||
return callback(result);
|
||||
},
|
||||
writable: false,
|
||||
configurable: true,
|
||||
});
|
||||
return identifier;
|
||||
}
|
||||
async function invoke(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!window.__TAURI_POST_MESSAGE__) reject('__TAURI_POST_MESSAGE__ does not exist!');
|
||||
const callback = transformCallback((e) => {
|
||||
resolve(e);
|
||||
Reflect.deleteProperty(window, `_${error}`);
|
||||
}, true);
|
||||
const error = transformCallback((e) => {
|
||||
reject(e);
|
||||
Reflect.deleteProperty(window, `_${callback}`);
|
||||
}, true);
|
||||
window.__TAURI_POST_MESSAGE__({
|
||||
cmd,
|
||||
callback,
|
||||
error,
|
||||
...args,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function message(message) {
|
||||
invoke('messageDialog', {
|
||||
__tauriModule: 'Dialog',
|
||||
message: {
|
||||
cmd: 'messageDialog',
|
||||
message: message.toString(),
|
||||
title: null,
|
||||
type: null,
|
||||
buttonLabel: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
window.uid = uid;
|
||||
window.invoke = invoke;
|
||||
window.message = message;
|
||||
window.transformCallback = transformCallback;
|
||||
|
||||
async function init() {
|
||||
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
document.getElementsByTagName('html')[0].style['font-size'] = '70%';
|
||||
}
|
||||
|
||||
async function platform() {
|
||||
return invoke('platform', {
|
||||
__tauriModule: 'Os',
|
||||
message: { cmd: 'platform' },
|
||||
});
|
||||
}
|
||||
|
||||
if (__TAURI_METADATA__.__currentWindow.label !== 'tray') {
|
||||
const _platform = await platform();
|
||||
const chatConf = (await invoke('get_app_conf')) || {};
|
||||
if (/darwin/.test(_platform) && !chatConf.titlebar) {
|
||||
const topStyleDom = document.createElement('style');
|
||||
topStyleDom.innerHTML = `#chatgpt-app-window-top{position:fixed;top:0;z-index:999999999;width:100%;height:24px;background:transparent;cursor:grab;cursor:-webkit-grab;user-select:none;-webkit-user-select:none;}#chatgpt-app-window-top:active {cursor:grabbing;cursor:-webkit-grabbing;}`;
|
||||
document.head.appendChild(topStyleDom);
|
||||
const topDom = document.createElement('div');
|
||||
topDom.id = 'chatgpt-app-window-top';
|
||||
document.body.appendChild(topDom);
|
||||
|
||||
if (window.location.host === 'chat.openai.com') {
|
||||
const nav = document.body.querySelector('nav');
|
||||
if (nav) {
|
||||
const currentPaddingTop = parseInt(
|
||||
window
|
||||
.getComputedStyle(document.querySelector('nav'), null)
|
||||
.getPropertyValue('padding-top')
|
||||
.replace('px', ''),
|
||||
10,
|
||||
);
|
||||
const navStyleDom = document.createElement('style');
|
||||
navStyleDom.innerHTML = `nav{padding-top:${
|
||||
currentPaddingTop + topDom.clientHeight
|
||||
}px !important}`;
|
||||
document.head.appendChild(navStyleDom);
|
||||
function coreInit() {
|
||||
const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0];
|
||||
function transformCallback(callback = () => {}, once = false) {
|
||||
const identifier = uid();
|
||||
const prop = `_${identifier}`;
|
||||
Object.defineProperty(window, prop, {
|
||||
value: (result) => {
|
||||
if (once) {
|
||||
Reflect.deleteProperty(window, prop);
|
||||
}
|
||||
return callback(result);
|
||||
},
|
||||
writable: false,
|
||||
configurable: true,
|
||||
});
|
||||
return identifier;
|
||||
}
|
||||
|
||||
async function invoke(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!window.__TAURI_POST_MESSAGE__) reject('__TAURI_POST_MESSAGE__ does not exist!');
|
||||
const callback = transformCallback((e) => {
|
||||
resolve(e);
|
||||
Reflect.deleteProperty(window, `_${error}`);
|
||||
}, true);
|
||||
const error = transformCallback((e) => {
|
||||
reject(e);
|
||||
Reflect.deleteProperty(window, `_${callback}`);
|
||||
}, true);
|
||||
window.__TAURI_POST_MESSAGE__({
|
||||
cmd,
|
||||
callback,
|
||||
error,
|
||||
...args,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function message(message) {
|
||||
invoke('messageDialog', {
|
||||
__tauriModule: 'Dialog',
|
||||
message: {
|
||||
cmd: 'messageDialog',
|
||||
message: message.toString(),
|
||||
title: null,
|
||||
type: null,
|
||||
buttonLabel: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
window.uid = uid;
|
||||
window.invoke = invoke;
|
||||
window.message = message;
|
||||
window.transformCallback = transformCallback;
|
||||
|
||||
async function init() {
|
||||
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
document.getElementsByTagName('html')[0].style['font-size'] = '70%';
|
||||
}
|
||||
|
||||
async function platform() {
|
||||
return invoke('platform', {
|
||||
__tauriModule: 'Os',
|
||||
message: { cmd: 'platform' },
|
||||
});
|
||||
}
|
||||
|
||||
if (__TAURI_METADATA__.__currentWindow.label !== 'tray') {
|
||||
const _platform = await platform();
|
||||
const chatConf = (await invoke('get_app_conf')) || {};
|
||||
if (/darwin/.test(_platform) && !chatConf.titlebar) {
|
||||
const topStyleDom = document.createElement('style');
|
||||
topStyleDom.innerHTML = `#chatgpt-app-window-top{position:fixed;top:0;z-index:999999999;width:100%;height:24px;background:transparent;cursor:grab;cursor:-webkit-grab;user-select:none;-webkit-user-select:none;}#chatgpt-app-window-top:active {cursor:grabbing;cursor:-webkit-grabbing;}`;
|
||||
document.head.appendChild(topStyleDom);
|
||||
const topDom = document.createElement('div');
|
||||
topDom.id = 'chatgpt-app-window-top';
|
||||
document.body.appendChild(topDom);
|
||||
|
||||
if (window.location.host === 'chat.openai.com') {
|
||||
const nav = document.body.querySelector('nav');
|
||||
if (nav) {
|
||||
const currentPaddingTop = parseInt(
|
||||
window
|
||||
.getComputedStyle(document.querySelector('nav'), null)
|
||||
.getPropertyValue('padding-top')
|
||||
.replace('px', ''),
|
||||
10,
|
||||
);
|
||||
const navStyleDom = document.createElement('style');
|
||||
navStyleDom.innerHTML = `nav{padding-top:${
|
||||
currentPaddingTop + topDom.clientHeight
|
||||
}px !important}`;
|
||||
document.head.appendChild(navStyleDom);
|
||||
}
|
||||
}
|
||||
|
||||
topDom.addEventListener('mousedown', () => invoke('drag_window'));
|
||||
topDom.addEventListener('touchstart', () => invoke('drag_window'));
|
||||
topDom.addEventListener('dblclick', () => invoke('fullscreen'));
|
||||
}
|
||||
|
||||
topDom.addEventListener('mousedown', () => invoke('drag_window'));
|
||||
topDom.addEventListener('touchstart', () => invoke('drag_window'));
|
||||
topDom.addEventListener('dblclick', () => invoke('fullscreen'));
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
const origin = e.target.closest('a');
|
||||
if (!origin || !origin.target) return;
|
||||
if (origin && origin.href && origin.target !== '_self') {
|
||||
invoke('open_link', { url: origin.href });
|
||||
document.addEventListener('click', (e) => {
|
||||
const origin = e.target.closest('a');
|
||||
if (!origin || !origin.target) return;
|
||||
if (origin && origin.href && origin.target !== '_self') {
|
||||
invoke('open_link', { url: origin.href });
|
||||
}
|
||||
});
|
||||
|
||||
// Fix Chinese input method "Enter" on Safari
|
||||
document.addEventListener(
|
||||
'keydown',
|
||||
(e) => {
|
||||
if (e.keyCode == 229) e.stopPropagation();
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
if (window.location.host === 'chat.openai.com') {
|
||||
window.__sync_prompts = async function () {
|
||||
await invoke('sync_prompts', { time: Date.now() });
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// Fix Chinese input method "Enter" on Safari
|
||||
document.addEventListener(
|
||||
'keydown',
|
||||
(e) => {
|
||||
if (e.keyCode == 229) e.stopPropagation();
|
||||
},
|
||||
true,
|
||||
);
|
||||
coreZoom();
|
||||
|
||||
if (window.location.host === 'chat.openai.com') {
|
||||
window.__sync_prompts = async function () {
|
||||
await invoke('sync_prompts', { time: Date.now() });
|
||||
};
|
||||
window.__LoadingMask = LoadingMask;
|
||||
}
|
||||
|
||||
coreZoom();
|
||||
}
|
||||
|
||||
function coreZoom() {
|
||||
const styleDom = document.createElement('style');
|
||||
styleDom.innerHTML = `
|
||||
#ZoomTopTip {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 20px;
|
||||
background: #2a2a2a;
|
||||
color: #fafafa;
|
||||
padding: 20px 15px;
|
||||
border-bottom-left-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
z-index: 999999;
|
||||
box-shadow: 0 2px 2px 2px #d8d8d8;
|
||||
}
|
||||
.ZoomTopTipAni {
|
||||
transition: opacity 200ms, display 200ms;
|
||||
display: none;
|
||||
opacity: 0;
|
||||
}
|
||||
`;
|
||||
document.head.append(styleDom);
|
||||
const zoomTipDom = document.createElement('div');
|
||||
zoomTipDom.id = 'ZoomTopTip';
|
||||
document.body.appendChild(zoomTipDom);
|
||||
function zoom(callback) {
|
||||
if (window.zoomSetTimeout) clearTimeout(window.zoomSetTimeout);
|
||||
const htmlZoom = window.localStorage.getItem('htmlZoom') || '100%';
|
||||
const html = document.getElementsByTagName('html')[0];
|
||||
const zoom = callback(htmlZoom);
|
||||
html.style.zoom = zoom;
|
||||
window.localStorage.setItem('htmlZoom', zoom);
|
||||
zoomTipDom.innerHTML = zoom;
|
||||
zoomTipDom.style.display = 'block';
|
||||
zoomTipDom.classList.remove('ZoomTopTipAni');
|
||||
window.zoomSetTimeout = setTimeout(() => {
|
||||
zoomTipDom.classList.add('ZoomTopTipAni');
|
||||
}, 2500);
|
||||
}
|
||||
function zoomDefault() {
|
||||
const htmlZoom = window.localStorage.getItem('htmlZoom');
|
||||
if (htmlZoom) {
|
||||
document.getElementsByTagName('html')[0].style.zoom = htmlZoom;
|
||||
function coreZoom() {
|
||||
const styleDom = document.createElement('style');
|
||||
styleDom.innerHTML = `
|
||||
#ZoomTopTip {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 20px;
|
||||
background: #2a2a2a;
|
||||
color: #fafafa;
|
||||
padding: 20px 15px;
|
||||
border-bottom-left-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
z-index: 999999;
|
||||
box-shadow: 0 2px 2px 2px #d8d8d8;
|
||||
}
|
||||
.ZoomTopTipAni {
|
||||
transition: opacity 200ms, display 200ms;
|
||||
display: none;
|
||||
opacity: 0;
|
||||
}
|
||||
`;
|
||||
document.head.append(styleDom);
|
||||
const zoomTipDom = document.createElement('div');
|
||||
zoomTipDom.id = 'ZoomTopTip';
|
||||
document.body.appendChild(zoomTipDom);
|
||||
function zoom(callback) {
|
||||
if (window.zoomSetTimeout) clearTimeout(window.zoomSetTimeout);
|
||||
const htmlZoom = window.localStorage.getItem('htmlZoom') || '100%';
|
||||
const html = document.getElementsByTagName('html')[0];
|
||||
const zoom = callback(htmlZoom);
|
||||
html.style.zoom = zoom;
|
||||
window.localStorage.setItem('htmlZoom', zoom);
|
||||
zoomTipDom.innerHTML = zoom;
|
||||
zoomTipDom.style.display = 'block';
|
||||
zoomTipDom.classList.remove('ZoomTopTipAni');
|
||||
window.zoomSetTimeout = setTimeout(() => {
|
||||
zoomTipDom.classList.add('ZoomTopTipAni');
|
||||
}, 2500);
|
||||
}
|
||||
function zoomDefault() {
|
||||
const htmlZoom = window.localStorage.getItem('htmlZoom');
|
||||
if (htmlZoom) {
|
||||
document.getElementsByTagName('html')[0].style.zoom = htmlZoom;
|
||||
}
|
||||
}
|
||||
function zoomIn() {
|
||||
zoom((htmlZoom) => `${Math.min(parseInt(htmlZoom) + 10, 200)}%`);
|
||||
}
|
||||
function zoomOut() {
|
||||
zoom((htmlZoom) => `${Math.max(parseInt(htmlZoom) - 10, 30)}%`);
|
||||
}
|
||||
function zoom0() {
|
||||
zoom(() => `100%`);
|
||||
}
|
||||
zoomDefault();
|
||||
window.__zoomIn = zoomIn;
|
||||
window.__zoomOut = zoomOut;
|
||||
window.__zoom0 = zoom0;
|
||||
}
|
||||
function zoomIn() {
|
||||
zoom((htmlZoom) => `${Math.min(parseInt(htmlZoom) + 10, 200)}%`);
|
||||
|
||||
function LoadingMask(text = 'Loading...') {
|
||||
// 创建遮罩元素
|
||||
const loadingOverlay = document.createElement('div');
|
||||
|
||||
function startLoading() {
|
||||
loadingOverlay.style = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0,0,0,.5);
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;`;
|
||||
loadingOverlay.innerHTML = `<div style="color:#fff;font-weight:bold">${text}</div>`;
|
||||
document.body.style.overflow = 'hidden';
|
||||
document.body.appendChild(loadingOverlay);
|
||||
}
|
||||
|
||||
function stopLoading() {
|
||||
document.body.style.overflow = null;
|
||||
loadingOverlay.remove();
|
||||
}
|
||||
|
||||
return { startLoading, stopLoading };
|
||||
}
|
||||
function zoomOut() {
|
||||
zoom((htmlZoom) => `${Math.max(parseInt(htmlZoom) - 10, 30)}%`);
|
||||
}
|
||||
function zoom0() {
|
||||
zoom(() => `100%`);
|
||||
}
|
||||
zoomDefault();
|
||||
window.__zoomIn = zoomIn;
|
||||
window.__zoomOut = zoomOut;
|
||||
window.__zoom0 = zoom0;
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
init();
|
||||
coreInit();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
document.addEventListener('DOMContentLoaded', coreInit);
|
||||
}
|
||||
|
6
scripts/dalle2.js
vendored
6
scripts/dalle2.js
vendored
@ -4,7 +4,7 @@
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/dalle2.js
|
||||
*/
|
||||
|
||||
function init() {
|
||||
function dalle2Init() {
|
||||
document.addEventListener('click', (e) => {
|
||||
const origin = e.target.closest('a');
|
||||
if (!origin || !origin.target) return;
|
||||
@ -35,7 +35,7 @@ function init() {
|
||||
}
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
init();
|
||||
dalle2Init();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
document.addEventListener('DOMContentLoaded', dalle2Init);
|
||||
}
|
||||
|
60
scripts/export.js
vendored
60
scripts/export.js
vendored
@ -4,7 +4,7 @@
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/export.js
|
||||
*/
|
||||
|
||||
async function init() {
|
||||
async function exportInit() {
|
||||
if (window.location.pathname === '/auth/login') return;
|
||||
const buttonOuterHTMLFallback = `<button class="btn flex justify-center gap-2 btn-neutral">Try Again</button>`;
|
||||
removeButtons();
|
||||
@ -153,7 +153,7 @@ async function init() {
|
||||
}
|
||||
|
||||
async function exportMarkdown() {
|
||||
const content = Array.from(document.querySelectorAll('main .items-center>div'))
|
||||
const content = Array.from(document.querySelectorAll('main div.group'))
|
||||
.map((i) => {
|
||||
let j = i.cloneNode(true);
|
||||
if (/dark\:bg-gray-800/.test(i.getAttribute('class'))) {
|
||||
@ -168,25 +168,29 @@ async function init() {
|
||||
await invoke('download_list', { pathname: 'chat.notes.json', filename, id, dir: 'notes' });
|
||||
}
|
||||
|
||||
function downloadThread({ as = Format.PNG } = {}) {
|
||||
async function downloadThread({ asF = Format.PNG } = {}) {
|
||||
const { startLoading, stopLoading } = new window.__LoadingMask('Exporting in progress...');
|
||||
startLoading();
|
||||
const elements = new Elements();
|
||||
elements.fixLocation();
|
||||
await elements.fixLocation();
|
||||
const pixelRatio = window.devicePixelRatio;
|
||||
const minRatio = as === Format.PDF ? 2 : 2.5;
|
||||
const minRatio = asF === Format.PDF ? 2 : 2.5;
|
||||
window.devicePixelRatio = Math.max(pixelRatio, minRatio);
|
||||
|
||||
html2canvas(elements.thread, {
|
||||
letterRendering: true,
|
||||
}).then(async function (canvas) {
|
||||
useCORS: true,
|
||||
}).then((canvas) => {
|
||||
elements.restoreLocation();
|
||||
window.devicePixelRatio = pixelRatio;
|
||||
const imgData = canvas.toDataURL('image/png');
|
||||
requestAnimationFrame(() => {
|
||||
if (as === Format.PDF) {
|
||||
return handlePdf(imgData, canvas, pixelRatio);
|
||||
requestAnimationFrame(async () => {
|
||||
if (asF === Format.PDF) {
|
||||
await handlePdf(imgData, canvas, pixelRatio);
|
||||
} else {
|
||||
handleImg(imgData);
|
||||
await handleImg(imgData);
|
||||
}
|
||||
stopLoading();
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -219,8 +223,7 @@ async function init() {
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
// this.threadWrapper = document.querySelector(".cdfdFe");
|
||||
this.spacer = document.querySelector("[class*='h-48'].w-full.flex-shrink-0");
|
||||
this.spacer = document.querySelector("main div[class*='h-'].flex-shrink-0");
|
||||
this.thread = document.querySelector(
|
||||
"[class*='react-scroll-to-bottom']>[class*='react-scroll-to-bottom']>div",
|
||||
);
|
||||
@ -232,8 +235,6 @@ async function init() {
|
||||
|
||||
// h-full overflow-y-auto
|
||||
this.positionForm = document.querySelector('form').parentNode;
|
||||
// this.styledThread = document.querySelector("main");
|
||||
// this.threadContent = document.querySelector(".gAnhyd");
|
||||
this.scroller = Array.from(document.querySelectorAll('[class*="react-scroll-to"]')).filter(
|
||||
(el) => el.classList.contains('h-full'),
|
||||
)[0];
|
||||
@ -245,8 +246,9 @@ async function init() {
|
||||
|
||||
this.hiddens = Array.from(document.querySelectorAll('.overflow-hidden'));
|
||||
this.images = Array.from(document.querySelectorAll('img[srcset]'));
|
||||
this.chatImages = Array.from(document.querySelectorAll('main img[src]'));
|
||||
}
|
||||
fixLocation() {
|
||||
async fixLocation() {
|
||||
this.hiddens.forEach((el) => {
|
||||
el.classList.remove('overflow-hidden');
|
||||
});
|
||||
@ -261,10 +263,17 @@ async function init() {
|
||||
img.setAttribute('srcset_old', srcset);
|
||||
img.setAttribute('srcset', '');
|
||||
});
|
||||
//Fix to the text shifting down when generating the canvas
|
||||
document.body.style.lineHeight = '0.5';
|
||||
|
||||
const chatImagePromises = this.chatImages.map(async (img) => {
|
||||
const src = img.getAttribute('src');
|
||||
if (!/^http/.test(src)) return;
|
||||
const data = await invoke('fetch_image', { url: src });
|
||||
const blob = new Blob([new Uint8Array(data)], { type: 'image/png' });
|
||||
img.src = URL.createObjectURL(blob);
|
||||
});
|
||||
await Promise.all(chatImagePromises);
|
||||
}
|
||||
restoreLocation() {
|
||||
async restoreLocation() {
|
||||
this.hiddens.forEach((el) => {
|
||||
el.classList.add('overflow-hidden');
|
||||
});
|
||||
@ -274,18 +283,11 @@ async function init() {
|
||||
this.positionForm.style.display = null;
|
||||
this.scroller.classList.add('h-full');
|
||||
this.scroller.style.minHeight = null;
|
||||
this.images.forEach((img) => {
|
||||
const srcset = img.getAttribute('srcset_old');
|
||||
img.setAttribute('srcset', srcset);
|
||||
img.setAttribute('srcset_old', '');
|
||||
});
|
||||
document.body.style.lineHeight = null;
|
||||
}
|
||||
}
|
||||
|
||||
function setIcon(type) {
|
||||
return {
|
||||
// link: `<svg class="chatappico" viewBox="0 0 1024 1024"><path d="M1007.382 379.672L655.374 75.702C624.562 49.092 576 70.694 576 112.03v160.106C254.742 275.814 0 340.2 0 644.652c0 122.882 79.162 244.618 166.666 308.264 27.306 19.862 66.222-5.066 56.154-37.262C132.132 625.628 265.834 548.632 576 544.17V720c0 41.4 48.6 62.906 79.374 36.328l352.008-304c22.142-19.124 22.172-53.506 0-72.656z" p-id="8506" fill="currentColor"></path></svg>`,
|
||||
png: `<svg class="chatappico" viewBox="0 0 1070 1024"><path d="M981.783273 0H85.224727C38.353455 0 0 35.374545 0 83.083636v844.893091c0 47.616 38.353455 86.574545 85.178182 86.574546h903.633454c46.917818 0 81.733818-38.958545 81.733819-86.574546V83.083636C1070.592 35.374545 1028.701091 0 981.783273 0zM335.825455 135.912727c74.193455 0 134.330182 60.974545 134.330181 136.285091 0 75.170909-60.136727 136.192-134.330181 136.192-74.286545 0-134.516364-61.021091-134.516364-136.192 0-75.264 60.229818-136.285091 134.516364-136.285091z m-161.512728 745.937455a41.890909 41.890909 0 0 1-27.648-10.379637 43.752727 43.752727 0 0 1-4.654545-61.067636l198.097454-255.162182a42.123636 42.123636 0 0 1 57.716364-6.702545l116.549818 128.139636 286.906182-352.814545c14.615273-18.711273 90.251636-106.775273 135.866182-6.935273 0.093091-0.093091 0.093091 112.965818 0.232727 247.761455 0.093091 140.8 0.093091 317.067636 0.093091 317.067636-1.024-0.093091-762.740364 0.093091-763.112727 0.093091z" fill="currentColor"></path></svg>`,
|
||||
pdf: `<svg class="chatappico pdf" viewBox="0 0 1024 1024"><path d="M821.457602 118.382249H205.725895c-48.378584 0-87.959995 39.583368-87.959996 87.963909v615.731707c0 48.378584 39.581411 87.959995 87.959996 87.959996h615.733664c48.380541 0 87.961952-39.581411 87.961952-87.959996V206.346158c-0.001957-48.378584-39.583368-87.963909-87.963909-87.963909zM493.962468 457.544987c-10.112054 32.545237-21.72487 82.872662-38.806571 124.248336-8.806957 22.378397-8.380404 18.480717-15.001764 32.609808l5.71738-1.851007c58.760658-16.443827 99.901532-20.519564 138.162194-27.561607-7.67796-6.06371-14.350194-10.751884-19.631237-15.586807-26.287817-29.101504-35.464584-34.570387-70.440002-111.862636v0.003913z m288.36767 186.413594c-7.476424 8.356924-20.670227 13.191847-40.019704 13.191847-33.427694 0-63.808858-9.229597-107.79277-31.660824-75.648648 8.356924-156.097 17.214754-201.399704 31.729308-2.199293 0.876587-4.832967 1.759043-7.916674 3.077836-54.536215 93.237125-95.031389 132.767663-130.621199 131.19646-11.286054-0.49895-27.694661-7.044-32.973748-10.11988l-6.52157-6.196764-2.29517-4.353583c-3.07588-7.91863-3.954423-15.395054-2.197337-23.751977 4.838837-23.309771 29.907651-60.251638 82.686779-93.237126 8.356924-6.159587 27.430511-15.897917 45.020944-24.25484 13.311204-21.177004 19.45905-34.744531 36.341171-72.259702 19.102937-45.324228 36.505531-99.492589 47.500041-138.191543v-0.44025c-16.267727-53.219378-25.945401-89.310095-9.67376-147.80856 3.958337-16.71189 18.46702-33.864031 34.748444-33.864031h10.552304c10.115967 0 19.791684 3.520043 26.829814 10.552304 29.029107 29.031064 15.39114 103.824649 0.8805 162.323113-0.8805 2.63563-1.322707 4.832967-1.761 6.153717 17.59239 49.697378 45.400538 98.774492 73.108895 121.647926 11.436717 8.791304 22.638634 18.899444 36.71098 26.814161 19.791684-2.20125 37.517128-4.11487 55.547812-4.11487 54.540128 0 87.525615 9.67963 100.279169 30.351814 4.400543 7.034217 6.595923 15.389184 5.281043 24.1844-0.44025 10.996467-4.39663 21.112434-12.31526 29.031064z m-27.796407-36.748157c-4.394673-4.398587-17.024957-16.936907-78.601259-16.936907-3.073923 0-10.622744-0.784623-14.57521 3.612007 32.104987 14.072347 62.830525 24.757704 83.058545 24.757703 3.083707 0 5.72325-0.442207 8.356923-0.876586h1.759044c2.20125-0.8805 3.520043-1.324663 3.960293-5.71738-0.87463-1.324663-1.757087-3.083707-3.958336-4.838837z m-387.124553 63.041845c-9.237424 5.27713-16.71189 10.112054-21.112433 13.634053-31.226444 28.586901-51.018128 57.616008-53.217422 74.331812 19.789727-6.59788 45.737084-35.626987 74.329855-87.961952v-0.003913z m125.574957-297.822284l2.197336-1.761c3.079793-14.072347 5.232127-29.189554 7.87167-38.869184l1.318794-7.036174c4.39663-25.070771 2.71781-39.720334-4.76057-50.272637l-6.59788-2.20125a57.381208 57.381208 0 0 0-3.079794 5.27713c-7.474467 18.47289-7.063567 55.283661 3.0524 94.865072l-0.001956-0.001957z" fill="currentColor"></path></svg>`,
|
||||
md: `<svg class="chatappico md" viewBox="0 0 1024 1024" width="200" height="200"><path d="M128 128h768a42.666667 42.666667 0 0 1 42.666667 42.666667v682.666666a42.666667 42.666667 0 0 1-42.666667 42.666667H128a42.666667 42.666667 0 0 1-42.666667-42.666667V170.666667a42.666667 42.666667 0 0 1 42.666667-42.666667z m170.666667 533.333333v-170.666666l85.333333 85.333333 85.333333-85.333333v170.666666h85.333334v-298.666666h-85.333334l-85.333333 85.333333-85.333333-85.333333H213.333333v298.666666h85.333334z m469.333333-128v-170.666666h-85.333333v170.666666h-85.333334l128 128 128-128h-85.333333z" p-id="1381" fill="currentColor"></path></svg>`,
|
||||
@ -301,7 +303,7 @@ async function init() {
|
||||
const hours = String(now.getHours()).padStart(2, '0');
|
||||
const minutes = String(now.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(now.getSeconds()).padStart(2, '0');
|
||||
const formattedDateTime = `${year}_${month}_${day}_${hours}_${minutes}_${seconds}`;
|
||||
const formattedDateTime = `${year}_${month}_${day}-${hours}${minutes}${seconds}`;
|
||||
return formattedDateTime;
|
||||
}
|
||||
|
||||
@ -313,10 +315,10 @@ async function init() {
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('resize', init);
|
||||
window.addEventListener('resize', exportInit);
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
init();
|
||||
exportInit();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
document.addEventListener('DOMContentLoaded', exportInit);
|
||||
}
|
||||
|
5
scripts/main.js
vendored
Normal file
5
scripts/main.js
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
// *** ChatGPT User Script ***
|
||||
// @github: https://github.com/lencx/ChatGPT
|
||||
// @path: $HOME/.chatgpt/scripts/main.js
|
||||
|
||||
console.log('Hello, ChatGPT!');
|
@ -12,6 +12,10 @@
|
||||
"name": "cmd.js",
|
||||
"version": "0.1.0"
|
||||
},
|
||||
{
|
||||
"name": "chat.js",
|
||||
"version": "0.1.0"
|
||||
},
|
||||
{
|
||||
"name": "core.js",
|
||||
"version": "0.1.0"
|
||||
|
6
scripts/popup.core.js
vendored
6
scripts/popup.core.js
vendored
@ -4,7 +4,7 @@
|
||||
* @url https://github.com/lencx/ChatGPT/tree/main/scripts/popup.core.js
|
||||
*/
|
||||
|
||||
async function init() {
|
||||
async function popupCoreInit() {
|
||||
const chatConf = (await invoke('get_app_conf')) || {};
|
||||
if (!chatConf.popup_search) return;
|
||||
if (!window.FloatingUIDOM) return;
|
||||
@ -77,7 +77,7 @@ async function init() {
|
||||
}
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
init();
|
||||
popupCoreInit();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
document.addEventListener('DOMContentLoaded', popupCoreInit);
|
||||
}
|
||||
|
44
sponsor.html
Normal file
44
sponsor.html
Normal file
@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ChatGPT</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
p {
|
||||
margin: 0;
|
||||
padding: 5px 10px;
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: #686868;
|
||||
}
|
||||
a {
|
||||
margin: 20px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
img {
|
||||
width: 240px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p>🙏 Thank you for your support, which can help ChatGPT Free version to develop better!</p>
|
||||
<p>🙏 感谢您的支持,可以让 ChatGPT 免费版更好的发展!</p>
|
||||
<a target="_blank" href="https://www.buymeacoffee.com/lencx">
|
||||
<img style="width: 160px" src="/bmc.png" />
|
||||
</a>
|
||||
<img src="/wxp.png" />
|
||||
</body>
|
||||
</html>
|
@ -22,11 +22,11 @@ thiserror = "1.0.38"
|
||||
walkdir = "2.3.2"
|
||||
regex = "1.7.0"
|
||||
reqwest = "0.11.13"
|
||||
wry = "0.24.1"
|
||||
dark-light = "1.0.0"
|
||||
wry = "0.*"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tokio = { version = "1.23.0", features = ["macros"] }
|
||||
tauri = { version = "1.2.4", features = ["devtools", "fs-create-dir", "fs-exists", "fs-read-dir", "fs-read-file", "fs-remove-dir", "fs-remove-file", "fs-write-file", "global-shortcut", "global-shortcut-all", "os-all", "path-all", "process-all", "shell-open-api", "system-tray", "updater"] }
|
||||
tauri = { version = "1.3.0", features = ["devtools", "fs-create-dir", "fs-exists", "fs-read-dir", "fs-read-file", "fs-remove-dir", "fs-remove-file", "fs-write-file", "global-shortcut", "global-shortcut-all", "os-all", "path-all", "process-all", "shell-all", "shell-open-api", "system-tray", "updater"] }
|
||||
tauri-plugin-positioner = { git = "https://github.com/lencx/tauri-plugins-workspace", features = ["system-tray"] }
|
||||
tauri-plugin-log = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev", features = ["colored"] }
|
||||
tauri-plugin-autostart = { git = "https://github.com/lencx/tauri-plugins-workspace", branch = "dev" }
|
||||
|
@ -18,30 +18,31 @@ pub fn fullscreen(app: AppHandle) {
|
||||
}
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn download(app: AppHandle, name: String, blob: Vec<u8>) {
|
||||
let win = app.app_handle().get_window("core");
|
||||
let path = utils::app_root().join(PathBuf::from(name));
|
||||
utils::create_file(&path).unwrap();
|
||||
fs::write(&path, blob).unwrap();
|
||||
tauri::api::dialog::message(
|
||||
win.as_ref(),
|
||||
"Save File",
|
||||
format!("PATH: {}", path.display()),
|
||||
);
|
||||
}
|
||||
// #[command]
|
||||
// pub fn download(app: AppHandle, name: String, blob: Vec<u8>) {
|
||||
// let win = app.app_handle().get_window("core");
|
||||
// let path = utils::app_root().join(PathBuf::from(name));
|
||||
// utils::create_file(&path).unwrap();
|
||||
// fs::write(&path, blob).unwrap();
|
||||
// tauri::api::dialog::message(
|
||||
// win.as_ref(),
|
||||
// "Save File",
|
||||
// format!("PATH: {}", path.display()),
|
||||
// );
|
||||
// }
|
||||
|
||||
#[command]
|
||||
pub fn save_file(app: AppHandle, name: String, content: String) {
|
||||
let win = app.app_handle().get_window("core");
|
||||
pub fn save_file(_app: AppHandle, name: String, content: String) {
|
||||
// let win = app.app_handle().get_window("core");
|
||||
let path = utils::app_root().join(PathBuf::from(name));
|
||||
utils::create_file(&path).unwrap();
|
||||
fs::write(&path, content).unwrap();
|
||||
tauri::api::dialog::message(
|
||||
win.as_ref(),
|
||||
"Save File",
|
||||
format!("PATH: {}", path.display()),
|
||||
);
|
||||
utils::open_file(path);
|
||||
// tauri::api::dialog::message(
|
||||
// win.as_ref(),
|
||||
// "Save File",
|
||||
// format!("PATH: {}", path.display()),
|
||||
// );
|
||||
}
|
||||
|
||||
#[command]
|
||||
@ -59,6 +60,13 @@ pub fn open_file(path: PathBuf) {
|
||||
utils::open_file(path);
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn download_file(name: String, blob: Vec<u8>) {
|
||||
let file = tauri::api::path::download_dir().unwrap().join(name);
|
||||
fs::write(&file, blob).unwrap();
|
||||
utils::open_file(file);
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn get_data(app: AppHandle, url: String, is_msg: Option<bool>) -> Option<String> {
|
||||
let is_msg = is_msg.unwrap_or(false);
|
||||
@ -72,3 +80,10 @@ pub async fn get_data(app: AppHandle, url: String, is_msg: Option<bool>) -> Opti
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn fetch_image(url: String) -> Vec<u8> {
|
||||
let response = reqwest::get(url).await.unwrap();
|
||||
let bytes = response.bytes().await.unwrap();
|
||||
bytes.to_vec()
|
||||
}
|
||||
|
@ -10,41 +10,46 @@ use tauri::{api, command, AppHandle, Manager};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
#[command]
|
||||
pub fn get_chat_model_cmd() -> serde_json::Value {
|
||||
let path = utils::app_root().join("chat.model.cmd.json");
|
||||
pub fn get_chat_prompt_cmd() -> serde_json::Value {
|
||||
let path = utils::app_root().join("chat.prompt.cmd.json");
|
||||
let content = fs::read_to_string(path).unwrap_or_else(|_| r#"{"data":[]}"#.to_string());
|
||||
serde_json::from_str(&content).unwrap()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PromptRecord {
|
||||
pub struct PromptBaseRecord {
|
||||
pub cmd: Option<String>,
|
||||
pub act: String,
|
||||
pub prompt: String,
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn parse_prompt(data: String) -> Vec<PromptRecord> {
|
||||
pub fn parse_prompt(data: String) -> Option<Vec<PromptBaseRecord>> {
|
||||
let mut rdr = csv::Reader::from_reader(data.as_bytes());
|
||||
let mut list = vec![];
|
||||
for result in rdr.deserialize() {
|
||||
let record: PromptRecord = result.unwrap_or_else(|err| {
|
||||
error!("parse_prompt: {}", err);
|
||||
PromptRecord {
|
||||
cmd: None,
|
||||
act: "".to_string(),
|
||||
prompt: "".to_string(),
|
||||
|
||||
for result in rdr.deserialize::<PromptBaseRecord>() {
|
||||
match result {
|
||||
Ok(record) => {
|
||||
if !record.act.is_empty() {
|
||||
list.push(record);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!("parse_prompt: {}", err);
|
||||
}
|
||||
});
|
||||
if !record.act.is_empty() {
|
||||
list.push(record);
|
||||
}
|
||||
}
|
||||
list
|
||||
|
||||
if list.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(list)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||
pub struct ModelRecord {
|
||||
pub struct PromptRecord {
|
||||
pub cmd: String,
|
||||
pub act: String,
|
||||
pub prompt: String,
|
||||
@ -53,15 +58,15 @@ pub struct ModelRecord {
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn cmd_list() -> Vec<ModelRecord> {
|
||||
pub fn cmd_list() -> Vec<PromptRecord> {
|
||||
let mut list = vec![];
|
||||
for entry in WalkDir::new(utils::app_root().join("cache_model"))
|
||||
for entry in WalkDir::new(utils::app_root().join("cache_prompts"))
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
{
|
||||
let file = fs::read_to_string(entry.path().display().to_string());
|
||||
if let Ok(v) = file {
|
||||
let data: Vec<ModelRecord> = serde_json::from_str(&v).unwrap_or_else(|_| vec![]);
|
||||
let data: Vec<PromptRecord> = serde_json::from_str(&v).unwrap_or_else(|_| vec![]);
|
||||
let enable_list = data.into_iter().filter(|v| v.enable);
|
||||
list.extend(enable_list)
|
||||
}
|
||||
@ -159,96 +164,100 @@ pub fn download_list(pathname: &str, dir: &str, filename: Option<String>, id: Op
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn sync_prompts(app: AppHandle, time: u64) -> Option<Vec<ModelRecord>> {
|
||||
pub async fn sync_prompts(app: AppHandle, time: u64) -> Option<Vec<PromptRecord>> {
|
||||
let res = utils::get_data(GITHUB_PROMPTS_CSV_URL, Some(&app))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
if let Some(v) = res {
|
||||
let data = parse_prompt(v)
|
||||
.iter()
|
||||
.map(move |i| ModelRecord {
|
||||
cmd: if i.cmd.is_some() {
|
||||
i.cmd.clone().unwrap()
|
||||
} else {
|
||||
utils::gen_cmd(i.act.clone())
|
||||
},
|
||||
act: i.act.clone(),
|
||||
prompt: i.prompt.clone(),
|
||||
tags: vec!["chatgpt-prompts".to_string()],
|
||||
enable: true,
|
||||
})
|
||||
.collect::<Vec<ModelRecord>>();
|
||||
|
||||
let data2 = data.clone();
|
||||
|
||||
let model = utils::app_root().join("chat.model.json");
|
||||
let model_cmd = utils::app_root().join("chat.model.cmd.json");
|
||||
let chatgpt_prompts = utils::app_root()
|
||||
.join("cache_model")
|
||||
.join("chatgpt_prompts.json");
|
||||
|
||||
if !utils::exists(&model) {
|
||||
fs::write(
|
||||
&model,
|
||||
serde_json::json!({
|
||||
"name": "ChatGPT Model",
|
||||
"link": "https://github.com/lencx/ChatGPT"
|
||||
if let Some(data) = parse_prompt(v) {
|
||||
let transformed_data = data
|
||||
.iter()
|
||||
.map(|i| PromptRecord {
|
||||
cmd: if let Some(cmd) = &i.cmd {
|
||||
cmd.clone()
|
||||
} else {
|
||||
utils::gen_cmd(i.act.clone())
|
||||
},
|
||||
act: i.act.clone(),
|
||||
prompt: i.prompt.clone(),
|
||||
tags: vec!["awesome-chatgpt-prompts".to_string()],
|
||||
enable: true,
|
||||
})
|
||||
.to_string(),
|
||||
.collect::<Vec<PromptRecord>>();
|
||||
|
||||
let prompts = utils::app_root().join("chat.prompt.json");
|
||||
let prompt_cmd = utils::app_root().join("chat.prompt.cmd.json");
|
||||
let chatgpt_prompts = utils::app_root()
|
||||
.join("cache_prompts")
|
||||
.join("chatgpt_prompts.json");
|
||||
|
||||
if !utils::exists(&prompts) {
|
||||
fs::write(
|
||||
&prompts,
|
||||
serde_json::json!({
|
||||
"name": "ChatGPT Prompts",
|
||||
"link": "https://github.com/lencx/ChatGPT"
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// chatgpt_prompts.json
|
||||
fs::write(
|
||||
chatgpt_prompts,
|
||||
serde_json::to_string_pretty(&transformed_data).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let cmd_data = cmd_list();
|
||||
|
||||
// chat.prompt.cmd.json
|
||||
fs::write(
|
||||
prompt_cmd,
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"name": "ChatGPT CMD",
|
||||
"last_updated": time,
|
||||
"data": cmd_data,
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut kv = HashMap::new();
|
||||
kv.insert(
|
||||
"sync_prompts".to_string(),
|
||||
serde_json::json!({ "id": "chatgpt_prompts", "last_updated": time }),
|
||||
);
|
||||
let prompts_data = utils::merge(
|
||||
&serde_json::from_str(&fs::read_to_string(&prompts).unwrap()).unwrap(),
|
||||
&kv,
|
||||
);
|
||||
|
||||
// chat.prompt.json
|
||||
fs::write(
|
||||
prompts,
|
||||
serde_json::to_string_pretty(&prompts_data).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// refresh window
|
||||
api::dialog::message(
|
||||
app.get_window("core").as_ref(),
|
||||
"Sync Prompts",
|
||||
"Prompts data has been synchronized!",
|
||||
);
|
||||
window::cmd::window_reload(app.clone(), "core");
|
||||
window::cmd::window_reload(app, "tray");
|
||||
|
||||
return Some(transformed_data);
|
||||
}
|
||||
|
||||
// chatgpt_prompts.json
|
||||
fs::write(
|
||||
chatgpt_prompts,
|
||||
serde_json::to_string_pretty(&data).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let cmd_data = cmd_list();
|
||||
|
||||
// chat.model.cmd.json
|
||||
fs::write(
|
||||
model_cmd,
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"name": "ChatGPT CMD",
|
||||
"last_updated": time,
|
||||
"data": cmd_data,
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut kv = HashMap::new();
|
||||
kv.insert(
|
||||
"sync_prompts".to_string(),
|
||||
serde_json::json!({ "id": "chatgpt_prompts", "last_updated": time }),
|
||||
);
|
||||
let model_data = utils::merge(
|
||||
&serde_json::from_str(&fs::read_to_string(&model).unwrap()).unwrap(),
|
||||
&kv,
|
||||
);
|
||||
|
||||
// chat.model.json
|
||||
fs::write(model, serde_json::to_string_pretty(&model_data).unwrap()).unwrap();
|
||||
|
||||
// refresh window
|
||||
api::dialog::message(
|
||||
app.get_window("core").as_ref(),
|
||||
"Sync Prompts",
|
||||
"ChatGPT Prompts data has been synchronized!",
|
||||
);
|
||||
window::cmd::window_reload(app.clone(), "core");
|
||||
window::cmd::window_reload(app, "tray");
|
||||
|
||||
return Some(data2);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn sync_user_prompts(url: String, data_type: String) -> Option<Vec<ModelRecord>> {
|
||||
pub async fn sync_user_prompts(url: String, data_type: String) -> Option<Vec<PromptRecord>> {
|
||||
info!("sync_user_prompts: url => {}", url);
|
||||
let res = utils::get_data(&url, None).await.unwrap_or_else(|err| {
|
||||
error!("chatgpt_http: {}", err);
|
||||
@ -256,37 +265,40 @@ pub async fn sync_user_prompts(url: String, data_type: String) -> Option<Vec<Mod
|
||||
});
|
||||
|
||||
if let Some(v) = res {
|
||||
let data;
|
||||
if data_type == "csv" {
|
||||
let data: Option<Vec<PromptBaseRecord>> = if data_type == "csv" {
|
||||
info!("chatgpt_http_csv_parse");
|
||||
data = parse_prompt(v);
|
||||
parse_prompt(v)
|
||||
} else if data_type == "json" {
|
||||
info!("chatgpt_http_json_parse");
|
||||
data = serde_json::from_str(&v).unwrap_or_else(|err| {
|
||||
error!("chatgpt_http_json_parse: {}", err);
|
||||
vec![]
|
||||
});
|
||||
match serde_json::from_str::<Vec<PromptBaseRecord>>(&v) {
|
||||
Ok(parsed) => Some(parsed),
|
||||
Err(err) => {
|
||||
error!("chatgpt_http_json_parse: {}", err);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
error!("chatgpt_http_unknown_type");
|
||||
data = vec![];
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(base_records) = data {
|
||||
let data = base_records
|
||||
.iter()
|
||||
.map(|i| PromptRecord {
|
||||
cmd: i
|
||||
.cmd
|
||||
.clone()
|
||||
.unwrap_or_else(|| utils::gen_cmd(i.act.clone())),
|
||||
act: i.act.clone(),
|
||||
prompt: i.prompt.clone(),
|
||||
tags: vec!["user-sync".to_string()],
|
||||
enable: true,
|
||||
})
|
||||
.collect::<Vec<PromptRecord>>();
|
||||
|
||||
return Some(data);
|
||||
}
|
||||
|
||||
let data = data
|
||||
.iter()
|
||||
.map(move |i| ModelRecord {
|
||||
cmd: if i.cmd.is_some() {
|
||||
i.cmd.clone().unwrap()
|
||||
} else {
|
||||
utils::gen_cmd(i.act.clone())
|
||||
},
|
||||
act: i.act.clone(),
|
||||
prompt: i.prompt.clone(),
|
||||
tags: vec!["user-sync".to_string()],
|
||||
enable: true,
|
||||
})
|
||||
.collect::<Vec<ModelRecord>>();
|
||||
|
||||
return Some(data);
|
||||
}
|
||||
|
||||
None
|
||||
|
@ -22,8 +22,8 @@ pub fn init() -> Menu {
|
||||
#[cfg(target_os = "macos")]
|
||||
MenuItem::About(name.into(), AboutMetadata::default()).into(),
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
CustomMenuItem::new("about".to_string(), "About ChatGPT").into(),
|
||||
CustomMenuItem::new("check_update".to_string(), "Check for Updates").into(),
|
||||
CustomMenuItem::new("about", "About ChatGPT").into(),
|
||||
CustomMenuItem::new("check_update", "Check for Updates").into(),
|
||||
MenuItem::Services.into(),
|
||||
MenuItem::Hide.into(),
|
||||
MenuItem::HideOthers.into(),
|
||||
@ -33,25 +33,24 @@ pub fn init() -> Menu {
|
||||
]),
|
||||
);
|
||||
|
||||
let stay_on_top =
|
||||
CustomMenuItem::new("stay_on_top".to_string(), "Stay On Top").accelerator("CmdOrCtrl+T");
|
||||
let stay_on_top = CustomMenuItem::new("stay_on_top", "Stay On Top").accelerator("CmdOrCtrl+T");
|
||||
let stay_on_top_menu = if app_conf.stay_on_top {
|
||||
stay_on_top.selected()
|
||||
} else {
|
||||
stay_on_top
|
||||
};
|
||||
|
||||
let theme_light = CustomMenuItem::new("theme_light".to_string(), "Light");
|
||||
let theme_dark = CustomMenuItem::new("theme_dark".to_string(), "Dark");
|
||||
let theme_system = CustomMenuItem::new("theme_system".to_string(), "System");
|
||||
let theme_light = CustomMenuItem::new("theme_light", "Light");
|
||||
let theme_dark = CustomMenuItem::new("theme_dark", "Dark");
|
||||
let theme_system = CustomMenuItem::new("theme_system", "System");
|
||||
let is_dark = app_conf.clone().theme_check("dark");
|
||||
let is_system = app_conf.clone().theme_check("system");
|
||||
|
||||
let update_prompt = CustomMenuItem::new("update_prompt".to_string(), "Prompt");
|
||||
let update_silent = CustomMenuItem::new("update_silent".to_string(), "Silent");
|
||||
// let _update_disable = CustomMenuItem::new("update_disable".to_string(), "Disable");
|
||||
let update_prompt = CustomMenuItem::new("update_prompt", "Prompt");
|
||||
let update_silent = CustomMenuItem::new("update_silent", "Silent");
|
||||
// let _update_disable = CustomMenuItem::new("update_disable", "Disable");
|
||||
|
||||
let popup_search = CustomMenuItem::new("popup_search".to_string(), "Pop-up Search");
|
||||
let popup_search = CustomMenuItem::new("popup_search", "Pop-up Search");
|
||||
let popup_search_menu = if app_conf.popup_search {
|
||||
popup_search.selected()
|
||||
} else {
|
||||
@ -59,7 +58,7 @@ pub fn init() -> Menu {
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
let titlebar = CustomMenuItem::new("titlebar".to_string(), "Titlebar").accelerator("CmdOrCtrl+B");
|
||||
let titlebar = CustomMenuItem::new("titlebar", "Titlebar").accelerator("CmdOrCtrl+B");
|
||||
#[cfg(target_os = "macos")]
|
||||
let titlebar_menu = if app_conf.titlebar {
|
||||
titlebar.selected()
|
||||
@ -67,18 +66,24 @@ pub fn init() -> Menu {
|
||||
titlebar
|
||||
};
|
||||
|
||||
let system_tray = CustomMenuItem::new("system_tray".to_string(), "System Tray");
|
||||
let system_tray = CustomMenuItem::new("system_tray", "System Tray");
|
||||
let system_tray_menu = if app_conf.tray {
|
||||
system_tray.selected()
|
||||
} else {
|
||||
system_tray
|
||||
};
|
||||
let hide_dock_icon = CustomMenuItem::new("hide_dock_icon", "Hide Dock Icon");
|
||||
let hide_dock_icon_menu = if app_conf.tray {
|
||||
hide_dock_icon
|
||||
} else {
|
||||
hide_dock_icon.disabled()
|
||||
};
|
||||
|
||||
let auto_update = app_conf.get_auto_update();
|
||||
let preferences_menu = Submenu::new(
|
||||
"Preferences",
|
||||
Menu::with_items([
|
||||
CustomMenuItem::new("control_center".to_string(), "Control Center")
|
||||
CustomMenuItem::new("control_center", "Control Center")
|
||||
.accelerator("CmdOrCtrl+Shift+P")
|
||||
.into(),
|
||||
MenuItem::Separator.into(),
|
||||
@ -86,11 +91,8 @@ pub fn init() -> Menu {
|
||||
#[cfg(target_os = "macos")]
|
||||
titlebar_menu.into(),
|
||||
#[cfg(target_os = "macos")]
|
||||
CustomMenuItem::new("hide_dock_icon".to_string(), "Hide Dock Icon").into(),
|
||||
hide_dock_icon_menu.into(),
|
||||
system_tray_menu.into(),
|
||||
CustomMenuItem::new("inject_script".to_string(), "Inject Script")
|
||||
.accelerator("CmdOrCtrl+J")
|
||||
.into(),
|
||||
MenuItem::Separator.into(),
|
||||
Submenu::new(
|
||||
"Theme",
|
||||
@ -133,18 +135,20 @@ pub fn init() -> Menu {
|
||||
.into(),
|
||||
MenuItem::Separator.into(),
|
||||
popup_search_menu.into(),
|
||||
CustomMenuItem::new("sync_prompts".to_string(), "Sync Prompts").into(),
|
||||
CustomMenuItem::new("sync_prompts", "Sync Prompts").into(),
|
||||
MenuItem::Separator.into(),
|
||||
CustomMenuItem::new("go_conf".to_string(), "Go to Config")
|
||||
CustomMenuItem::new("go_conf", "Go to Config")
|
||||
.accelerator("CmdOrCtrl+Shift+G")
|
||||
.into(),
|
||||
CustomMenuItem::new("restart".to_string(), "Restart ChatGPT")
|
||||
CustomMenuItem::new("restart", "Restart ChatGPT")
|
||||
.accelerator("CmdOrCtrl+Shift+R")
|
||||
.into(),
|
||||
CustomMenuItem::new("clear_conf".to_string(), "Clear Config").into(),
|
||||
CustomMenuItem::new("clear_conf", "Clear Config").into(),
|
||||
MenuItem::Separator.into(),
|
||||
CustomMenuItem::new("nofwl".to_string(), "NoFWL Desktop Application").into(),
|
||||
CustomMenuItem::new("buy_coffee".to_string(), "Buy lencx a coffee").into(),
|
||||
CustomMenuItem::new("chatgpt_sponsors", "ChatGPT Sponsors").into(),
|
||||
MenuItem::Separator.into(),
|
||||
CustomMenuItem::new("nofwl", "NoFWL Desktop Application").into(),
|
||||
CustomMenuItem::new("sponsor", "Sponsor Author").into(),
|
||||
]),
|
||||
);
|
||||
|
||||
@ -163,38 +167,28 @@ pub fn init() -> Menu {
|
||||
let view_menu = Submenu::new(
|
||||
"View",
|
||||
Menu::new()
|
||||
.add_item(CustomMenuItem::new("go_back".to_string(), "Go Back").accelerator("CmdOrCtrl+["))
|
||||
.add_item(CustomMenuItem::new("go_back", "Go Back").accelerator("CmdOrCtrl+["))
|
||||
.add_item(CustomMenuItem::new("go_forward", "Go Forward").accelerator("CmdOrCtrl+]"))
|
||||
.add_item(
|
||||
CustomMenuItem::new("go_forward".to_string(), "Go Forward").accelerator("CmdOrCtrl+]"),
|
||||
CustomMenuItem::new("scroll_top", "Scroll to Top of Screen").accelerator("CmdOrCtrl+Up"),
|
||||
)
|
||||
.add_item(
|
||||
CustomMenuItem::new("scroll_top".to_string(), "Scroll to Top of Screen")
|
||||
.accelerator("CmdOrCtrl+Up"),
|
||||
)
|
||||
.add_item(
|
||||
CustomMenuItem::new("scroll_bottom".to_string(), "Scroll to Bottom of Screen")
|
||||
CustomMenuItem::new("scroll_bottom", "Scroll to Bottom of Screen")
|
||||
.accelerator("CmdOrCtrl+Down"),
|
||||
)
|
||||
.add_native_item(MenuItem::Separator)
|
||||
.add_item(
|
||||
CustomMenuItem::new("zoom_0".to_string(), "Zoom to Actual Size").accelerator("CmdOrCtrl+0"),
|
||||
)
|
||||
.add_item(CustomMenuItem::new("zoom_out".to_string(), "Zoom Out").accelerator("CmdOrCtrl+-"))
|
||||
.add_item(CustomMenuItem::new("zoom_in".to_string(), "Zoom In").accelerator("CmdOrCtrl+Plus"))
|
||||
.add_item(CustomMenuItem::new("zoom_0", "Zoom to Actual Size").accelerator("CmdOrCtrl+0"))
|
||||
.add_item(CustomMenuItem::new("zoom_out", "Zoom Out").accelerator("CmdOrCtrl+-"))
|
||||
.add_item(CustomMenuItem::new("zoom_in", "Zoom In").accelerator("CmdOrCtrl+Plus"))
|
||||
.add_native_item(MenuItem::Separator)
|
||||
.add_item(
|
||||
CustomMenuItem::new("reload".to_string(), "Refresh the Screen").accelerator("CmdOrCtrl+R"),
|
||||
),
|
||||
.add_item(CustomMenuItem::new("reload", "Refresh the Screen").accelerator("CmdOrCtrl+R")),
|
||||
);
|
||||
|
||||
let window_menu = Submenu::new(
|
||||
"Window",
|
||||
Menu::new()
|
||||
.add_item(CustomMenuItem::new(
|
||||
"app_website".to_string(),
|
||||
"ChatGPT User's Guide",
|
||||
))
|
||||
.add_item(CustomMenuItem::new("dalle2".to_string(), "DALL·E 2"))
|
||||
.add_item(CustomMenuItem::new("app_website", "ChatGPT User's Guide"))
|
||||
.add_item(CustomMenuItem::new("dalle2", "DALL·E 2"))
|
||||
.add_native_item(MenuItem::Separator)
|
||||
.add_native_item(MenuItem::Minimize)
|
||||
.add_native_item(MenuItem::Zoom),
|
||||
@ -203,15 +197,11 @@ pub fn init() -> Menu {
|
||||
let help_menu = Submenu::new(
|
||||
"Help",
|
||||
Menu::new()
|
||||
.add_item(CustomMenuItem::new(
|
||||
"chatgpt_log".to_string(),
|
||||
"ChatGPT Log",
|
||||
))
|
||||
.add_item(CustomMenuItem::new("update_log".to_string(), "Update Log"))
|
||||
.add_item(CustomMenuItem::new("report_bug".to_string(), "Report Bug"))
|
||||
.add_item(CustomMenuItem::new("chatgpt_log", "ChatGPT Log"))
|
||||
.add_item(CustomMenuItem::new("update_log", "Update Log"))
|
||||
.add_item(CustomMenuItem::new("report_bug", "Report Bug"))
|
||||
.add_item(
|
||||
CustomMenuItem::new("dev_tools".to_string(), "Toggle Developer Tools")
|
||||
.accelerator("CmdOrCtrl+Shift+I"),
|
||||
CustomMenuItem::new("dev_tools", "Toggle Developer Tools").accelerator("CmdOrCtrl+Shift+I"),
|
||||
),
|
||||
);
|
||||
|
||||
@ -228,7 +218,6 @@ pub fn init() -> Menu {
|
||||
pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
|
||||
let win = Some(event.window()).unwrap();
|
||||
let app = win.app_handle();
|
||||
let script_path = utils::script_path().to_string_lossy().to_string();
|
||||
let menu_id = event.menu_item_id();
|
||||
let menu_handle = win.menu_handle();
|
||||
|
||||
@ -246,9 +235,8 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
|
||||
utils::run_check_update(app, false, None);
|
||||
}
|
||||
// Preferences
|
||||
"control_center" => window::cmd::control_window(app),
|
||||
"control_center" => window::cmd::control_window(app, "control".into()),
|
||||
"restart" => tauri::api::process::restart(&app.env()),
|
||||
"inject_script" => open(&app, script_path),
|
||||
"go_conf" => utils::open_file(utils::app_root()),
|
||||
"clear_conf" => utils::clear_conf(&app),
|
||||
"app_website" => window::cmd::wa_window(
|
||||
@ -258,8 +246,15 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
|
||||
conf::APP_WEBSITE.into(),
|
||||
None,
|
||||
),
|
||||
"nofwl" => open(&app, conf::NOFWL_APP.to_string()),
|
||||
"buy_coffee" => open(&app, conf::BUY_COFFEE.to_string()),
|
||||
"nofwl" => open(&app, conf::NOFWL_APP),
|
||||
"chatgpt_sponsors" => window::cmd::wa_window(
|
||||
app,
|
||||
"chatgpt_sponsors".into(),
|
||||
"Sponsors".into(),
|
||||
conf::APP_SPONSORS.into(),
|
||||
None,
|
||||
),
|
||||
"sponsor" => window::sponsor_window(app),
|
||||
"popup_search" => {
|
||||
let app_conf = AppConf::read();
|
||||
let popup_search = !app_conf.popup_search;
|
||||
@ -394,8 +389,8 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
|
||||
.unwrap(),
|
||||
// Help
|
||||
"chatgpt_log" => utils::open_file(utils::app_root().join("chatgpt.log")),
|
||||
"update_log" => open(&app, conf::UPDATE_LOG_URL.to_string()),
|
||||
"report_bug" => open(&app, conf::ISSUES_URL.to_string()),
|
||||
"update_log" => open(&app, conf::UPDATE_LOG_URL),
|
||||
"report_bug" => open(&app, conf::ISSUES_URL),
|
||||
"dev_tools" => {
|
||||
win.open_devtools();
|
||||
win.close_devtools();
|
||||
@ -408,41 +403,29 @@ pub fn menu_handler(event: WindowMenuEvent<tauri::Wry>) {
|
||||
pub fn tray_menu() -> SystemTray {
|
||||
if cfg!(target_os = "macos") {
|
||||
let mut tray_menu = SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new(
|
||||
"control_center".to_string(),
|
||||
"Control Center",
|
||||
))
|
||||
.add_item(CustomMenuItem::new("control_center", "Control Center"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator);
|
||||
|
||||
if AppConf::read().hide_dock_icon {
|
||||
tray_menu = tray_menu.add_item(CustomMenuItem::new(
|
||||
"show_dock_icon".to_string(),
|
||||
"Show Dock Icon",
|
||||
));
|
||||
tray_menu = tray_menu.add_item(CustomMenuItem::new("show_dock_icon", "Show Dock Icon"));
|
||||
} else {
|
||||
tray_menu = tray_menu
|
||||
.add_item(CustomMenuItem::new(
|
||||
"hide_dock_icon".to_string(),
|
||||
"Hide Dock Icon",
|
||||
))
|
||||
.add_item(CustomMenuItem::new("show_core".to_string(), "Show Window"));
|
||||
.add_item(CustomMenuItem::new("hide_dock_icon", "Hide Dock Icon"))
|
||||
.add_item(CustomMenuItem::new("show_core", "Show Window"));
|
||||
}
|
||||
|
||||
SystemTray::new().with_menu(
|
||||
tray_menu
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit".to_string(), "Quit")),
|
||||
.add_item(CustomMenuItem::new("quit", "Quit")),
|
||||
)
|
||||
} else {
|
||||
SystemTray::new().with_menu(
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new(
|
||||
"control_center".to_string(),
|
||||
"Control Center",
|
||||
))
|
||||
.add_item(CustomMenuItem::new("show_core".to_string(), "Show Window"))
|
||||
.add_item(CustomMenuItem::new("control_center", "Control Center"))
|
||||
.add_item(CustomMenuItem::new("show_core", "Show Window"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit".to_string(), "Quit")),
|
||||
.add_item(CustomMenuItem::new("quit", "Quit")),
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -474,7 +457,7 @@ pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
|
||||
}
|
||||
}
|
||||
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
|
||||
"control_center" => window::cmd::control_window(app),
|
||||
"control_center" => window::cmd::control_window(app, "control".into()),
|
||||
"restart" => tauri::api::process::restart(&handle.env()),
|
||||
"show_dock_icon" => {
|
||||
AppConf::read()
|
||||
@ -508,6 +491,6 @@ pub fn tray_handler(handle: &AppHandle, event: SystemTrayEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open(app: &AppHandle, path: String) {
|
||||
pub fn open(app: &AppHandle, path: &str) {
|
||||
tauri::api::shell::open(&app.shell_scope(), path, None).unwrap();
|
||||
}
|
||||
|
@ -2,5 +2,7 @@ pub mod cmd;
|
||||
pub mod fs_extra;
|
||||
pub mod gpt;
|
||||
pub mod menu;
|
||||
pub mod script;
|
||||
pub mod setup;
|
||||
pub mod template;
|
||||
pub mod window;
|
||||
|
191
src-tauri/src/app/script.rs
Normal file
191
src-tauri/src/app/script.rs
Normal file
@ -0,0 +1,191 @@
|
||||
use crate::utils::{app_root, create_file, exists};
|
||||
use log::error;
|
||||
use log::info;
|
||||
use regex::Regex;
|
||||
use serde_json::{from_str, json, Value};
|
||||
use std::fs;
|
||||
use tauri::Manager;
|
||||
|
||||
use crate::{conf::SCRIPTS_DIR, window};
|
||||
|
||||
pub async fn init_script(app: tauri::AppHandle) -> anyhow::Result<(), reqwest::Error> {
|
||||
let body = reqwest::get(format!("{}{}", SCRIPTS_DIR, "manifest.json"))
|
||||
.await?
|
||||
.text()
|
||||
.await?;
|
||||
|
||||
if exist_scripts("manifest.json".into()) {
|
||||
let compare = compare_nested_json_objects(
|
||||
&fs::read_to_string(app_root().join("scripts").join("manifest.json")).unwrap(),
|
||||
&body,
|
||||
);
|
||||
if !compare {
|
||||
info!("update_scripts_manifest");
|
||||
create_chatgpt_scripts("manifest.json".into(), body);
|
||||
|
||||
if let Some(v) = app.get_window("core") {
|
||||
tauri::api::dialog::ask(Some(&v), "Scripts Update", "There are new available scripts. Please go to 'Preferences -> Control Center -> Scripts' to check for updates.", |is_ok| {
|
||||
if is_ok {
|
||||
info!("update_scripts_manifest_ok");
|
||||
// TODO: goto scripts page
|
||||
window::cmd::control_window(app, "scripts".into())
|
||||
} else {
|
||||
info!("update_scripts_manifest_cancel");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
create_chatgpt_scripts("manifest.json".into(), body);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn parse_script(name: String) -> Option<serde_json::Value> {
|
||||
let script_file = app_root().join("scripts").join(name);
|
||||
let code = match fs::read_to_string(&script_file) {
|
||||
Ok(content) => content,
|
||||
Err(_) => {
|
||||
error!("parse_script_error: {}", script_file.display());
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// let code = &fs::read_to_string(name).unwrap();
|
||||
let re_name = Regex::new(r"@name\s+(.*?)\n").unwrap();
|
||||
let re_version = Regex::new(r"@version\s+(.*?)\n").unwrap();
|
||||
let re_url = Regex::new(r"@url\s+(.*?)\n").unwrap();
|
||||
|
||||
let mut name = String::new();
|
||||
let mut version = String::new();
|
||||
let mut url = String::new();
|
||||
|
||||
if let Some(capture) = re_name.captures(&code) {
|
||||
name = capture.get(1).unwrap().as_str().trim().to_owned();
|
||||
}
|
||||
|
||||
if let Some(capture) = re_version.captures(&code) {
|
||||
version = capture.get(1).unwrap().as_str().trim().to_owned();
|
||||
}
|
||||
|
||||
if let Some(capture) = re_url.captures(&code) {
|
||||
url = capture.get(1).unwrap().as_str().trim().to_owned();
|
||||
}
|
||||
|
||||
let json_data = json!({
|
||||
"name": name,
|
||||
"version": version,
|
||||
"url": url,
|
||||
});
|
||||
|
||||
Some(json_data)
|
||||
}
|
||||
|
||||
pub fn exist_scripts(file: String) -> bool {
|
||||
let script_file = app_root().join("scripts").join(file);
|
||||
exists(&script_file)
|
||||
}
|
||||
|
||||
pub fn create_chatgpt_scripts(file: String, body: String) {
|
||||
let script_file = app_root().join("scripts").join(file);
|
||||
match create_file(&script_file) {
|
||||
Ok(_) => {
|
||||
info!("script_file: {:?}", script_file);
|
||||
fs::write(&script_file, body).unwrap();
|
||||
}
|
||||
Err(e) => {
|
||||
error!("create_file, {}: {}", script_file.display(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compare_nested_json_objects(json1: &str, json2: &str) -> bool {
|
||||
let value1: Value = from_str(json1).unwrap_or_else(|err| {
|
||||
error!("json_parse_1_error: {}", err);
|
||||
json!({})
|
||||
});
|
||||
let value2: Value = from_str(json2).unwrap_or_else(|err| {
|
||||
error!("json_parse_2_error: {}", err);
|
||||
json!({})
|
||||
});
|
||||
|
||||
compare_json_objects(&value1, &value2)
|
||||
}
|
||||
|
||||
pub fn compare_json_objects(obj1: &Value, obj2: &Value) -> bool {
|
||||
match (obj1, obj2) {
|
||||
(Value::Object(obj1), Value::Object(obj2)) => {
|
||||
if obj1.len() != obj2.len() {
|
||||
return false;
|
||||
}
|
||||
for (key, value) in obj1 {
|
||||
if !obj2.contains_key(key) || !compare_json_objects(value, obj2.get(key).unwrap()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
(Value::Array(arr1), Value::Array(arr2)) => {
|
||||
if arr1.len() != arr2.len() {
|
||||
return false;
|
||||
}
|
||||
for (value1, value2) in arr1.iter().zip(arr2.iter()) {
|
||||
if !compare_json_objects(value1, value2) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => obj1 == obj2,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod cmd {
|
||||
use super::{create_chatgpt_scripts, parse_script};
|
||||
use crate::conf::SCRIPTS_DIR;
|
||||
use log::{error, info};
|
||||
use tauri::Manager;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_script_info(name: String) -> Option<serde_json::Value> {
|
||||
parse_script(name)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn sync_scripts(app: tauri::AppHandle, name: String) -> bool {
|
||||
let res = reqwest::get(format!("{}{}", SCRIPTS_DIR, name)).await;
|
||||
|
||||
info!("sync_scripts: {}", name);
|
||||
let body = match res {
|
||||
Ok(response) => match response.text().await {
|
||||
Ok(text) => text,
|
||||
Err(err) => {
|
||||
error!("sync_scripts_result_error: {}", err);
|
||||
if let Some(v) = app.get_window("core") {
|
||||
tauri::api::dialog::message(
|
||||
Some(&v),
|
||||
"Sync Scripts Error",
|
||||
format!("sync_scripts_result_error: {}", err),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
error!("sync_scripts_response_error: {}", err);
|
||||
if let Some(v) = app.get_window("core") {
|
||||
tauri::api::dialog::message(
|
||||
Some(&v),
|
||||
"Sync Scripts Error",
|
||||
format!("sync_scripts_response_error: {}", err),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
create_chatgpt_scripts(name, body);
|
||||
|
||||
true
|
||||
}
|
||||
}
|
@ -1,18 +1,34 @@
|
||||
use crate::{app::window, conf::AppConf, utils};
|
||||
use crate::{
|
||||
app,
|
||||
conf::AppConf,
|
||||
utils::{self, load_script},
|
||||
};
|
||||
use log::{error, info};
|
||||
use tauri::{utils::config::WindowUrl, window::WindowBuilder, App, GlobalShortcutManager, Manager};
|
||||
use wry::application::accelerator::Accelerator;
|
||||
|
||||
pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
pub fn init(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
info!("stepup");
|
||||
|
||||
let app_conf = AppConf::read();
|
||||
let url = app_conf.main_origin.to_string();
|
||||
let theme = AppConf::theme_mode();
|
||||
let handle = app.app_handle();
|
||||
|
||||
app::template::Template::new(utils::app_root().join("scripts"));
|
||||
|
||||
let handle = app.app_handle();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
app::script::init_script(handle)
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
error!("script_init_error: {}", err);
|
||||
});
|
||||
});
|
||||
|
||||
let handle = app.app_handle();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
info!("stepup_tray");
|
||||
window::tray_window(&handle);
|
||||
app::window::tray_window(&handle);
|
||||
});
|
||||
|
||||
if let Some(v) = app_conf.clone().global_shortcut {
|
||||
@ -52,13 +68,8 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
|
||||
} else {
|
||||
let app = app.handle();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let link = if app_conf2.main_dashboard {
|
||||
"index.html"
|
||||
} else {
|
||||
&url
|
||||
};
|
||||
info!("main_window: {}", link);
|
||||
let mut main_win = WindowBuilder::new(&app, "core", WindowUrl::App(link.into()))
|
||||
let url2 = &url;
|
||||
let mut main_win = WindowBuilder::new(&app, "core", WindowUrl::App(url2.into()))
|
||||
.title("ChatGPT")
|
||||
.resizable(true)
|
||||
.fullscreen(false)
|
||||
@ -66,7 +77,7 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
|
||||
.theme(Some(theme))
|
||||
.always_on_top(app_conf2.stay_on_top)
|
||||
.initialization_script(&utils::user_script())
|
||||
.initialization_script(include_str!("../scripts/core.js"))
|
||||
.initialization_script(&load_script("core.js"))
|
||||
.user_agent(&app_conf2.ua_window);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
@ -76,7 +87,7 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
|
||||
.hidden_title(true);
|
||||
}
|
||||
|
||||
if url == "https://chat.openai.com" && !app_conf2.main_dashboard {
|
||||
if url == "https://chat.openai.com" {
|
||||
main_win = main_win
|
||||
.initialization_script(include_str!("../vendors/floating-ui-core.js"))
|
||||
.initialization_script(include_str!("../vendors/floating-ui-dom.js"))
|
||||
@ -84,11 +95,11 @@ pub fn init(app: &mut App) -> std::result::Result<(), Box<dyn std::error::Error>
|
||||
.initialization_script(include_str!("../vendors/jspdf.js"))
|
||||
.initialization_script(include_str!("../vendors/turndown.js"))
|
||||
.initialization_script(include_str!("../vendors/turndown-plugin-gfm.js"))
|
||||
.initialization_script(include_str!("../scripts/popup.core.js"))
|
||||
.initialization_script(include_str!("../scripts/export.js"))
|
||||
.initialization_script(include_str!("../scripts/markdown.export.js"))
|
||||
.initialization_script(include_str!("../scripts/cmd.js"))
|
||||
.initialization_script(include_str!("../scripts/chat.js"))
|
||||
.initialization_script(&load_script("popup.core.js"))
|
||||
.initialization_script(&load_script("export.js"))
|
||||
.initialization_script(&load_script("markdown.export.js"))
|
||||
.initialization_script(&load_script("cmd.js"))
|
||||
.initialization_script(&load_script("chat.js"))
|
||||
}
|
||||
|
||||
main_win.build().unwrap();
|
||||
|
110
src-tauri/src/app/template.rs
Normal file
110
src-tauri/src/app/template.rs
Normal file
@ -0,0 +1,110 @@
|
||||
use anyhow::Result;
|
||||
use log::{error, info};
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::Write,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
pub static SCRIPT_MAIN: &[u8] = include_bytes!("../../../scripts/main.js");
|
||||
pub static SCRIPT_CORE: &[u8] = include_bytes!("../../../scripts/core.js");
|
||||
pub static SCRIPT_CHAT: &[u8] = include_bytes!("../../../scripts/chat.js");
|
||||
pub static SCRIPT_CMD: &[u8] = include_bytes!("../../../scripts/cmd.js");
|
||||
pub static SCRIPT_DALLE2: &[u8] = include_bytes!("../../../scripts/dalle2.js");
|
||||
pub static SCRIPT_EXPORT: &[u8] = include_bytes!("../../../scripts/export.js");
|
||||
pub static SCRIPT_MD_EXPORT: &[u8] = include_bytes!("../../../scripts/markdown.export.js");
|
||||
pub static SCRIPT_POPUP_CORE: &[u8] = include_bytes!("../../../scripts/popup.core.js");
|
||||
pub static SCRIPT_MANIFEST: &[u8] = include_bytes!("../../../scripts/manifest.json");
|
||||
pub static SCRIPT_README: &[u8] = include_bytes!("../../../scripts/README.md");
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Template {
|
||||
pub main: Vec<u8>,
|
||||
pub core: Vec<u8>,
|
||||
pub chat: Vec<u8>,
|
||||
pub cmd: Vec<u8>,
|
||||
pub dalle2: Vec<u8>,
|
||||
pub export: Vec<u8>,
|
||||
pub markdown_export: Vec<u8>,
|
||||
pub popup_core: Vec<u8>,
|
||||
pub manifest: Vec<u8>,
|
||||
pub readme: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Template {
|
||||
pub fn new<P: AsRef<Path>>(template_dir: P) -> Self {
|
||||
let template_dir = template_dir.as_ref();
|
||||
let mut template = Template::default();
|
||||
|
||||
{
|
||||
let files = vec![
|
||||
(template_dir.join("main.js"), &mut template.main),
|
||||
(template_dir.join("core.js"), &mut template.core),
|
||||
(template_dir.join("chat.js"), &mut template.chat),
|
||||
(template_dir.join("cmd.js"), &mut template.cmd),
|
||||
(template_dir.join("dalle2.js"), &mut template.dalle2),
|
||||
(template_dir.join("export.js"), &mut template.export),
|
||||
(
|
||||
template_dir.join("markdown.export.js"),
|
||||
&mut template.markdown_export,
|
||||
),
|
||||
(template_dir.join("popup.core.js"), &mut template.popup_core),
|
||||
(template_dir.join("README.md"), &mut template.readme),
|
||||
(template_dir.join("manifest.json"), &mut template.manifest),
|
||||
];
|
||||
|
||||
for (filename, dest) in files {
|
||||
if !filename.exists() {
|
||||
match create_dir(&filename) {
|
||||
Ok(_) => {
|
||||
if let Err(e) = write_file_contents(&filename, dest) {
|
||||
error!("write_script, {}: {}", filename.display(), e);
|
||||
} else {
|
||||
info!("write_script: {}", filename.display());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("create_file, {}: {}", filename.display(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Template {
|
||||
fn default() -> Template {
|
||||
Template {
|
||||
main: Vec::from(SCRIPT_MAIN),
|
||||
core: Vec::from(SCRIPT_CORE),
|
||||
chat: Vec::from(SCRIPT_CHAT),
|
||||
cmd: Vec::from(SCRIPT_CMD),
|
||||
dalle2: Vec::from(SCRIPT_DALLE2),
|
||||
export: Vec::from(SCRIPT_EXPORT),
|
||||
markdown_export: Vec::from(SCRIPT_MD_EXPORT),
|
||||
popup_core: Vec::from(SCRIPT_POPUP_CORE),
|
||||
manifest: Vec::from(SCRIPT_MANIFEST),
|
||||
readme: Vec::from(SCRIPT_README),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_dir<P: AsRef<Path>>(filename: P) -> Result<()> {
|
||||
let filename = filename.as_ref();
|
||||
if let Some(parent) = filename.parent() {
|
||||
if !parent.exists() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_file_contents<P: AsRef<Path>>(filename: P, data: &[u8]) -> Result<()> {
|
||||
let filename = filename.as_ref();
|
||||
let mut file = File::create(filename)?;
|
||||
file.write_all(data)?;
|
||||
Ok(())
|
||||
}
|
@ -1,4 +1,7 @@
|
||||
use crate::{conf::AppConf, utils};
|
||||
use crate::{
|
||||
conf::AppConf,
|
||||
utils::{self, load_script},
|
||||
};
|
||||
use log::info;
|
||||
use std::time::SystemTime;
|
||||
use tauri::{utils::config::WindowUrl, window::WindowBuilder, Manager};
|
||||
@ -23,16 +26,16 @@ pub fn tray_window(handle: &tauri::AppHandle) {
|
||||
.always_on_top(true)
|
||||
.theme(Some(theme))
|
||||
.initialization_script(&utils::user_script())
|
||||
.initialization_script(include_str!("../scripts/core.js"))
|
||||
.initialization_script(&load_script("core.js"))
|
||||
.user_agent(&app_conf.ua_tray);
|
||||
|
||||
if app_conf.tray_origin == "https://chat.openai.com" && !app_conf.tray_dashboard {
|
||||
tray_win = tray_win
|
||||
.initialization_script(include_str!("../vendors/floating-ui-core.js"))
|
||||
.initialization_script(include_str!("../vendors/floating-ui-dom.js"))
|
||||
.initialization_script(include_str!("../scripts/cmd.js"))
|
||||
.initialization_script(include_str!("../scripts/chat.js"))
|
||||
.initialization_script(include_str!("../scripts/popup.core.js"))
|
||||
.initialization_script(&load_script("cmd.js"))
|
||||
.initialization_script(&load_script("chat.js"))
|
||||
.initialization_script(&load_script("popup.core.js"))
|
||||
}
|
||||
|
||||
tray_win.build().unwrap().hide().unwrap();
|
||||
@ -78,9 +81,9 @@ pub fn dalle2_window(
|
||||
.inner_size(800.0, 600.0)
|
||||
.always_on_top(false)
|
||||
.theme(Some(theme))
|
||||
.initialization_script(include_str!("../scripts/core.js"))
|
||||
.initialization_script(&load_script("core.js"))
|
||||
.initialization_script(&load_script("dalle2.js"))
|
||||
.initialization_script(&query)
|
||||
.initialization_script(include_str!("../scripts/dalle2.js"))
|
||||
.build()
|
||||
.unwrap();
|
||||
});
|
||||
@ -91,6 +94,23 @@ pub fn dalle2_window(
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sponsor_window(handle: tauri::AppHandle) {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Some(win) = handle.get_window("sponsor") {
|
||||
win.show().unwrap()
|
||||
} else {
|
||||
WindowBuilder::new(&handle, "sponsor", WindowUrl::App("sponsor.html".into()))
|
||||
.title("Sponsor")
|
||||
.resizable(true)
|
||||
.fullscreen(false)
|
||||
.inner_size(600.0, 600.0)
|
||||
.min_inner_size(600.0, 600.0)
|
||||
.build()
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub mod cmd {
|
||||
use super::*;
|
||||
use log::info;
|
||||
@ -107,13 +127,13 @@ pub mod cmd {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn control_window(handle: tauri::AppHandle) {
|
||||
pub fn control_window(handle: tauri::AppHandle, win_type: String) {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if handle.get_window("main").is_none() {
|
||||
WindowBuilder::new(
|
||||
&handle,
|
||||
"main",
|
||||
WindowUrl::App("index.html?type=control".into()),
|
||||
WindowUrl::App(format!("index.html?type={}", win_type).into()),
|
||||
)
|
||||
.title("Control Center")
|
||||
.resizable(true)
|
||||
@ -144,7 +164,7 @@ pub mod cmd {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tauri::WindowBuilder::new(&app, label, tauri::WindowUrl::App(url.parse().unwrap()))
|
||||
.initialization_script(&script.unwrap_or_default())
|
||||
.initialization_script(include_str!("../scripts/core.js"))
|
||||
.initialization_script(&load_script("core.js"))
|
||||
.title(title)
|
||||
.inner_size(960.0, 700.0)
|
||||
.resizable(true)
|
||||
|
@ -9,12 +9,14 @@ use tauri::TitleBarStyle;
|
||||
use crate::utils::{app_root, create_file, exists};
|
||||
|
||||
pub const APP_WEBSITE: &str = "https://lencx.github.io/app/";
|
||||
pub const APP_SPONSORS: &str = "https://lencx.github.io/app/sponsors";
|
||||
pub const ISSUES_URL: &str = "https://github.com/lencx/ChatGPT/issues";
|
||||
pub const NOFWL_APP: &str = "https://github.com/lencx/nofwl";
|
||||
pub const UPDATE_LOG_URL: &str = "https://github.com/lencx/ChatGPT/blob/main/UPDATE_LOG.md";
|
||||
pub const BUY_COFFEE: &str = "https://www.buymeacoffee.com/lencx";
|
||||
// pub const BUY_COFFEE: &str = "https://www.buymeacoffee.com/lencx";
|
||||
pub const GITHUB_PROMPTS_CSV_URL: &str =
|
||||
"https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv";
|
||||
pub const SCRIPTS_DIR: &str = "https://raw.githubusercontent.com/lencx/ChatGPT/main/scripts/";
|
||||
|
||||
pub const APP_CONF_PATH: &str = "chat.conf.json";
|
||||
pub const CHATGPT_URL: &str = "https://chat.openai.com";
|
||||
@ -67,7 +69,7 @@ impl AppConf {
|
||||
Self {
|
||||
titlebar: !cfg!(target_os = "macos"),
|
||||
hide_dock_icon: false,
|
||||
save_window_state: false,
|
||||
save_window_state: true,
|
||||
theme: "light".into(),
|
||||
auto_update: "prompt".into(),
|
||||
#[cfg(target_os = "macos")]
|
||||
|
@ -7,7 +7,7 @@ mod app;
|
||||
mod conf;
|
||||
mod utils;
|
||||
|
||||
use app::{cmd, fs_extra, gpt, menu, setup, window};
|
||||
use app::{cmd, fs_extra, gpt, menu, script, setup, window};
|
||||
use conf::AppConf;
|
||||
use tauri_plugin_autostart::MacosLauncher;
|
||||
use tauri_plugin_log::{
|
||||
@ -55,13 +55,14 @@ async fn main() {
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
cmd::drag_window,
|
||||
cmd::fullscreen,
|
||||
cmd::download,
|
||||
cmd::save_file,
|
||||
cmd::open_link,
|
||||
cmd::run_check_update,
|
||||
cmd::open_file,
|
||||
cmd::download_file,
|
||||
cmd::get_data,
|
||||
gpt::get_chat_model_cmd,
|
||||
cmd::fetch_image,
|
||||
gpt::get_chat_prompt_cmd,
|
||||
gpt::parse_prompt,
|
||||
gpt::sync_prompts,
|
||||
gpt::sync_user_prompts,
|
||||
@ -75,6 +76,8 @@ async fn main() {
|
||||
conf::cmd::form_confirm,
|
||||
conf::cmd::form_cancel,
|
||||
conf::cmd::form_msg,
|
||||
script::cmd::sync_scripts,
|
||||
script::cmd::get_script_info,
|
||||
window::cmd::wa_window,
|
||||
window::cmd::control_window,
|
||||
window::cmd::window_reload,
|
||||
|
124
src-tauri/src/scripts/chat.js
vendored
124
src-tauri/src/scripts/chat.js
vendored
@ -1,124 +0,0 @@
|
||||
async function init() {
|
||||
new MutationObserver(function (mutationsList) {
|
||||
for (const mutation of mutationsList) {
|
||||
if (mutation.target.closest("form")) {
|
||||
chatBtns();
|
||||
}
|
||||
}
|
||||
}).observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
document.addEventListener('visibilitychange', () =>
|
||||
document.getElementsByTagName('textarea')[0]?.focus()
|
||||
);
|
||||
}
|
||||
|
||||
async function chatBtns() {
|
||||
const chatConf = await invoke('get_app_conf') || {};
|
||||
const synth = window.speechSynthesis;
|
||||
let currentUtterance = null;
|
||||
let currentIndex = -1;
|
||||
const list = Array.from(document.querySelectorAll("main >div>div>div>div>div"));
|
||||
list.forEach((i, idx) => {
|
||||
if (i.querySelector('.chat-item-copy')) return;
|
||||
if (!i.querySelector('button.rounded-md')) return;
|
||||
if (!i.querySelector('.self-end')) return;
|
||||
const cpbtn = i.querySelector('button.rounded-md').cloneNode(true);
|
||||
cpbtn.classList.add('chat-item-copy');
|
||||
cpbtn.title = 'Copy to clipboard';
|
||||
cpbtn.innerHTML = setIcon('copy');
|
||||
i.querySelector('.self-end').appendChild(cpbtn);
|
||||
cpbtn.onclick = () => {
|
||||
copyToClipboard(i?.innerText?.trim() || '', cpbtn);
|
||||
}
|
||||
|
||||
const saybtn = i.querySelector('button.rounded-md').cloneNode(true);
|
||||
saybtn.classList.add('chat-item-voice');
|
||||
saybtn.title = 'Say';
|
||||
saybtn.innerHTML = setIcon('voice');
|
||||
i.querySelector('.self-end').appendChild(saybtn);
|
||||
saybtn.onclick = () => {
|
||||
if (currentUtterance && currentIndex !== -1) {
|
||||
synth.cancel();
|
||||
if (idx === currentIndex) {
|
||||
saybtn.innerHTML = setIcon('voice');
|
||||
currentUtterance = null;
|
||||
currentIndex = -1;
|
||||
return;
|
||||
} else if (list[currentIndex].querySelector('.chat-item-voice')) {
|
||||
list[currentIndex].querySelector('.chat-item-voice').innerHTML = setIcon('voice');
|
||||
list[idx].querySelector('.chat-item-voice').innerHTML = setIcon('speaking');
|
||||
}
|
||||
}
|
||||
const txt = i?.innerText?.trim() || '';
|
||||
if (!txt) return;
|
||||
const utterance = new SpeechSynthesisUtterance(txt);
|
||||
const voices = speechSynthesis.getVoices();
|
||||
let voice = voices.find(voice => voice.voiceURI === chatConf.speech_lang);
|
||||
if (!voice) {
|
||||
voice = voices.find(voice => voice.lang === 'en-US');
|
||||
}
|
||||
utterance.voice = voice;
|
||||
currentIndex = idx;
|
||||
utterance.lang = voice.lang;
|
||||
// utterance.rate = 0.7;
|
||||
// utterance.pitch = 1.1;
|
||||
// utterance.volume = 1;
|
||||
synth.speak(utterance);
|
||||
amISpeaking = synth.speaking;
|
||||
saybtn.innerHTML = setIcon('speaking');
|
||||
currentUtterance = utterance;
|
||||
currentIndex = idx;
|
||||
utterance.onend = () => {
|
||||
saybtn.innerHTML = setIcon('voice');
|
||||
currentUtterance = null;
|
||||
currentIndex = -1;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function copyToClipboard(text, btn) {
|
||||
window.clearTimeout(window.__cpTimeout);
|
||||
btn.innerHTML = setIcon('cpok');
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
var textarea = document.createElement('textarea');
|
||||
document.body.appendChild(textarea);
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.clip = 'rect(0 0 0 0)';
|
||||
textarea.style.top = '10px';
|
||||
textarea.value = text;
|
||||
textarea.select();
|
||||
document.execCommand('copy', true);
|
||||
document.body.removeChild(textarea);
|
||||
}
|
||||
window.__cpTimeout = setTimeout(() => {
|
||||
btn.innerHTML = setIcon('copy');
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function focusOnInput() {
|
||||
// This currently works because there is only a single `<textarea>` element on the ChatGPT UI page.
|
||||
document.getElementsByTagName("textarea")[0].focus();
|
||||
}
|
||||
|
||||
function setIcon(type) {
|
||||
return {
|
||||
copy: `<svg class="chatappico copy" stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg>`,
|
||||
cpok: `<svg class="chatappico cpok" viewBox="0 0 24 24"><g fill="none" stroke="#10a37f" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2M16 4h2a2 2 0 0 1 2 2v4m1 4H11"/><path d="m15 10l-4 4l4 4"/></g></svg>`,
|
||||
voice: `<svg class="chatappico voice" viewBox="0 0 1024 1024"><path d="M542.923802 202.113207c-5.110391 0-10.717086 1.186012-16.572444 3.739161L360.043634 312.714188l-83.057671 0c-46.109154 0-83.433224 36.917818-83.433224 83.121116l0 166.646438c0 45.952588 36.950564 83.153862 83.433224 83.153862l83.057671 0 166.307723 106.829074c23.550369 10.218736 41.745776-0.717338 41.745776-23.898293L568.097134 229.687216C568.096111 212.426087 557.753555 202.113207 542.923802 202.113207z" fill="currentColor"></path><path d="M794.154683 314.39548c-16.758686-28.537963-33.771151-48.258097-45.610804-58.882062-3.986801-3.489474-8.972349-5.233188-13.833053-5.233188-5.79396 0-11.464099 2.337231-15.57779 6.91448-7.662517 8.631588-6.976902 21.808702 1.620917 29.410843 1.994424 1.744737 5.856381 5.700839 11.154038 11.777231 9.033747 10.437723 18.006096 22.774703 26.419719 37.072337 24.235984 41.033555 38.755676 89.011266 38.755676 143.688563 0 54.705949-14.519692 102.651938-38.755676 143.810337-8.414647 14.20656-17.448394 26.668383-26.484188 37.07336-5.234211 6.076392-9.096169 10.033517-11.149944 11.778254-8.538467 7.603165-9.224082 20.717857-1.683339 29.40982 7.599072 8.473999 20.807908 9.222035 29.40982 1.650593 11.900028-10.562567 28.910447-30.252001 45.732577-58.850339 27.79095-47.078225 44.490284-102.3122 44.490284-164.872025C838.708412 416.646282 821.946656 361.470635 794.154683 314.39548z" fill="currentColor"></path><path d="M690.846806 377.360534c-8.723685-17.790178-17.698081-30.2827-24.301476-37.260625-4.111644-4.3951-9.595542-6.544043-15.139815-6.544043-5.110391 0-10.159384 1.774413-14.270005 5.54632-8.350179 7.881504-8.847505 20.99722-0.997724 29.471219 3.927449 4.112668 10.468422 13.304004 17.448394 27.199479 11.587919 23.77038 18.567891 51.559283 18.567891 83.370803 0 31.80845-6.978948 59.72322-18.567891 83.400478-6.978948 13.892405-13.520945 23.052019-17.448394 27.259854-7.850805 8.410554-7.353478 21.559015 0.997724 29.440519 8.473999 7.882528 21.559015 7.353478 29.474288-1.025353 6.53995-7.011694 15.513322-19.440771 24.238031-37.356816 14.393825-29.189809 22.992667-63.243393 22.992667-101.781104C713.839473 440.603927 705.241654 406.583089 690.846806 377.360534z" fill="currentColor"></path></svg>`,
|
||||
speaking: `<svg class="chatappico voice" viewBox="0 0 1024 1024"><path d="M542.923802 202.113207c-5.110391 0-10.717086 1.186012-16.572444 3.739161L360.043634 312.714188l-83.057671 0c-46.109154 0-83.433224 36.917818-83.433224 83.121116l0 166.646438c0 45.952588 36.950564 83.153862 83.433224 83.153862l83.057671 0 166.307723 106.829074c23.550369 10.218736 41.745776-0.717338 41.745776-23.898293L568.097134 229.687216C568.096111 212.426087 557.753555 202.113207 542.923802 202.113207z" fill="#10a37f"></path><path d="M794.154683 314.39548c-16.758686-28.537963-33.771151-48.258097-45.610804-58.882062-3.986801-3.489474-8.972349-5.233188-13.833053-5.233188-5.79396 0-11.464099 2.337231-15.57779 6.91448-7.662517 8.631588-6.976902 21.808702 1.620917 29.410843 1.994424 1.744737 5.856381 5.700839 11.154038 11.777231 9.033747 10.437723 18.006096 22.774703 26.419719 37.072337 24.235984 41.033555 38.755676 89.011266 38.755676 143.688563 0 54.705949-14.519692 102.651938-38.755676 143.810337-8.414647 14.20656-17.448394 26.668383-26.484188 37.07336-5.234211 6.076392-9.096169 10.033517-11.149944 11.778254-8.538467 7.603165-9.224082 20.717857-1.683339 29.40982 7.599072 8.473999 20.807908 9.222035 29.40982 1.650593 11.900028-10.562567 28.910447-30.252001 45.732577-58.850339 27.79095-47.078225 44.490284-102.3122 44.490284-164.872025C838.708412 416.646282 821.946656 361.470635 794.154683 314.39548z" fill="#10a37f"></path><path d="M690.846806 377.360534c-8.723685-17.790178-17.698081-30.2827-24.301476-37.260625-4.111644-4.3951-9.595542-6.544043-15.139815-6.544043-5.110391 0-10.159384 1.774413-14.270005 5.54632-8.350179 7.881504-8.847505 20.99722-0.997724 29.471219 3.927449 4.112668 10.468422 13.304004 17.448394 27.199479 11.587919 23.77038 18.567891 51.559283 18.567891 83.370803 0 31.80845-6.978948 59.72322-18.567891 83.400478-6.978948 13.892405-13.520945 23.052019-17.448394 27.259854-7.850805 8.410554-7.353478 21.559015 0.997724 29.440519 8.473999 7.882528 21.559015 7.353478 29.474288-1.025353 6.53995-7.011694 15.513322-19.440771 24.238031-37.356816 14.393825-29.189809 22.992667-63.243393 22.992667-101.781104C713.839473 440.603927 705.241654 406.583089 690.846806 377.360534z" fill="#10a37f"></path></svg>`,
|
||||
}[type];
|
||||
}
|
||||
|
||||
if (
|
||||
document.readyState === "complete" ||
|
||||
document.readyState === "interactive"
|
||||
) {
|
||||
init();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
}
|
320
src-tauri/src/scripts/cmd.js
vendored
320
src-tauri/src/scripts/cmd.js
vendored
@ -1,320 +0,0 @@
|
||||
// *** Core Script - CMD ***
|
||||
|
||||
function init() {
|
||||
const styleDom = document.createElement('style');
|
||||
styleDom.innerHTML = `form {
|
||||
position: relative;
|
||||
}
|
||||
.chat-model-cmd-list {
|
||||
position: absolute;
|
||||
bottom: 60px;
|
||||
max-height: 100px;
|
||||
overflow: auto;
|
||||
z-index: 9999;
|
||||
}
|
||||
.chat-model-cmd-list>div {
|
||||
border: solid 2px rgba(80,80,80,.3);
|
||||
border-radius: 5px;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
html.dark .chat-model-cmd-list>div {
|
||||
background-color: #4a4a4a;
|
||||
}
|
||||
html.dark .chat-model-cmd-list .cmd-item {
|
||||
border-color: #666;
|
||||
}
|
||||
html.dark .chat-model-cmd-list .cmd-item b {
|
||||
color: #e8e8e8;
|
||||
}
|
||||
html.dark .chat-model-cmd-list .cmd-item i {
|
||||
color: #999;
|
||||
}
|
||||
html.dark .chat-model-cmd-list .cmd-item.selected {
|
||||
background: rgba(59,130,246,.5);
|
||||
}
|
||||
|
||||
.chat-model-cmd-list .cmd-item {
|
||||
font-size: 12px;
|
||||
border-bottom: solid 1px rgba(80,80,80,.2);
|
||||
padding: 2px 4px;
|
||||
display: flex;
|
||||
user-select: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-model-cmd-list .cmd-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.chat-model-cmd-list .cmd-item.selected {
|
||||
background: rgba(59,130,246,.3);
|
||||
}
|
||||
.chat-model-cmd-list .cmd-item b {
|
||||
display: inline-block;
|
||||
width: 100px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
border-radius: 4px;
|
||||
margin-right: 10px;
|
||||
color: #2a2a2a;
|
||||
}
|
||||
.chat-model-cmd-list .cmd-item i {
|
||||
width: 100%;
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
color: #888;
|
||||
}
|
||||
.chatappico {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
.chatappico.pdf, .chatappico.md {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
.chatappico.copy {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
.chatappico.cpok {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
.chatappico.refresh {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
#download-markdown-button,
|
||||
#download-png-button,
|
||||
#download-pdf-button,
|
||||
#refresh-page-button {
|
||||
border: none;
|
||||
}
|
||||
@media screen and (max-width: 767px) {
|
||||
#download-png-button, #download-pdf-button, #download-html-button {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
`;
|
||||
document.head.append(styleDom);
|
||||
|
||||
if (window.formInterval) {
|
||||
clearInterval(window.formInterval);
|
||||
}
|
||||
window.formInterval = setInterval(() => {
|
||||
const form = document.querySelector("form textarea");
|
||||
if (!form) return;
|
||||
clearInterval(window.formInterval);
|
||||
cmdTip();
|
||||
new MutationObserver(function (mutationsList) {
|
||||
for (const mutation of mutationsList) {
|
||||
if (mutation.target.getAttribute('id') === '__next') {
|
||||
initDom();
|
||||
cmdTip();
|
||||
}
|
||||
if (mutation.target.getAttribute('class') === 'chat-model-cmd-list') {
|
||||
// The `chatgpt prompt` fill can be done by clicking on the event.
|
||||
const searchDom = document.querySelector("form .chat-model-cmd-list>div");
|
||||
const searchInput = document.querySelector('form textarea');
|
||||
if (!searchDom) return;
|
||||
searchDom.addEventListener('click', (event) => {
|
||||
const item = event.target.closest("div");
|
||||
if (item) {
|
||||
const val = decodeURIComponent(item.getAttribute('data-prompt'));
|
||||
searchInput.value = val;
|
||||
document.querySelector('form textarea').focus();
|
||||
initDom();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}).observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
}, 300);
|
||||
}
|
||||
|
||||
async function cmdTip() {
|
||||
initDom();
|
||||
const chatModelJson = await invoke('get_chat_model_cmd') || {};
|
||||
const data = chatModelJson.data;
|
||||
if (data.length <= 0) return;
|
||||
|
||||
let modelDom = document.querySelector('.chat-model-cmd-list');
|
||||
if (!modelDom) {
|
||||
const dom = document.createElement('div');
|
||||
dom.classList.add('chat-model-cmd-list');
|
||||
document.querySelector('form').appendChild(dom);
|
||||
modelDom = document.querySelector('.chat-model-cmd-list');
|
||||
|
||||
// fix: tray window
|
||||
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
modelDom.style.bottom = '54px';
|
||||
}
|
||||
|
||||
const itemDom = (v) => `<div class="cmd-item" title="${v.prompt}" data-cmd="${v.cmd}" data-prompt="${encodeURIComponent(v.prompt)}"><b title="${v.cmd}">/${v.cmd}</b><i>${v.act}</i></div>`;
|
||||
const renderList = (v) => {
|
||||
initDom();
|
||||
modelDom.innerHTML = `<div>${v.map(itemDom).join('')}</div>`;
|
||||
window.__CHAT_MODEL_CMD_PROMPT__ = v[0]?.prompt.trim();
|
||||
window.__CHAT_MODEL_CMD__ = v[0]?.cmd.trim();
|
||||
window.__cmd_list = modelDom.querySelectorAll('.cmd-item');
|
||||
window.__cmd_index = 0;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
};
|
||||
const setPrompt = (v = '') => {
|
||||
if (v.trim()) {
|
||||
window.__CHAT_MODEL_CMD_PROMPT__ = window.__CHAT_MODEL_CMD_PROMPT__?.replace(/\{([^{}]*)\}/, `{${v.trim()}}`);
|
||||
}
|
||||
}
|
||||
const searchInput = document.querySelector('form textarea');
|
||||
|
||||
// Enter a command starting with `/` and press a space to automatically fill `chatgpt prompt`.
|
||||
// If more than one command appears in the search results, the first one will be used by default.
|
||||
function cmdKeydown(event) {
|
||||
if (!window.__CHAT_MODEL_CMD_PROMPT__) {
|
||||
if (!event.shiftKey && event.keyCode === 13 && __TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
const btn = document.querySelector('form button');
|
||||
if (btn) btn.click();
|
||||
event.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ------------------ Keyboard scrolling (ArrowUp | ArrowDown) --------------------------
|
||||
if (event.keyCode === 38 && window.__cmd_index > 0) { // ArrowUp
|
||||
window.__cmd_list[window.__cmd_index].classList.remove('selected');
|
||||
window.__cmd_index = window.__cmd_index - 1;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
window.__CHAT_MODEL_CMD_PROMPT__ = decodeURIComponent(window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'));
|
||||
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (event.keyCode === 40 && window.__cmd_index < window.__cmd_list.length - 1) { // ArrowDown
|
||||
window.__cmd_list[window.__cmd_index].classList.remove('selected');
|
||||
window.__cmd_index = window.__cmd_index + 1;
|
||||
window.__cmd_list[window.__cmd_index].classList.add('selected');
|
||||
window.__CHAT_MODEL_CMD_PROMPT__ = decodeURIComponent(window.__cmd_list[window.__cmd_index].getAttribute('data-prompt'));
|
||||
searchInput.value = `/${window.__cmd_list[window.__cmd_index].getAttribute('data-cmd')}`;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
const containerHeight = modelDom.offsetHeight;
|
||||
const itemHeight = window.__cmd_list[0].offsetHeight + 1;
|
||||
|
||||
const itemTop = window.__cmd_list[window.__cmd_index].offsetTop;
|
||||
const itemBottom = itemTop + itemHeight;
|
||||
if (itemTop < modelDom.scrollTop || itemBottom > modelDom.scrollTop + containerHeight) {
|
||||
modelDom.scrollTop = itemTop;
|
||||
}
|
||||
|
||||
// ------------------ TAB key replaces `{q}` tag content -------------------------------
|
||||
// feat: https://github.com/lencx/ChatGPT/issues/54
|
||||
if (event.keyCode === 9 && !window.__CHAT_MODEL_STATUS__) {
|
||||
const strGroup = window.__CHAT_MODEL_CMD_PROMPT__.match(/\{([^{}]*)\}/) || [];
|
||||
|
||||
if (strGroup[1]) {
|
||||
searchInput.value = `/${window.__CHAT_MODEL_CMD__}` + ` {${strGroup[1]}}` + ' |-> ';
|
||||
window.__CHAT_MODEL_STATUS__ = 1;
|
||||
} else {
|
||||
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
initDom();
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (window.__CHAT_MODEL_STATUS__ === 1 && event.keyCode === 9) { // TAB
|
||||
const data = searchInput.value.split('|->');
|
||||
if (data[1]?.trim()) {
|
||||
setPrompt(data[1]);
|
||||
window.__CHAT_MODEL_STATUS__ = 2;
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// input text
|
||||
if (window.__CHAT_MODEL_STATUS__ === 2 && event.keyCode === 9) { // TAB
|
||||
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
modelDom.innerHTML = '';
|
||||
delete window.__CHAT_MODEL_STATUS__;
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// ------------------ type in a space to complete the fill ------------------------------------
|
||||
if (event.keyCode === 32) {
|
||||
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
modelDom.innerHTML = '';
|
||||
delete window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
}
|
||||
|
||||
// ------------------ send --------------------------------------------------------------------
|
||||
if (event.keyCode === 13 && window.__CHAT_MODEL_CMD_PROMPT__) { // Enter
|
||||
const data = searchInput.value.split('|->');
|
||||
setPrompt(data[1]);
|
||||
|
||||
searchInput.value = window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
|
||||
initDom();
|
||||
|
||||
event.preventDefault();
|
||||
}
|
||||
}
|
||||
searchInput.removeEventListener('keydown', cmdKeydown, { capture: true });
|
||||
searchInput.addEventListener('keydown', cmdKeydown, { capture: true });
|
||||
|
||||
function cmdInput() {
|
||||
if (searchInput.value === '') {
|
||||
initDom();
|
||||
}
|
||||
|
||||
if (window.__CHAT_MODEL_STATUS__) return;
|
||||
|
||||
const query = searchInput.value;
|
||||
if (!query || !/^\//.test(query)) {
|
||||
initDom();
|
||||
return;
|
||||
}
|
||||
|
||||
// all cmd result
|
||||
if (query === '/') {
|
||||
renderList(data);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = data.filter(i => new RegExp(query.substring(1)).test(i.cmd));
|
||||
if (result.length > 0) {
|
||||
renderList(result);
|
||||
} else {
|
||||
initDom();
|
||||
}
|
||||
}
|
||||
searchInput.removeEventListener('input', cmdInput);
|
||||
searchInput.addEventListener('input', cmdInput);
|
||||
}
|
||||
}
|
||||
|
||||
function initDom() {
|
||||
const modelDom = document.querySelector('.chat-model-cmd-list');
|
||||
if (modelDom) {
|
||||
modelDom.innerHTML = '';
|
||||
}
|
||||
delete window.__CHAT_MODEL_CMD_PROMPT__;
|
||||
delete window.__CHAT_MODEL_CMD__;
|
||||
delete window.__CHAT_MODEL_STATUS__;
|
||||
delete window.__cmd_list;
|
||||
delete window.__cmd_index;
|
||||
}
|
||||
|
||||
if (
|
||||
document.readyState === "complete" ||
|
||||
document.readyState === "interactive"
|
||||
) {
|
||||
init();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
}
|
188
src-tauri/src/scripts/core.js
vendored
188
src-tauri/src/scripts/core.js
vendored
@ -1,188 +0,0 @@
|
||||
// *** Core Script - IPC ***
|
||||
|
||||
const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0];
|
||||
function transformCallback(callback = () => {}, once = false) {
|
||||
const identifier = uid();
|
||||
const prop = `_${identifier}`;
|
||||
Object.defineProperty(window, prop, {
|
||||
value: (result) => {
|
||||
if (once) {
|
||||
Reflect.deleteProperty(window, prop);
|
||||
}
|
||||
return callback(result)
|
||||
},
|
||||
writable: false,
|
||||
configurable: true,
|
||||
})
|
||||
return identifier;
|
||||
}
|
||||
async function invoke(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!window.__TAURI_POST_MESSAGE__) reject('__TAURI_POST_MESSAGE__ does not exist!');
|
||||
const callback = transformCallback((e) => {
|
||||
resolve(e);
|
||||
Reflect.deleteProperty(window, `_${error}`);
|
||||
}, true)
|
||||
const error = transformCallback((e) => {
|
||||
reject(e);
|
||||
Reflect.deleteProperty(window, `_${callback}`);
|
||||
}, true)
|
||||
window.__TAURI_POST_MESSAGE__({
|
||||
cmd,
|
||||
callback,
|
||||
error,
|
||||
...args
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function message(message) {
|
||||
invoke('messageDialog', {
|
||||
__tauriModule: 'Dialog',
|
||||
message: {
|
||||
cmd: 'messageDialog',
|
||||
message: message.toString(),
|
||||
title: null,
|
||||
type: null,
|
||||
buttonLabel: null
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
window.uid = uid;
|
||||
window.invoke = invoke;
|
||||
window.message = message;
|
||||
window.transformCallback = transformCallback;
|
||||
|
||||
async function init() {
|
||||
if (__TAURI_METADATA__.__currentWindow.label === 'tray') {
|
||||
document.getElementsByTagName('html')[0].style['font-size'] = '70%';
|
||||
}
|
||||
|
||||
async function platform() {
|
||||
return invoke('platform', {
|
||||
__tauriModule: 'Os',
|
||||
message: { cmd: 'platform' }
|
||||
});
|
||||
}
|
||||
|
||||
if (__TAURI_METADATA__.__currentWindow.label !== 'tray') {
|
||||
const _platform = await platform();
|
||||
const chatConf = await invoke('get_app_conf') || {};
|
||||
if (/darwin/.test(_platform) && !chatConf.titlebar) {
|
||||
const topStyleDom = document.createElement("style");
|
||||
topStyleDom.innerHTML = `#chatgpt-app-window-top{position:fixed;top:0;z-index:999999999;width:100%;height:24px;background:transparent;cursor:grab;cursor:-webkit-grab;user-select:none;-webkit-user-select:none;}#chatgpt-app-window-top:active {cursor:grabbing;cursor:-webkit-grabbing;}`;
|
||||
document.head.appendChild(topStyleDom);
|
||||
const topDom = document.createElement("div");
|
||||
topDom.id = "chatgpt-app-window-top";
|
||||
document.body.appendChild(topDom);
|
||||
|
||||
if (window.location.host === 'chat.openai.com') {
|
||||
const nav = document.body.querySelector('nav');
|
||||
if (nav) {
|
||||
const currentPaddingTop = parseInt(window.getComputedStyle(document.querySelector('nav'), null).getPropertyValue('padding-top').replace('px', ''), 10);
|
||||
const navStyleDom = document.createElement("style");
|
||||
navStyleDom.innerHTML = `nav{padding-top:${currentPaddingTop + topDom.clientHeight}px !important}`;
|
||||
document.head.appendChild(navStyleDom);
|
||||
}
|
||||
}
|
||||
|
||||
topDom.addEventListener("mousedown", () => invoke("drag_window"));
|
||||
topDom.addEventListener("touchstart", () => invoke("drag_window"));
|
||||
topDom.addEventListener("dblclick", () => invoke("fullscreen"));
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("click", (e) => {
|
||||
const origin = e.target.closest("a");
|
||||
if (!origin || !origin.target) return;
|
||||
if (origin && origin.href && origin.target !== '_self') {
|
||||
invoke('open_link', { url: origin.href });
|
||||
}
|
||||
});
|
||||
|
||||
// Fix Chinese input method "Enter" on Safari
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if(e.keyCode == 229) e.stopPropagation();
|
||||
}, true)
|
||||
|
||||
if (window.location.host === 'chat.openai.com') {
|
||||
window.__sync_prompts = async function() {
|
||||
await invoke('sync_prompts', { time: Date.now() });
|
||||
}
|
||||
}
|
||||
|
||||
coreZoom();
|
||||
}
|
||||
|
||||
function coreZoom() {
|
||||
const styleDom = document.createElement('style');
|
||||
styleDom.innerHTML = `
|
||||
#ZoomTopTip {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 20px;
|
||||
background: #2a2a2a;
|
||||
color: #fafafa;
|
||||
padding: 20px 15px;
|
||||
border-bottom-left-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
z-index: 999999;
|
||||
box-shadow: 0 2px 2px 2px #d8d8d8;
|
||||
}
|
||||
.ZoomTopTipAni {
|
||||
transition: opacity 200ms, display 200ms;
|
||||
display: none;
|
||||
opacity: 0;
|
||||
}
|
||||
`;
|
||||
document.head.append(styleDom);
|
||||
const zoomTipDom = document.createElement('div');
|
||||
zoomTipDom.id = 'ZoomTopTip';
|
||||
document.body.appendChild(zoomTipDom);
|
||||
function zoom(callback) {
|
||||
if (window.zoomSetTimeout) clearTimeout(window.zoomSetTimeout);
|
||||
const htmlZoom = window.localStorage.getItem("htmlZoom") || "100%";
|
||||
const html = document.getElementsByTagName("html")[0];
|
||||
const zoom = callback(htmlZoom);
|
||||
html.style.zoom = zoom;
|
||||
window.localStorage.setItem("htmlZoom", zoom);
|
||||
zoomTipDom.innerHTML = zoom;
|
||||
zoomTipDom.style.display = 'block';
|
||||
zoomTipDom.classList.remove('ZoomTopTipAni');
|
||||
window.zoomSetTimeout = setTimeout(() => {
|
||||
zoomTipDom.classList.add('ZoomTopTipAni');
|
||||
}, 2500);
|
||||
}
|
||||
function zoomDefault() {
|
||||
const htmlZoom = window.localStorage.getItem("htmlZoom");
|
||||
if (htmlZoom) {
|
||||
document.getElementsByTagName("html")[0].style.zoom = htmlZoom;
|
||||
}
|
||||
}
|
||||
function zoomIn() {
|
||||
zoom((htmlZoom) => `${Math.min(parseInt(htmlZoom) + 10, 200)}%`);
|
||||
}
|
||||
function zoomOut() {
|
||||
zoom((htmlZoom) => `${Math.max(parseInt(htmlZoom) - 10, 30)}%`);
|
||||
}
|
||||
function zoom0() {
|
||||
zoom(() => `100%`);
|
||||
}
|
||||
zoomDefault();
|
||||
window.__zoomIn = zoomIn;
|
||||
window.__zoomOut = zoomOut;
|
||||
window.__zoom0 = zoom0;
|
||||
}
|
||||
|
||||
if (
|
||||
document.readyState === "complete" ||
|
||||
document.readyState === "interactive"
|
||||
) {
|
||||
init();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
}
|
40
src-tauri/src/scripts/dalle2.js
vendored
40
src-tauri/src/scripts/dalle2.js
vendored
@ -1,40 +0,0 @@
|
||||
// *** Core Script - DALL·E 2 ***
|
||||
|
||||
function init() {
|
||||
document.addEventListener("click", (e) => {
|
||||
const origin = e.target.closest("a");
|
||||
if (!origin || !origin.target) return;
|
||||
if (origin && origin.href && origin.target !== '_self') {
|
||||
if (/\/(login|signup)$/.test(window.location.href)) {
|
||||
origin.target = '_self';
|
||||
} else {
|
||||
invoke('open_link', { url: origin.href });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (window.searchInterval) {
|
||||
clearInterval(window.searchInterval);
|
||||
}
|
||||
|
||||
window.searchInterval = setInterval(() => {
|
||||
const searchInput = document.querySelector('.image-prompt-form-wrapper form>.text-input');
|
||||
if (searchInput) {
|
||||
clearInterval(window.searchInterval);
|
||||
|
||||
if (!window.__CHATGPT_QUERY__) return;
|
||||
const query = decodeURIComponent(window.__CHATGPT_QUERY__);
|
||||
searchInput.focus();
|
||||
searchInput.value = query;
|
||||
}
|
||||
}, 200)
|
||||
}
|
||||
|
||||
if (
|
||||
document.readyState === "complete" ||
|
||||
document.readyState === "interactive"
|
||||
) {
|
||||
init();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
}
|
306
src-tauri/src/scripts/export.js
vendored
306
src-tauri/src/scripts/export.js
vendored
@ -1,306 +0,0 @@
|
||||
// *** Core Script - Export ***
|
||||
|
||||
async function init() {
|
||||
if (window.location.pathname === '/auth/login') return;
|
||||
const buttonOuterHTMLFallback = `<button class="btn flex justify-center gap-2 btn-neutral" id="download-png-button">Try Again</button>`;
|
||||
removeButtons();
|
||||
if (window.buttonsInterval) {
|
||||
clearInterval(window.buttonsInterval);
|
||||
}
|
||||
if (window.innerWidth < 767) return;
|
||||
|
||||
const chatConf = await invoke('get_app_conf') || {};
|
||||
window.buttonsInterval = setInterval(() => {
|
||||
const actionsArea = document.querySelector("form>div>div");
|
||||
if (!actionsArea) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldAddButtons(actionsArea)) {
|
||||
let TryAgainButton = actionsArea.querySelector("button");
|
||||
if (!TryAgainButton) {
|
||||
const parentNode = document.createElement("div");
|
||||
parentNode.innerHTML = buttonOuterHTMLFallback;
|
||||
TryAgainButton = parentNode.querySelector("button");
|
||||
}
|
||||
addActionsButtons(actionsArea, TryAgainButton, chatConf);
|
||||
} else if (shouldRemoveButtons()) {
|
||||
removeButtons();
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
const Format = {
|
||||
PNG: "png",
|
||||
PDF: "pdf",
|
||||
};
|
||||
|
||||
function shouldRemoveButtons() {
|
||||
if (document.querySelector("form .text-2xl")) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function shouldAddButtons(actionsArea) {
|
||||
// first, check if there's a "Try Again" button and no other buttons
|
||||
const buttons = actionsArea.querySelectorAll("button");
|
||||
|
||||
const hasTryAgainButton = Array.from(buttons).some((button) => {
|
||||
return !/download-/.test(button.id);
|
||||
});
|
||||
|
||||
const stopBtn = buttons?.[0]?.innerText;
|
||||
|
||||
if (/Stop generating/ig.test(stopBtn)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (buttons.length === 2 && (/Regenerate response/ig.test(stopBtn) || buttons[1].innerText === '')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (hasTryAgainButton && buttons.length === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// otherwise, check if open screen is not visible
|
||||
const isOpenScreen = document.querySelector("h1.text-4xl");
|
||||
if (isOpenScreen) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check if the conversation is finished and there are no share buttons
|
||||
const finishedConversation = document.querySelector("form button>svg");
|
||||
const hasShareButtons = actionsArea.querySelectorAll("button[share-ext]");
|
||||
if (finishedConversation && !hasShareButtons.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function removeButtons() {
|
||||
const downloadPngButton = document.getElementById("download-png-button");
|
||||
const downloadPdfButton = document.getElementById("download-pdf-button");
|
||||
const downloadMdButton = document.getElementById("download-markdown-button");
|
||||
const refreshButton = document.getElementById("refresh-page-button");
|
||||
if (downloadPngButton) {
|
||||
downloadPngButton.remove();
|
||||
}
|
||||
if (downloadPdfButton) {
|
||||
downloadPdfButton.remove();
|
||||
}
|
||||
if (downloadPdfButton) {
|
||||
downloadMdButton.remove();
|
||||
}
|
||||
if (refreshButton) {
|
||||
refreshButton.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function addActionsButtons(actionsArea, TryAgainButton) {
|
||||
// Export markdown
|
||||
const exportMd = TryAgainButton.cloneNode(true);
|
||||
exportMd.id = "download-markdown-button";
|
||||
exportMd.setAttribute("share-ext", "true");
|
||||
exportMd.title = "Export Markdown";
|
||||
|
||||
exportMd.innerHTML = setIcon('md');
|
||||
exportMd.onclick = () => {
|
||||
exportMarkdown();
|
||||
};
|
||||
actionsArea.appendChild(exportMd);
|
||||
|
||||
// Generate PNG
|
||||
const downloadPngButton = TryAgainButton.cloneNode(true);
|
||||
downloadPngButton.id = "download-png-button";
|
||||
downloadPngButton.setAttribute("share-ext", "true");
|
||||
downloadPngButton.title = "Generate PNG";
|
||||
downloadPngButton.innerHTML = setIcon('png');
|
||||
downloadPngButton.onclick = () => {
|
||||
downloadThread();
|
||||
};
|
||||
actionsArea.appendChild(downloadPngButton);
|
||||
|
||||
// Generate PDF
|
||||
const downloadPdfButton = TryAgainButton.cloneNode(true);
|
||||
downloadPdfButton.id = "download-pdf-button";
|
||||
downloadPdfButton.setAttribute("share-ext", "true");
|
||||
downloadPdfButton.title = "Download PDF";
|
||||
downloadPdfButton.innerHTML = setIcon('pdf');
|
||||
downloadPdfButton.onclick = () => {
|
||||
downloadThread({ as: Format.PDF });
|
||||
};
|
||||
actionsArea.appendChild(downloadPdfButton);
|
||||
|
||||
// Refresh
|
||||
const refreshButton = TryAgainButton.cloneNode(true);
|
||||
refreshButton.id = "refresh-page-button";
|
||||
refreshButton.title = "Refresh the Page";
|
||||
refreshButton.innerHTML = setIcon('refresh');
|
||||
refreshButton.onclick = () => {
|
||||
window.location.reload();
|
||||
};
|
||||
actionsArea.appendChild(refreshButton);
|
||||
}
|
||||
|
||||
async function exportMarkdown() {
|
||||
const content = Array.from(document.querySelectorAll('main .items-center>div')).map(i => {
|
||||
let j = i.cloneNode(true);
|
||||
if (/dark\:bg-gray-800/.test(i.getAttribute('class'))) {
|
||||
j.innerHTML = `<blockquote>${i.innerHTML}</blockquote>`;
|
||||
}
|
||||
return j.innerHTML;
|
||||
}).join('');
|
||||
const data = ExportMD.turndown(content);
|
||||
const { id, filename } = getName();
|
||||
await invoke('save_file', { name: `notes/${id}.md`, content: data });
|
||||
await invoke('download_list', { pathname: 'chat.notes.json', filename, id, dir: 'notes' });
|
||||
}
|
||||
|
||||
function downloadThread({ as = Format.PNG } = {}) {
|
||||
const elements = new Elements();
|
||||
elements.fixLocation();
|
||||
const pixelRatio = window.devicePixelRatio;
|
||||
const minRatio = as === Format.PDF ? 2 : 2.5;
|
||||
window.devicePixelRatio = Math.max(pixelRatio, minRatio);
|
||||
|
||||
html2canvas(elements.thread, {
|
||||
letterRendering: true,
|
||||
}).then(async function (canvas) {
|
||||
elements.restoreLocation();
|
||||
window.devicePixelRatio = pixelRatio;
|
||||
const imgData = canvas.toDataURL("image/png");
|
||||
requestAnimationFrame(() => {
|
||||
if (as === Format.PDF) {
|
||||
return handlePdf(imgData, canvas, pixelRatio);
|
||||
} else {
|
||||
handleImg(imgData);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function handleImg(imgData) {
|
||||
const binaryData = atob(imgData.split("base64,")[1]);
|
||||
const data = [];
|
||||
for (let i = 0; i < binaryData.length; i++) {
|
||||
data.push(binaryData.charCodeAt(i));
|
||||
}
|
||||
const { pathname, id, filename } = getName();
|
||||
await invoke('download', { name: `download/img/${id}.png`, blob: data });
|
||||
await invoke('download_list', { pathname, filename, id, dir: 'download' });
|
||||
}
|
||||
|
||||
async function handlePdf(imgData, canvas, pixelRatio) {
|
||||
const { jsPDF } = window.jspdf;
|
||||
const orientation = canvas.width > canvas.height ? "l" : "p";
|
||||
var pdf = new jsPDF(orientation, "pt", [
|
||||
canvas.width / pixelRatio,
|
||||
canvas.height / pixelRatio,
|
||||
]);
|
||||
var pdfWidth = pdf.internal.pageSize.getWidth();
|
||||
var pdfHeight = pdf.internal.pageSize.getHeight();
|
||||
pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight, '', 'FAST');
|
||||
const { pathname, id, filename } = getName();
|
||||
const data = pdf.__private__.getArrayBuffer(pdf.__private__.buildDocument());
|
||||
await invoke('download', { name: `download/pdf/${id}.pdf`, blob: Array.from(new Uint8Array(data)) });
|
||||
await invoke('download_list', { pathname, filename, id, dir: 'download' });
|
||||
}
|
||||
|
||||
function getName() {
|
||||
const id = window.crypto.getRandomValues(new Uint32Array(1))[0].toString(36);
|
||||
const name = document.querySelector('nav .overflow-y-auto a.hover\\:bg-gray-800')?.innerText?.trim() || '';
|
||||
return { filename: name ? name : id, id, pathname: 'chat.download.json' };
|
||||
}
|
||||
|
||||
class Elements {
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
init() {
|
||||
// this.threadWrapper = document.querySelector(".cdfdFe");
|
||||
this.spacer = document.querySelector("[class*='h-48'].w-full.flex-shrink-0");
|
||||
this.thread = document.querySelector(
|
||||
"[class*='react-scroll-to-bottom']>[class*='react-scroll-to-bottom']>div"
|
||||
);
|
||||
|
||||
// fix: old chat https://github.com/lencx/ChatGPT/issues/185
|
||||
if (!this.thread) {
|
||||
this.thread = document.querySelector("main .overflow-y-auto");
|
||||
}
|
||||
|
||||
// h-full overflow-y-auto
|
||||
this.positionForm = document.querySelector("form").parentNode;
|
||||
// this.styledThread = document.querySelector("main");
|
||||
// this.threadContent = document.querySelector(".gAnhyd");
|
||||
this.scroller = Array.from(
|
||||
document.querySelectorAll('[class*="react-scroll-to"]')
|
||||
).filter((el) => el.classList.contains("h-full"))[0];
|
||||
|
||||
// fix: old chat
|
||||
if (!this.scroller) {
|
||||
this.scroller = document.querySelector('main .overflow-y-auto');
|
||||
}
|
||||
|
||||
this.hiddens = Array.from(document.querySelectorAll(".overflow-hidden"));
|
||||
this.images = Array.from(document.querySelectorAll("img[srcset]"));
|
||||
}
|
||||
fixLocation() {
|
||||
this.hiddens.forEach((el) => {
|
||||
el.classList.remove("overflow-hidden");
|
||||
});
|
||||
this.spacer.style.display = "none";
|
||||
this.thread.style.maxWidth = "960px";
|
||||
this.thread.style.marginInline = "auto";
|
||||
this.positionForm.style.display = "none";
|
||||
this.scroller.classList.remove("h-full");
|
||||
this.scroller.style.minHeight = "100vh";
|
||||
this.images.forEach((img) => {
|
||||
const srcset = img.getAttribute("srcset");
|
||||
img.setAttribute("srcset_old", srcset);
|
||||
img.setAttribute("srcset", "");
|
||||
});
|
||||
//Fix to the text shifting down when generating the canvas
|
||||
document.body.style.lineHeight = "0.5";
|
||||
}
|
||||
restoreLocation() {
|
||||
this.hiddens.forEach((el) => {
|
||||
el.classList.add("overflow-hidden");
|
||||
});
|
||||
this.spacer.style.display = null;
|
||||
this.thread.style.maxWidth = null;
|
||||
this.thread.style.marginInline = null;
|
||||
this.positionForm.style.display = null;
|
||||
this.scroller.classList.add("h-full");
|
||||
this.scroller.style.minHeight = null;
|
||||
this.images.forEach((img) => {
|
||||
const srcset = img.getAttribute("srcset_old");
|
||||
img.setAttribute("srcset", srcset);
|
||||
img.setAttribute("srcset_old", "");
|
||||
});
|
||||
document.body.style.lineHeight = null;
|
||||
}
|
||||
}
|
||||
|
||||
function setIcon(type) {
|
||||
return {
|
||||
// link: `<svg class="chatappico" viewBox="0 0 1024 1024"><path d="M1007.382 379.672L655.374 75.702C624.562 49.092 576 70.694 576 112.03v160.106C254.742 275.814 0 340.2 0 644.652c0 122.882 79.162 244.618 166.666 308.264 27.306 19.862 66.222-5.066 56.154-37.262C132.132 625.628 265.834 548.632 576 544.17V720c0 41.4 48.6 62.906 79.374 36.328l352.008-304c22.142-19.124 22.172-53.506 0-72.656z" p-id="8506" fill="currentColor"></path></svg>`,
|
||||
png: `<svg class="chatappico" viewBox="0 0 1070 1024"><path d="M981.783273 0H85.224727C38.353455 0 0 35.374545 0 83.083636v844.893091c0 47.616 38.353455 86.574545 85.178182 86.574546h903.633454c46.917818 0 81.733818-38.958545 81.733819-86.574546V83.083636C1070.592 35.374545 1028.701091 0 981.783273 0zM335.825455 135.912727c74.193455 0 134.330182 60.974545 134.330181 136.285091 0 75.170909-60.136727 136.192-134.330181 136.192-74.286545 0-134.516364-61.021091-134.516364-136.192 0-75.264 60.229818-136.285091 134.516364-136.285091z m-161.512728 745.937455a41.890909 41.890909 0 0 1-27.648-10.379637 43.752727 43.752727 0 0 1-4.654545-61.067636l198.097454-255.162182a42.123636 42.123636 0 0 1 57.716364-6.702545l116.549818 128.139636 286.906182-352.814545c14.615273-18.711273 90.251636-106.775273 135.866182-6.935273 0.093091-0.093091 0.093091 112.965818 0.232727 247.761455 0.093091 140.8 0.093091 317.067636 0.093091 317.067636-1.024-0.093091-762.740364 0.093091-763.112727 0.093091z" fill="currentColor"></path></svg>`,
|
||||
pdf: `<svg class="chatappico pdf" viewBox="0 0 1024 1024"><path d="M821.457602 118.382249H205.725895c-48.378584 0-87.959995 39.583368-87.959996 87.963909v615.731707c0 48.378584 39.581411 87.959995 87.959996 87.959996h615.733664c48.380541 0 87.961952-39.581411 87.961952-87.959996V206.346158c-0.001957-48.378584-39.583368-87.963909-87.963909-87.963909zM493.962468 457.544987c-10.112054 32.545237-21.72487 82.872662-38.806571 124.248336-8.806957 22.378397-8.380404 18.480717-15.001764 32.609808l5.71738-1.851007c58.760658-16.443827 99.901532-20.519564 138.162194-27.561607-7.67796-6.06371-14.350194-10.751884-19.631237-15.586807-26.287817-29.101504-35.464584-34.570387-70.440002-111.862636v0.003913z m288.36767 186.413594c-7.476424 8.356924-20.670227 13.191847-40.019704 13.191847-33.427694 0-63.808858-9.229597-107.79277-31.660824-75.648648 8.356924-156.097 17.214754-201.399704 31.729308-2.199293 0.876587-4.832967 1.759043-7.916674 3.077836-54.536215 93.237125-95.031389 132.767663-130.621199 131.19646-11.286054-0.49895-27.694661-7.044-32.973748-10.11988l-6.52157-6.196764-2.29517-4.353583c-3.07588-7.91863-3.954423-15.395054-2.197337-23.751977 4.838837-23.309771 29.907651-60.251638 82.686779-93.237126 8.356924-6.159587 27.430511-15.897917 45.020944-24.25484 13.311204-21.177004 19.45905-34.744531 36.341171-72.259702 19.102937-45.324228 36.505531-99.492589 47.500041-138.191543v-0.44025c-16.267727-53.219378-25.945401-89.310095-9.67376-147.80856 3.958337-16.71189 18.46702-33.864031 34.748444-33.864031h10.552304c10.115967 0 19.791684 3.520043 26.829814 10.552304 29.029107 29.031064 15.39114 103.824649 0.8805 162.323113-0.8805 2.63563-1.322707 4.832967-1.761 6.153717 17.59239 49.697378 45.400538 98.774492 73.108895 121.647926 11.436717 8.791304 22.638634 18.899444 36.71098 26.814161 19.791684-2.20125 37.517128-4.11487 55.547812-4.11487 54.540128 0 87.525615 9.67963 100.279169 30.351814 4.400543 7.034217 6.595923 15.389184 5.281043 24.1844-0.44025 10.996467-4.39663 21.112434-12.31526 29.031064z m-27.796407-36.748157c-4.394673-4.398587-17.024957-16.936907-78.601259-16.936907-3.073923 0-10.622744-0.784623-14.57521 3.612007 32.104987 14.072347 62.830525 24.757704 83.058545 24.757703 3.083707 0 5.72325-0.442207 8.356923-0.876586h1.759044c2.20125-0.8805 3.520043-1.324663 3.960293-5.71738-0.87463-1.324663-1.757087-3.083707-3.958336-4.838837z m-387.124553 63.041845c-9.237424 5.27713-16.71189 10.112054-21.112433 13.634053-31.226444 28.586901-51.018128 57.616008-53.217422 74.331812 19.789727-6.59788 45.737084-35.626987 74.329855-87.961952v-0.003913z m125.574957-297.822284l2.197336-1.761c3.079793-14.072347 5.232127-29.189554 7.87167-38.869184l1.318794-7.036174c4.39663-25.070771 2.71781-39.720334-4.76057-50.272637l-6.59788-2.20125a57.381208 57.381208 0 0 0-3.079794 5.27713c-7.474467 18.47289-7.063567 55.283661 3.0524 94.865072l-0.001956-0.001957z" fill="currentColor"></path></svg>`,
|
||||
md: `<svg class="chatappico md" viewBox="0 0 1024 1024" width="200" height="200"><path d="M128 128h768a42.666667 42.666667 0 0 1 42.666667 42.666667v682.666666a42.666667 42.666667 0 0 1-42.666667 42.666667H128a42.666667 42.666667 0 0 1-42.666667-42.666667V170.666667a42.666667 42.666667 0 0 1 42.666667-42.666667z m170.666667 533.333333v-170.666666l85.333333 85.333333 85.333333-85.333333v170.666666h85.333334v-298.666666h-85.333334l-85.333333 85.333333-85.333333-85.333333H213.333333v298.666666h85.333334z m469.333333-128v-170.666666h-85.333333v170.666666h-85.333334l128 128 128-128h-85.333333z" p-id="1381" fill="currentColor"></path></svg>`,
|
||||
refresh: `<svg class="chatappico refresh" viewBox="0 0 1024 1024"><path d="M512 63.5C264.3 63.5 63.5 264.3 63.5 512S264.3 960.5 512 960.5 960.5 759.7 960.5 512 759.7 63.5 512 63.5zM198 509.6h87.6c0-136.3 102.3-243.4 233.7-238.5 43.8 0 82.8 14.6 121.7 34.1L597.2 349c-24.4-9.8-53.6-19.5-82.8-19.5-92.5 0-170.4 77.9-170.4 180.1h87.6L314.8 631.3 198 509.6z m540.3-0.1c0 131.4-102.2 243.4-228.8 243.4-43.8 0-82.8-19.4-121.7-38.9l43.8-43.8c24.4 9.8 53.6 19.5 82.8 19.5 92.5 0 170.4-77.9 170.4-180.1h-92.5l116.9-121.7L826 509.5h-87.7z" fill="currentColor"></path></svg>`,
|
||||
}[type];
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('resize', init);
|
||||
|
||||
if (
|
||||
document.readyState === "complete" ||
|
||||
document.readyState === "interactive"
|
||||
) {
|
||||
init();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
}
|
38
src-tauri/src/scripts/markdown.export.js
vendored
38
src-tauri/src/scripts/markdown.export.js
vendored
@ -1,38 +0,0 @@
|
||||
var ExportMD = (function () {
|
||||
if (!TurndownService || !turndownPluginGfm) return;
|
||||
const hljsREG = /^.*(hljs).*(language-[a-z0-9]+).*$/i;
|
||||
const gfm = turndownPluginGfm.gfm
|
||||
const turndownService = new TurndownService({
|
||||
hr: '---'
|
||||
})
|
||||
.use(gfm)
|
||||
.addRule('code', {
|
||||
filter: (node) => {
|
||||
if (node.nodeName === 'CODE' && hljsREG.test(node.classList.value)) {
|
||||
return 'code';
|
||||
}
|
||||
},
|
||||
replacement: (content, node) => {
|
||||
const classStr = node.getAttribute('class');
|
||||
if (hljsREG.test(classStr)) {
|
||||
const lang = classStr.match(/.*language-(\w+)/)[1];
|
||||
if (lang) {
|
||||
return `\`\`\`${lang}\n${content}\n\`\`\``;
|
||||
}
|
||||
return `\`\`\`\n${content}\n\`\`\``;
|
||||
}
|
||||
}
|
||||
})
|
||||
.addRule('ignore', {
|
||||
filter: ['button', 'img'],
|
||||
replacement: () => '',
|
||||
})
|
||||
.addRule('table', {
|
||||
filter: 'table',
|
||||
replacement: function(content, node) {
|
||||
return `\`\`\`${content}\n\`\`\``;
|
||||
},
|
||||
});
|
||||
|
||||
return turndownService;
|
||||
}({}));
|
84
src-tauri/src/scripts/popup.core.js
vendored
84
src-tauri/src/scripts/popup.core.js
vendored
@ -1,84 +0,0 @@
|
||||
// *** Core Script - DALL·E 2 Core ***
|
||||
|
||||
async function init() {
|
||||
const chatConf = await invoke('get_app_conf') || {};
|
||||
if (!chatConf.popup_search) return;
|
||||
if (!window.FloatingUIDOM) return;
|
||||
|
||||
const styleDom = document.createElement('style');
|
||||
styleDom.innerHTML = `
|
||||
#chagpt-selection-menu {
|
||||
display: none;
|
||||
width: max-content;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
background: #4a4a4a;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
padding: 3px 5px;
|
||||
border-radius: 2px;
|
||||
font-size: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
`;
|
||||
document.head.append(styleDom);
|
||||
|
||||
const selectionMenu = document.createElement('div');
|
||||
selectionMenu.id = 'chagpt-selection-menu';
|
||||
selectionMenu.innerHTML = 'DALL·E 2';
|
||||
document.body.appendChild(selectionMenu);
|
||||
const { computePosition, flip, offset, shift } = window.FloatingUIDOM;
|
||||
|
||||
document.body.addEventListener('mousedown', async (e) => {
|
||||
selectionMenu.style.display = 'none';
|
||||
if (e.target.id === 'chagpt-selection-menu') {
|
||||
await invoke('dalle2_search_window', { query: encodeURIComponent(window.__DALLE2_CONTENT__) });
|
||||
} else {
|
||||
delete window.__DALLE2_CONTENT__;
|
||||
}
|
||||
});
|
||||
|
||||
document.body.addEventListener("mouseup", async (e) => {
|
||||
selectionMenu.style.display = 'none';
|
||||
const selection = window.getSelection();
|
||||
window.__DALLE2_CONTENT__ = selection.toString().trim();
|
||||
|
||||
if (!window.__DALLE2_CONTENT__) return;
|
||||
|
||||
if (selection.rangeCount > 0) {
|
||||
const range = selection.getRangeAt(0);
|
||||
const rect = range.getClientRects()[0];
|
||||
|
||||
const rootEl = document.createElement('div');
|
||||
rootEl.style.top = `${rect.top}px`;
|
||||
rootEl.style.position = 'fixed';
|
||||
rootEl.style.left = `${rect.left}px`;
|
||||
document.body.appendChild(rootEl);
|
||||
|
||||
selectionMenu.style.display = 'block';
|
||||
computePosition(rootEl, selectionMenu, {
|
||||
placement: 'top',
|
||||
middleware: [
|
||||
flip(),
|
||||
offset(5),
|
||||
shift({ padding: 5 })
|
||||
]
|
||||
}).then(({x, y}) => {
|
||||
Object.assign(selectionMenu.style, {
|
||||
left: `${x}px`,
|
||||
top: `${y}px`,
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
document.readyState === "complete" ||
|
||||
document.readyState === "interactive"
|
||||
) {
|
||||
init();
|
||||
} else {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
}
|
@ -4,7 +4,7 @@ use regex::Regex;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{self, File},
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
@ -25,46 +25,41 @@ pub fn exists(path: &Path) -> bool {
|
||||
Path::new(path).exists()
|
||||
}
|
||||
|
||||
pub fn create_file(path: &Path) -> Result<File> {
|
||||
if let Some(p) = path.parent() {
|
||||
fs::create_dir_all(p)?
|
||||
pub fn create_file<P: AsRef<Path>>(filename: P) -> Result<()> {
|
||||
let filename = filename.as_ref();
|
||||
if let Some(parent) = filename.parent() {
|
||||
if !parent.exists() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
}
|
||||
File::create(path).map_err(Into::into)
|
||||
fs::File::create(filename)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_chatgpt_prompts() {
|
||||
let sync_file = app_root().join("cache_model").join("chatgpt_prompts.json");
|
||||
let sync_file = app_root()
|
||||
.join("cache_prompts")
|
||||
.join("chatgpt_prompts.json");
|
||||
if !exists(&sync_file) {
|
||||
create_file(&sync_file).unwrap();
|
||||
fs::write(&sync_file, "[]").unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn script_path() -> PathBuf {
|
||||
let script_file = app_root().join("main.js");
|
||||
if !exists(&script_file) {
|
||||
create_file(&script_file).unwrap();
|
||||
fs::write(
|
||||
&script_file,
|
||||
format!(
|
||||
"// *** ChatGPT User Script ***\n// @github: https://github.com/lencx/ChatGPT \n// @path: {}\n\nconsole.log('🤩 Hello ChatGPT!!!');",
|
||||
&script_file.to_string_lossy()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
script_file
|
||||
}
|
||||
|
||||
pub fn user_script() -> String {
|
||||
let user_script_content = fs::read_to_string(script_path()).unwrap_or_else(|_| "".to_string());
|
||||
let user_script_file = app_root().join("scripts").join("main.js");
|
||||
let user_script_content = fs::read_to_string(user_script_file).unwrap_or_else(|_| "".to_string());
|
||||
format!(
|
||||
"window.addEventListener('DOMContentLoaded', function() {{\n{}\n}})",
|
||||
user_script_content
|
||||
)
|
||||
}
|
||||
|
||||
pub fn load_script(filename: &str) -> String {
|
||||
let script_file = app_root().join("scripts").join(filename);
|
||||
fs::read_to_string(script_file).unwrap_or_else(|_| "".to_string())
|
||||
}
|
||||
|
||||
pub fn open_file(path: PathBuf) {
|
||||
let pathname = convert_path(path.to_str().unwrap());
|
||||
info!("open_file: {}", pathname);
|
||||
|
@ -7,7 +7,7 @@
|
||||
},
|
||||
"package": {
|
||||
"productName": "ChatGPT",
|
||||
"version": "0.12.0"
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
@ -15,6 +15,9 @@
|
||||
"globalShortcut": {
|
||||
"all": true
|
||||
},
|
||||
"shell": {
|
||||
"all": true
|
||||
},
|
||||
"fs": {
|
||||
"all": false,
|
||||
"readFile": true,
|
||||
@ -25,7 +28,8 @@
|
||||
"removeFile": true,
|
||||
"removeDir": true,
|
||||
"scope": [
|
||||
"$HOME/.chatgpt/**"
|
||||
"$HOME/.chatgpt/**",
|
||||
"$DOWNLOAD/**"
|
||||
]
|
||||
},
|
||||
"path": {
|
||||
@ -83,7 +87,43 @@
|
||||
}
|
||||
},
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": null,
|
||||
"dangerousRemoteDomainIpcAccess": [
|
||||
{
|
||||
"windows": [
|
||||
"core",
|
||||
"main",
|
||||
"tray"
|
||||
],
|
||||
"domain": "chat.openai.com",
|
||||
"enableTauriAPI": true
|
||||
},
|
||||
{
|
||||
"windows": [
|
||||
"core",
|
||||
"main"
|
||||
],
|
||||
"domain": "labs.openai.com",
|
||||
"enableTauriAPI": true
|
||||
},
|
||||
{
|
||||
"windows": [
|
||||
"core",
|
||||
"main",
|
||||
"tray"
|
||||
],
|
||||
"domain": "openai.com",
|
||||
"enableTauriAPI": true
|
||||
},
|
||||
{
|
||||
"windows": [
|
||||
"chatgpt_sponsors",
|
||||
"app_website"
|
||||
],
|
||||
"domain": "app.nofwl.com",
|
||||
"enableTauriAPI": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"updater": {
|
||||
"active": true,
|
||||
|
3
src/components/FilePath/index.tsx
vendored
3
src/components/FilePath/index.tsx
vendored
@ -16,7 +16,8 @@ const FilePath: FC<FilePathProps> = ({ className, label = 'PATH', paths = '', ur
|
||||
const [filePath, setPath] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!path && !url) return;
|
||||
if (!(paths || url)) return;
|
||||
|
||||
(async () => {
|
||||
if (url) {
|
||||
setPath(url);
|
||||
|
58
src/hooks/useChatModel.ts
vendored
58
src/hooks/useChatModel.ts
vendored
@ -1,58 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { clone } from 'lodash';
|
||||
import { invoke } from '@tauri-apps/api';
|
||||
|
||||
import { CHAT_MODEL_JSON, CHAT_MODEL_CMD_JSON, readJSON, writeJSON } from '@/utils';
|
||||
import useInit from '@/hooks/useInit';
|
||||
|
||||
export default function useChatModel(key: string, file = CHAT_MODEL_JSON) {
|
||||
const [modelJson, setModelJson] = useState<Record<string, any>>({});
|
||||
|
||||
useInit(async () => {
|
||||
const data = await readJSON(file, {
|
||||
defaultVal: { name: 'ChatGPT Model', [key]: null },
|
||||
});
|
||||
setModelJson(data);
|
||||
});
|
||||
|
||||
const modelSet = async (data: Record<string, any>[] | Record<string, any>) => {
|
||||
const oData = clone(modelJson);
|
||||
oData[key] = data;
|
||||
await writeJSON(file, oData);
|
||||
setModelJson(oData);
|
||||
};
|
||||
|
||||
return { modelJson, modelSet, modelData: modelJson?.[key] || [] };
|
||||
}
|
||||
|
||||
export function useCacheModel(file = '') {
|
||||
const [modelCacheJson, setModelCacheJson] = useState<Record<string, any>[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!file) return;
|
||||
(async () => {
|
||||
const data = await readJSON(file, { isRoot: true, isList: true });
|
||||
setModelCacheJson(data);
|
||||
})();
|
||||
}, [file]);
|
||||
|
||||
const modelCacheSet = async (data: Record<string, any>[], newFile = '') => {
|
||||
await writeJSON(newFile ? newFile : file, data, { isRoot: true });
|
||||
setModelCacheJson(data);
|
||||
await modelCacheCmd();
|
||||
};
|
||||
|
||||
const modelCacheCmd = async () => {
|
||||
// Generate the `chat.model.cmd.json` file and refresh the page for the slash command to take effect.
|
||||
const list = await invoke('cmd_list');
|
||||
await writeJSON(CHAT_MODEL_CMD_JSON, {
|
||||
name: 'ChatGPT CMD',
|
||||
last_updated: Date.now(),
|
||||
data: list,
|
||||
});
|
||||
await invoke('window_reload', { label: 'core' });
|
||||
await invoke('window_reload', { label: 'tray' });
|
||||
};
|
||||
|
||||
return { modelCacheJson, modelCacheSet, modelCacheCmd };
|
||||
}
|
68
src/hooks/useChatPrompt.ts
vendored
Normal file
68
src/hooks/useChatPrompt.ts
vendored
Normal file
@ -0,0 +1,68 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { clone } from 'lodash';
|
||||
import { invoke } from '@tauri-apps/api';
|
||||
|
||||
import { CHAT_PROMPT_JSON, CHAT_PROMPT_CMD_JSON, readJSON, writeJSON } from '@/utils';
|
||||
import useInit from '@/hooks/useInit';
|
||||
|
||||
export default function useChatPrompt(key: string, file = CHAT_PROMPT_JSON) {
|
||||
const [promptJson, setPromptJson] = useState<Record<string, any>>({});
|
||||
|
||||
useInit(async () => {
|
||||
const data = await readJSON(file, {
|
||||
defaultVal: { name: 'ChatGPT Prompts', [key]: null },
|
||||
});
|
||||
setPromptJson(data);
|
||||
});
|
||||
|
||||
const promptSet = async (data: Record<string, any>[] | Record<string, any>) => {
|
||||
const oData = clone(promptJson);
|
||||
oData[key] = data;
|
||||
|
||||
await writeJSON(file, oData);
|
||||
setPromptJson(oData);
|
||||
};
|
||||
|
||||
const promptUpdate = async (id: string, field: string, value: any) => {
|
||||
const oData = clone(promptJson);
|
||||
const idx = oData[key].findIndex((v: any) => v.id === id);
|
||||
oData[key][idx][field] = value;
|
||||
|
||||
await writeJSON(file, oData);
|
||||
setPromptJson(oData);
|
||||
};
|
||||
|
||||
return { promptJson, promptSet, promptUpdate, promptData: promptJson?.[key] || [] };
|
||||
}
|
||||
|
||||
export function useCachePrompt(file = '') {
|
||||
const [promptCacheJson, setPromptCacheJson] = useState<Record<string, any>[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!file) return;
|
||||
(async () => {
|
||||
const data = await readJSON(file, { isRoot: true, isList: true });
|
||||
setPromptCacheJson(data);
|
||||
})();
|
||||
}, [file]);
|
||||
|
||||
const promptCacheSet = async (data: Record<string, any>[], newFile = '') => {
|
||||
await writeJSON(newFile ? newFile : file, data, { isRoot: true });
|
||||
setPromptCacheJson(data);
|
||||
await promptCacheCmd();
|
||||
};
|
||||
|
||||
const promptCacheCmd = async () => {
|
||||
// Generate the `chat.prompt.cmd.json` file and refresh the page for the slash command to take effect.
|
||||
const list = await invoke('cmd_list');
|
||||
await writeJSON(CHAT_PROMPT_CMD_JSON, {
|
||||
name: 'ChatGPT CMD',
|
||||
last_updated: Date.now(),
|
||||
data: list,
|
||||
});
|
||||
await invoke('window_reload', { label: 'core' });
|
||||
await invoke('window_reload', { label: 'tray' });
|
||||
};
|
||||
|
||||
return { promptCacheJson, promptCacheSet, promptCacheCmd };
|
||||
}
|
1
src/hooks/useColumns.tsx
vendored
1
src/hooks/useColumns.tsx
vendored
@ -74,6 +74,7 @@ export const EditRow: FC<EditRowProps> = ({ rowKey, row, actions }) => {
|
||||
onChange={handleChange}
|
||||
{...DISABLE_AUTO_COMPLETE}
|
||||
onPressEnter={handleSave}
|
||||
onBlur={handleSave}
|
||||
/>
|
||||
) : (
|
||||
<div className="rowedit" onClick={handleEdit}>
|
||||
|
6
src/layout/index.tsx
vendored
6
src/layout/index.tsx
vendored
@ -23,8 +23,8 @@ export default function ChatLayout() {
|
||||
if (location.search === '?type=control') {
|
||||
go('/settings');
|
||||
}
|
||||
if (location.search === '?type=preview') {
|
||||
go('/?type=preview');
|
||||
if (location.search === '?type=scripts') {
|
||||
go('/scripts');
|
||||
}
|
||||
setMenuKey(location.pathname);
|
||||
setDashboard(location.pathname === '/');
|
||||
@ -88,7 +88,7 @@ export default function ChatLayout() {
|
||||
theme={appInfo.appTheme === 'dark' ? 'dark' : 'light'}
|
||||
inlineIndent={12}
|
||||
items={menuItems}
|
||||
// defaultOpenKeys={['/model']}
|
||||
// defaultOpenKeys={['/prompts']}
|
||||
onClick={(i) => go(i.key)}
|
||||
/>
|
||||
</Sider>
|
||||
|
31
src/main.scss
vendored
31
src/main.scss
vendored
@ -73,6 +73,11 @@ body,
|
||||
}
|
||||
}
|
||||
|
||||
.action-btn,
|
||||
.file-path {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chat-file-path {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
@ -109,3 +114,29 @@ body,
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.editor-task {
|
||||
margin-bottom: 5px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
.ant-breadcrumb-link {
|
||||
padding: 3px 5px;
|
||||
transition: all 300ms ease;
|
||||
border-radius: 4px;
|
||||
&:hover {
|
||||
color: rgba(120, 120, 90, 0.88);
|
||||
background-color: rgba(40, 40, 40, 0.06);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.editor-btn {
|
||||
cursor: pointer;
|
||||
margin-left: 5px;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-message {
|
||||
max-width: 500px;
|
||||
}
|
||||
|
44
src/routes.tsx
vendored
44
src/routes.tsx
vendored
@ -5,24 +5,22 @@ import {
|
||||
SyncOutlined,
|
||||
FileSyncOutlined,
|
||||
UserOutlined,
|
||||
DownloadOutlined,
|
||||
FormOutlined,
|
||||
GlobalOutlined,
|
||||
InfoCircleOutlined,
|
||||
CodeOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import type { MenuProps } from 'antd';
|
||||
|
||||
import Settings from '@/view/settings';
|
||||
import About from '@/view/about';
|
||||
import Awesome from '@/view/awesome';
|
||||
import UserCustom from '@/view/model/UserCustom';
|
||||
import SyncPrompts from '@/view/model/SyncPrompts';
|
||||
import SyncCustom from '@/view/model/SyncCustom';
|
||||
import SyncRecord from '@/view/model/SyncRecord';
|
||||
import Download from '@/view/download';
|
||||
import Scripts from '@/view/scripts';
|
||||
import ScriptsEditor from '@/view/scripts/Editor';
|
||||
import UserCustom from '@/view/prompts/UserCustom';
|
||||
import SyncPrompts from '@/view/prompts/SyncPrompts';
|
||||
import SyncCustom from '@/view/prompts/SyncCustom';
|
||||
import SyncRecord from '@/view/prompts/SyncRecord';
|
||||
import Notes from '@/view/notes';
|
||||
import Markdown from '@/view/markdown';
|
||||
import Dashboard from '@/view/dashboard';
|
||||
|
||||
export type ChatRouteMetaObject = {
|
||||
label: string;
|
||||
@ -46,14 +44,6 @@ export const routes: Array<ChatRouteObject> = [
|
||||
icon: <SettingOutlined />,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/awesome',
|
||||
element: <Awesome />,
|
||||
meta: {
|
||||
label: 'Awesome',
|
||||
icon: <GlobalOutlined />,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/notes',
|
||||
element: <Notes />,
|
||||
@ -68,9 +58,9 @@ export const routes: Array<ChatRouteObject> = [
|
||||
hideMenu: true,
|
||||
},
|
||||
{
|
||||
path: '/model',
|
||||
path: '/prompts',
|
||||
meta: {
|
||||
label: 'Language Model',
|
||||
label: 'Prompts',
|
||||
icon: <BulbOutlined />,
|
||||
},
|
||||
children: [
|
||||
@ -107,13 +97,18 @@ export const routes: Array<ChatRouteObject> = [
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/download',
|
||||
element: <Download />,
|
||||
path: '/scripts',
|
||||
element: <Scripts />,
|
||||
meta: {
|
||||
label: 'Download',
|
||||
icon: <DownloadOutlined />,
|
||||
label: 'Scripts',
|
||||
icon: <CodeOutlined />,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/scripts/:id',
|
||||
element: <ScriptsEditor />,
|
||||
hideMenu: true,
|
||||
},
|
||||
{
|
||||
path: '/about',
|
||||
element: <About />,
|
||||
@ -124,8 +119,7 @@ export const routes: Array<ChatRouteObject> = [
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
element: <Dashboard />,
|
||||
hideMenu: true,
|
||||
element: <Settings />,
|
||||
},
|
||||
];
|
||||
|
||||
|
12
src/utils.ts
vendored
12
src/utils.ts
vendored
@ -3,8 +3,8 @@ import { homeDir, join, dirname } from '@tauri-apps/api/path';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
export const APP_CONF_JSON = 'chat.conf.json';
|
||||
export const CHAT_MODEL_JSON = 'chat.model.json';
|
||||
export const CHAT_MODEL_CMD_JSON = 'chat.model.cmd.json';
|
||||
export const CHAT_PROMPT_JSON = 'chat.prompt.json';
|
||||
export const CHAT_PROMPT_CMD_JSON = 'chat.prompt.cmd.json';
|
||||
export const CHAT_DOWNLOAD_JSON = 'chat.download.json';
|
||||
export const CHAT_AWESOME_JSON = 'chat.awesome.json';
|
||||
export const CHAT_NOTES_JSON = 'chat.notes.json';
|
||||
@ -23,8 +23,12 @@ export const chatRoot = async () => {
|
||||
return join(await homeDir(), '.chatgpt');
|
||||
};
|
||||
|
||||
export const chatModelPath = async (): Promise<string> => {
|
||||
return join(await chatRoot(), CHAT_MODEL_JSON);
|
||||
export const scriptRoot = async () => {
|
||||
return join(await chatRoot(), 'scripts');
|
||||
};
|
||||
|
||||
export const chatPromptPath = async (): Promise<string> => {
|
||||
return join(await chatRoot(), CHAT_PROMPT_JSON);
|
||||
};
|
||||
|
||||
export const chatPromptsPath = async (): Promise<string> => {
|
||||
|
4
src/view/about/index.tsx
vendored
4
src/view/about/index.tsx
vendored
@ -69,10 +69,6 @@ const AboutChatGPT = () => {
|
||||
src="https://user-images.githubusercontent.com/16164244/207228025-117b5f77-c5d2-48c2-a070-774b7a1596f2.png"
|
||||
/>
|
||||
</p>
|
||||
<img
|
||||
width="250"
|
||||
src="https://user-images.githubusercontent.com/16164244/219439614-d5c3710c-e0b3-4df9-9b3c-c150ba0ba5f1.png"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
7
src/view/dashboard/index.tsx
vendored
7
src/view/dashboard/index.tsx
vendored
@ -61,8 +61,11 @@ export default function Dashboard() {
|
||||
No data
|
||||
</div>
|
||||
<div className="txt">
|
||||
Go to <a onClick={() => invoke('control_window')}>{'Control Center -> Awesome'}</a> to add
|
||||
data and make sure they are enabled.
|
||||
Go to{' '}
|
||||
<a onClick={() => invoke('control_window', { type: 'control' })}>
|
||||
{'Control Center -> Awesome'}
|
||||
</a>{' '}
|
||||
to add data and make sure they are enabled.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
16
src/view/markdown/index.scss
vendored
16
src/view/markdown/index.scss
vendored
@ -1,16 +0,0 @@
|
||||
.md-task {
|
||||
margin-bottom: 5px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
.ant-breadcrumb-link {
|
||||
padding: 3px 5px;
|
||||
transition: all 300ms ease;
|
||||
border-radius: 4px;
|
||||
&:hover {
|
||||
color: rgba(0, 0, 0, 0.88);
|
||||
background-color: rgba(0, 0, 0, 0.06);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
}
|
3
src/view/markdown/index.tsx
vendored
3
src/view/markdown/index.tsx
vendored
@ -8,7 +8,6 @@ import { fs, shell } from '@tauri-apps/api';
|
||||
import useInit from '@/hooks/useInit';
|
||||
import SplitIcon from '@/icons/SplitIcon';
|
||||
import { getPath } from '@/view/notes/config';
|
||||
import './index.scss';
|
||||
|
||||
const modeMap: any = {
|
||||
0: 'split',
|
||||
@ -41,7 +40,7 @@ export default function Markdown() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="md-task">
|
||||
<div className="editor-task">
|
||||
<Breadcrumb separator="">
|
||||
<Breadcrumb.Item onClick={() => history.go(-1)}>
|
||||
<ArrowLeftOutlined />
|
||||
|
128
src/view/model/SyncCustom/Form.tsx
vendored
128
src/view/model/SyncCustom/Form.tsx
vendored
@ -1,128 +0,0 @@
|
||||
import {
|
||||
useEffect,
|
||||
useState,
|
||||
ForwardRefRenderFunction,
|
||||
useImperativeHandle,
|
||||
forwardRef,
|
||||
} from 'react';
|
||||
import { Form, Input, Select, Tooltip } from 'antd';
|
||||
import { v4 } from 'uuid';
|
||||
import type { FormProps } from 'antd';
|
||||
|
||||
import { DISABLE_AUTO_COMPLETE, chatRoot } from '@/utils';
|
||||
import useInit from '@/hooks/useInit';
|
||||
|
||||
interface SyncFormProps {
|
||||
record?: Record<string | symbol, any> | null;
|
||||
type: string;
|
||||
}
|
||||
|
||||
const initFormValue = {
|
||||
act: '',
|
||||
enable: true,
|
||||
tags: [],
|
||||
prompt: '',
|
||||
};
|
||||
|
||||
const SyncForm: ForwardRefRenderFunction<FormProps, SyncFormProps> = ({ record, type }, ref) => {
|
||||
const isDisabled = type === 'edit';
|
||||
const [form] = Form.useForm();
|
||||
useImperativeHandle(ref, () => ({ form }));
|
||||
const [root, setRoot] = useState('');
|
||||
|
||||
useInit(async () => {
|
||||
setRoot(await chatRoot());
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (record) {
|
||||
form.setFieldsValue(record);
|
||||
}
|
||||
}, [record]);
|
||||
|
||||
const pathOptions = (
|
||||
<Form.Item noStyle name="protocol" initialValue="https">
|
||||
<Select disabled={isDisabled}>
|
||||
<Select.Option value="local">{root}</Select.Option>
|
||||
<Select.Option value="http">http://</Select.Option>
|
||||
<Select.Option value="https">https://</Select.Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
);
|
||||
const extOptions = (
|
||||
<Form.Item noStyle name="ext" initialValue="json">
|
||||
<Select disabled={isDisabled}>
|
||||
<Select.Option value="csv">.csv</Select.Option>
|
||||
<Select.Option value="json">.json</Select.Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
);
|
||||
|
||||
const jsonTip = (
|
||||
<Tooltip
|
||||
title={
|
||||
<pre>
|
||||
{JSON.stringify(
|
||||
[
|
||||
{ cmd: '', act: '', prompt: '' },
|
||||
{ cmd: '', act: '', prompt: '' },
|
||||
],
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</pre>
|
||||
}
|
||||
>
|
||||
<a>JSON</a>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
const csvTip = (
|
||||
<Tooltip
|
||||
title={
|
||||
<pre>{`"cmd","act","prompt"
|
||||
"cmd","act","prompt"
|
||||
"cmd","act","prompt"
|
||||
"cmd","act","prompt"`}</pre>
|
||||
}
|
||||
>
|
||||
<a>CSV</a>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form form={form} labelCol={{ span: 4 }} initialValues={initFormValue}>
|
||||
<Form.Item
|
||||
label="Name"
|
||||
name="name"
|
||||
rules={[{ required: true, message: 'Please enter a name!' }]}
|
||||
>
|
||||
<Input placeholder="Please enter a name" {...DISABLE_AUTO_COMPLETE} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="PATH"
|
||||
name="path"
|
||||
rules={[{ required: true, message: 'Please enter the path!' }]}
|
||||
>
|
||||
<Input
|
||||
placeholder="YOUR_PATH"
|
||||
addonBefore={pathOptions}
|
||||
addonAfter={extOptions}
|
||||
{...DISABLE_AUTO_COMPLETE}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item style={{ display: 'none' }} name="id" initialValue={v4().replace(/-/g, '')}>
|
||||
<input />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<div className="tip">
|
||||
<p>
|
||||
The file supports only {csvTip} and {jsonTip} formats.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default forwardRef(SyncForm);
|
155
src/view/model/SyncCustom/index.tsx
vendored
155
src/view/model/SyncCustom/index.tsx
vendored
@ -1,155 +0,0 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { Table, Modal, Button, message } from 'antd';
|
||||
import { invoke, path, fs } from '@tauri-apps/api';
|
||||
|
||||
import useData from '@/hooks/useData';
|
||||
import useColumns from '@/hooks/useColumns';
|
||||
import { TABLE_PAGINATION } from '@/hooks/useTable';
|
||||
import useChatModel, { useCacheModel } from '@/hooks/useChatModel';
|
||||
import { CHAT_MODEL_JSON, chatRoot, readJSON, genCmd } from '@/utils';
|
||||
import { syncColumns, getPath } from './config';
|
||||
import SyncForm from './Form';
|
||||
|
||||
const fmtData = (data: Record<string, any>[] = []) =>
|
||||
(Array.isArray(data) ? data : []).map((i) => ({
|
||||
...i,
|
||||
cmd: i.cmd ? i.cmd : genCmd(i.act),
|
||||
tags: ['user-sync'],
|
||||
enable: true,
|
||||
}));
|
||||
|
||||
export default function SyncCustom() {
|
||||
const [isVisible, setVisible] = useState(false);
|
||||
const { modelData, modelSet } = useChatModel('sync_custom', CHAT_MODEL_JSON);
|
||||
const { modelCacheCmd, modelCacheSet } = useCacheModel();
|
||||
const { opData, opInit, opAdd, opRemove, opReplace, opSafeKey } = useData([]);
|
||||
const { columns, ...opInfo } = useColumns(syncColumns());
|
||||
const formRef = useRef<any>(null);
|
||||
|
||||
const hide = () => {
|
||||
setVisible(false);
|
||||
opInfo.resetRecord();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (modelData.length <= 0) return;
|
||||
opInit(modelData);
|
||||
}, [modelData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!opInfo.opType) return;
|
||||
if (opInfo.opType === 'sync') {
|
||||
const filename = `${opInfo?.opRecord?.id}.json`;
|
||||
handleSync(filename).then((isOk: boolean) => {
|
||||
opInfo.resetRecord();
|
||||
if (!isOk) return;
|
||||
const data = opReplace(opInfo?.opRecord?.[opSafeKey], {
|
||||
...opInfo?.opRecord,
|
||||
last_updated: Date.now(),
|
||||
});
|
||||
modelSet(data);
|
||||
opInfo.resetRecord();
|
||||
});
|
||||
}
|
||||
if (['edit', 'new'].includes(opInfo.opType)) {
|
||||
setVisible(true);
|
||||
}
|
||||
if (['delete'].includes(opInfo.opType)) {
|
||||
(async () => {
|
||||
try {
|
||||
const file = await path.join(
|
||||
await chatRoot(),
|
||||
'cache_model',
|
||||
`${opInfo?.opRecord?.id}.json`,
|
||||
);
|
||||
await fs.removeFile(file);
|
||||
} catch (e) {}
|
||||
const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
|
||||
modelSet(data);
|
||||
opInfo.resetRecord();
|
||||
modelCacheCmd();
|
||||
})();
|
||||
}
|
||||
}, [opInfo.opType, formRef]);
|
||||
|
||||
const handleSync = async (filename: string) => {
|
||||
const record = opInfo?.opRecord;
|
||||
const isJson = /json$/.test(record?.ext);
|
||||
const file = await path.join(await chatRoot(), 'cache_model', filename);
|
||||
const filePath = await getPath(record);
|
||||
|
||||
// https or http
|
||||
if (/^http/.test(record?.protocol)) {
|
||||
const data = await invoke('sync_user_prompts', { url: filePath, dataType: record?.ext });
|
||||
if (data) {
|
||||
await modelCacheSet(data as [], file);
|
||||
await modelCacheCmd();
|
||||
message.success('ChatGPT Prompts data has been synchronized!');
|
||||
return true;
|
||||
} else {
|
||||
message.error('ChatGPT Prompts data sync failed, please try again!');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// local
|
||||
if (isJson) {
|
||||
// parse json
|
||||
const data = await readJSON(filePath, { isRoot: true });
|
||||
await modelCacheSet(fmtData(data), file);
|
||||
} else {
|
||||
// parse csv
|
||||
const data = await fs.readTextFile(filePath);
|
||||
const list: Record<string, string>[] = await invoke('parse_prompt', { data });
|
||||
await modelCacheSet(fmtData(list), file);
|
||||
}
|
||||
await modelCacheCmd();
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleOk = () => {
|
||||
formRef.current?.form?.validateFields().then((vals: Record<string, any>) => {
|
||||
if (opInfo.opType === 'new') {
|
||||
const data = opAdd(vals);
|
||||
modelSet(data);
|
||||
message.success('Data added successfully');
|
||||
}
|
||||
if (opInfo.opType === 'edit') {
|
||||
const data = opReplace(opInfo?.opRecord?.[opSafeKey], vals);
|
||||
modelSet(data);
|
||||
message.success('Data updated successfully');
|
||||
}
|
||||
hide();
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button
|
||||
style={{ marginBottom: 10 }}
|
||||
className="chat-add-btn"
|
||||
type="primary"
|
||||
onClick={opInfo.opNew}
|
||||
>
|
||||
Add PATH
|
||||
</Button>
|
||||
<Table
|
||||
key="id"
|
||||
rowKey="name"
|
||||
columns={columns}
|
||||
scroll={{ x: 800 }}
|
||||
dataSource={opData}
|
||||
pagination={TABLE_PAGINATION}
|
||||
/>
|
||||
<Modal
|
||||
open={isVisible}
|
||||
onCancel={hide}
|
||||
title="Sync PATH"
|
||||
onOk={handleOk}
|
||||
destroyOnClose
|
||||
maskClosable={false}
|
||||
>
|
||||
<SyncForm ref={formRef} record={opInfo?.opRecord} type={opInfo.opType} />
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
2
src/view/notes/config.tsx
vendored
2
src/view/notes/config.tsx
vendored
@ -67,5 +67,5 @@ const RenderPath = ({ row }: any) => {
|
||||
};
|
||||
|
||||
export const getPath = async (row: any) => {
|
||||
return (await path.join(await chatRoot(), 'notes', row.id)) + `.${row.ext}`;
|
||||
return await path.join(await chatRoot(), 'notes', `${row.id}.md`);
|
||||
};
|
||||
|
166
src/view/prompts/SyncCustom/Form.tsx
vendored
Normal file
166
src/view/prompts/SyncCustom/Form.tsx
vendored
Normal file
@ -0,0 +1,166 @@
|
||||
import {
|
||||
useEffect,
|
||||
useState,
|
||||
ForwardRefRenderFunction,
|
||||
useImperativeHandle,
|
||||
forwardRef,
|
||||
} from 'react';
|
||||
import { Form, Input, Radio, Upload, Tooltip, Button, message } from 'antd';
|
||||
import { v4 } from 'uuid';
|
||||
import { UploadOutlined } from '@ant-design/icons';
|
||||
import type { FormProps, RadioChangeEvent, UploadProps, UploadFile } from 'antd';
|
||||
|
||||
import { DISABLE_AUTO_COMPLETE, chatRoot } from '@/utils';
|
||||
|
||||
interface SyncFormProps {
|
||||
record?: Record<string | symbol, any> | null;
|
||||
}
|
||||
|
||||
const initFormValue = {
|
||||
name: '',
|
||||
url: '',
|
||||
file: null,
|
||||
protocol: 'https',
|
||||
};
|
||||
|
||||
const SyncForm: ForwardRefRenderFunction<FormProps, SyncFormProps> = ({ record }, ref) => {
|
||||
const [form] = Form.useForm();
|
||||
useImperativeHandle(ref, () => ({ form }));
|
||||
const [protocol, setProtocol] = useState('https');
|
||||
const [fileList, setFileList] = useState<UploadFile[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (record) {
|
||||
form.setFieldsValue(record);
|
||||
}
|
||||
}, [record]);
|
||||
|
||||
const jsonTip = (
|
||||
<Tooltip
|
||||
title={
|
||||
<pre>
|
||||
{JSON.stringify(
|
||||
[
|
||||
{ cmd: '', act: '', prompt: '' },
|
||||
{ cmd: '', act: '', prompt: '' },
|
||||
],
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</pre>
|
||||
}
|
||||
>
|
||||
<a>.json</a>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
const csvTip = (
|
||||
<Tooltip
|
||||
title={
|
||||
<pre>{`"cmd","act","prompt"
|
||||
"a","aaa","aaa aaa"
|
||||
"b","bbb","bbb bbb"
|
||||
"c","ccc","ccc ccc"`}</pre>
|
||||
}
|
||||
>
|
||||
<a>.csv</a>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
const handleType = (e: RadioChangeEvent) => {
|
||||
setProtocol(e.target.value);
|
||||
};
|
||||
|
||||
const uploadOptions: UploadProps = {
|
||||
onRemove: () => {
|
||||
setFileList([]);
|
||||
},
|
||||
customRequest: () => {},
|
||||
beforeUpload: (file) => {
|
||||
const isCSV = /.csv$/.test(file.name);
|
||||
const isJSON = /.json$/.test(file.name);
|
||||
const isOk = isCSV || isJSON;
|
||||
if (!isOk) {
|
||||
message.error('You can only upload .json or .csv file!');
|
||||
} else {
|
||||
setFileList([file]);
|
||||
}
|
||||
return isOk || Upload.LIST_IGNORE;
|
||||
},
|
||||
maxCount: 1,
|
||||
fileList,
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form form={form} labelCol={{ span: 4 }} initialValues={initFormValue}>
|
||||
<Form.Item
|
||||
label="Name"
|
||||
name="name"
|
||||
rules={[{ required: true, message: 'Please enter a name!' }]}
|
||||
>
|
||||
<Input placeholder="Please enter a name" {...DISABLE_AUTO_COMPLETE} />
|
||||
</Form.Item>
|
||||
<Form.Item label="Protocol" name="protocol" rules={[{ required: true }]}>
|
||||
<Radio.Group onChange={handleType} value={protocol}>
|
||||
<Radio value="https">https</Radio>
|
||||
<Radio value="http">http</Radio>
|
||||
<Radio value="local">local</Radio>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
{['http', 'https'].includes(protocol) && (
|
||||
<div style={{ height: 180 }}>
|
||||
<Form.Item
|
||||
label="URL"
|
||||
name="url"
|
||||
rules={[
|
||||
{ required: true, message: 'Please enter the URL!' },
|
||||
({ getFieldValue }) => ({
|
||||
validator(_, value) {
|
||||
if (!value || /\.json$|\.csv$/.test(getFieldValue('url'))) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return Promise.reject(
|
||||
new Error('The file supports only .csv and .json formats'),
|
||||
);
|
||||
},
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<Input
|
||||
placeholder="your_path/file_name.ext"
|
||||
addonBefore={`${protocol}://`}
|
||||
{...DISABLE_AUTO_COMPLETE}
|
||||
/>
|
||||
</Form.Item>
|
||||
<div style={{ marginLeft: 80, color: '#888' }}>
|
||||
<p>
|
||||
<b>.ext</b>: only {csvTip} or {jsonTip} file formats are supported.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{protocol === 'local' && (
|
||||
<Form.Item
|
||||
name="file"
|
||||
label="File"
|
||||
rules={[{ required: true, message: 'Please select a file!' }]}
|
||||
style={{ height: 168 }}
|
||||
>
|
||||
<Upload.Dragger {...uploadOptions}>
|
||||
<Button icon={<UploadOutlined />}>Click to Upload</Button>
|
||||
<p className="ant-upload-hint">
|
||||
Only {csvTip} or {jsonTip} file formats are supported.
|
||||
</p>
|
||||
</Upload.Dragger>
|
||||
</Form.Item>
|
||||
)}
|
||||
<Form.Item style={{ display: 'none' }} name="id" initialValue={v4().replace(/-/g, '')}>
|
||||
<input />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default forwardRef(SyncForm);
|
@ -4,6 +4,7 @@ import { HistoryOutlined } from '@ant-design/icons';
|
||||
import { shell, path } from '@tauri-apps/api';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
import { EditRow } from '@/hooks/useColumns';
|
||||
import useInit from '@/hooks/useInit';
|
||||
import { chatRoot, fmtDate } from '@/utils';
|
||||
|
||||
@ -13,6 +14,9 @@ export const syncColumns = () => [
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 100,
|
||||
render: (_: string, row: any, actions: any) => (
|
||||
<EditRow rowKey="name" row={row} actions={actions} />
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Protocol',
|
||||
@ -47,21 +51,22 @@ export const syncColumns = () => [
|
||||
render: (_: any, row: any, actions: any) => {
|
||||
return (
|
||||
<Space>
|
||||
<Popconfirm
|
||||
overlayStyle={{ width: 250 }}
|
||||
title="Sync will overwrite the previous data, confirm to sync?"
|
||||
onConfirm={() => actions.setRecord(row, 'sync')}
|
||||
okText="Yes"
|
||||
cancelText="No"
|
||||
>
|
||||
<a>Sync</a>
|
||||
</Popconfirm>
|
||||
{row.protocol !== 'local' && (
|
||||
<Popconfirm
|
||||
overlayStyle={{ width: 250 }}
|
||||
title="Sync will overwrite the previous data, confirm to sync?"
|
||||
onConfirm={() => actions.setRecord(row, 'sync')}
|
||||
okText="Yes"
|
||||
cancelText="No"
|
||||
>
|
||||
<a>Sync</a>
|
||||
</Popconfirm>
|
||||
)}
|
||||
{row.last_updated && (
|
||||
<Link to={`${row.id}`} state={row}>
|
||||
View
|
||||
</Link>
|
||||
)}
|
||||
<a onClick={() => actions.setRecord(row, 'edit')}>Edit</a>
|
||||
<Popconfirm
|
||||
title="Are you sure to delete this path?"
|
||||
onConfirm={() => actions.setRecord(row, 'delete')}
|
||||
@ -86,8 +91,8 @@ const RenderPath = ({ row }: any) => {
|
||||
|
||||
export const getPath = async (row: any) => {
|
||||
if (!/^http/.test(row.protocol)) {
|
||||
return (await path.join(await chatRoot(), row.path)) + `.${row.ext}`;
|
||||
return await path.join(await chatRoot(), 'cache_prompts', `${row.id}.json`);
|
||||
} else {
|
||||
return `${row.protocol}://${row.path}.${row.ext}`;
|
||||
return `${row.protocol}://${row.url}`;
|
||||
}
|
||||
};
|
228
src/view/prompts/SyncCustom/index.tsx
vendored
Normal file
228
src/view/prompts/SyncCustom/index.tsx
vendored
Normal file
@ -0,0 +1,228 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { Table, Modal, Button, message } from 'antd';
|
||||
import { invoke, path, fs, shell } from '@tauri-apps/api';
|
||||
|
||||
import useData from '@/hooks/useData';
|
||||
import useInit from '@/hooks/useInit';
|
||||
import useColumns from '@/hooks/useColumns';
|
||||
import { TABLE_PAGINATION } from '@/hooks/useTable';
|
||||
import useChatPrompt, { useCachePrompt } from '@/hooks/useChatPrompt';
|
||||
import { CHAT_PROMPT_JSON, chatRoot, genCmd } from '@/utils';
|
||||
import { syncColumns, getPath } from './config';
|
||||
import SyncForm from './Form';
|
||||
|
||||
const fmtData = (data: Record<string, any>[] = []) =>
|
||||
(Array.isArray(data) ? data : []).map((i) => ({
|
||||
...i,
|
||||
cmd: i.cmd ? i.cmd : genCmd(i.act),
|
||||
tags: ['user-sync'],
|
||||
enable: true,
|
||||
}));
|
||||
|
||||
export default function SyncCustom() {
|
||||
const [logPath, setLogPath] = useState('');
|
||||
const [isVisible, setVisible] = useState(false);
|
||||
const { promptData, promptSet, promptUpdate } = useChatPrompt('sync_custom', CHAT_PROMPT_JSON);
|
||||
const { promptCacheCmd, promptCacheSet } = useCachePrompt();
|
||||
const { opData, opInit, opAdd, opRemove, opReplace, opSafeKey } = useData([]);
|
||||
const { columns, ...opInfo } = useColumns(syncColumns());
|
||||
const formRef = useRef<any>(null);
|
||||
|
||||
const hide = () => {
|
||||
setVisible(false);
|
||||
opInfo.resetRecord();
|
||||
};
|
||||
|
||||
useInit(async () => {
|
||||
const filePath = await path.join(await chatRoot(), 'chatgpt.log');
|
||||
setLogPath(filePath);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (promptData.length <= 0) return;
|
||||
opInit(promptData);
|
||||
}, [promptData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!opInfo.opType) return;
|
||||
(async () => {
|
||||
if (opInfo.opType === 'sync') {
|
||||
handleSync();
|
||||
}
|
||||
if (opInfo.opType === 'rowedit') {
|
||||
await promptUpdate(opInfo?.opRecord?.id, 'name', opInfo?.opRecord?.name);
|
||||
message.success('Name has been changed');
|
||||
opInfo.resetRecord();
|
||||
}
|
||||
if (['edit', 'new'].includes(opInfo.opType)) {
|
||||
setVisible(true);
|
||||
}
|
||||
if (['delete'].includes(opInfo.opType)) {
|
||||
try {
|
||||
const file = await path.join(
|
||||
await chatRoot(),
|
||||
'cache_prompts',
|
||||
`${opInfo?.opRecord?.id}.json`,
|
||||
);
|
||||
await fs.removeFile(file);
|
||||
} catch (e) {}
|
||||
const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
|
||||
promptSet(data);
|
||||
opInfo.resetRecord();
|
||||
promptCacheCmd();
|
||||
}
|
||||
})();
|
||||
}, [opInfo.opType, formRef]);
|
||||
|
||||
const handleSync = async () => {
|
||||
const filename = `${opInfo?.opRecord?.id}.json`;
|
||||
const record = opInfo?.opRecord;
|
||||
|
||||
// https or http
|
||||
if (/^http/.test(record?.protocol)) {
|
||||
const isJson = /json$/.test(record?.url);
|
||||
const file = await path.join(await chatRoot(), 'cache_prompts', filename);
|
||||
const filePath = await getPath(record);
|
||||
|
||||
const data = await invoke('sync_user_prompts', {
|
||||
url: filePath,
|
||||
dataType: isJson ? 'json' : 'csv',
|
||||
});
|
||||
if (data) {
|
||||
await promptCacheSet(data as [], file);
|
||||
await promptCacheCmd();
|
||||
message.success('Prompts successfully synchronized');
|
||||
const data2 = opReplace(opInfo?.opRecord?.[opSafeKey], {
|
||||
...opInfo?.opRecord,
|
||||
last_updated: Date.now(),
|
||||
});
|
||||
promptSet(data2);
|
||||
opInfo.resetRecord();
|
||||
} else {
|
||||
message.error(
|
||||
'Prompts synchronization failed, please try again (click to "View Log" for more details)',
|
||||
);
|
||||
}
|
||||
}
|
||||
opInfo.resetRecord();
|
||||
};
|
||||
|
||||
const parseLocal = async (file: File): Promise<[boolean, any[] | null]> => {
|
||||
if (file) {
|
||||
const fileData = await readFile(file);
|
||||
const isJSON = /json$/.test(file.name);
|
||||
|
||||
if (isJSON) {
|
||||
// parse json
|
||||
try {
|
||||
const jsonData = JSON.parse(fileData);
|
||||
return [true, jsonData];
|
||||
} catch (e) {
|
||||
message.error('JSON parse error, please check your file');
|
||||
return [false, null];
|
||||
}
|
||||
} else {
|
||||
// parse csv
|
||||
const list: Record<string, string>[] | null = await invoke('parse_prompt', {
|
||||
data: fileData,
|
||||
});
|
||||
if (!list) {
|
||||
message.error('CSV parse error, please check your file');
|
||||
return [false, null];
|
||||
} else {
|
||||
return [true, list];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
message.error('File parsing exception');
|
||||
return [false, null];
|
||||
};
|
||||
|
||||
const handleOk = () => {
|
||||
formRef.current?.form?.validateFields().then(async (vals: Record<string, any>) => {
|
||||
if (opInfo.opType === 'new') {
|
||||
if (vals.protocol !== 'local') {
|
||||
// http or https
|
||||
delete vals.file;
|
||||
const data = opAdd(vals);
|
||||
await promptSet(data);
|
||||
hide();
|
||||
opInfo.setRecord(data[0], 'sync');
|
||||
message.success('Data added successfully');
|
||||
} else {
|
||||
const file = vals?.file?.file?.originFileObj;
|
||||
const data = opAdd(vals);
|
||||
const parseData = await parseLocal(file);
|
||||
if (parseData[0]) {
|
||||
const id = data[0].id;
|
||||
const filePath = await path.join(await chatRoot(), 'cache_prompts', `${id}.json`);
|
||||
data[0].last_updated = Date.now();
|
||||
await promptSet(data);
|
||||
await promptCacheSet(fmtData(parseData[1] as []), filePath);
|
||||
await promptCacheCmd();
|
||||
hide();
|
||||
message.success('Data added successfully');
|
||||
} else {
|
||||
opRemove(data?.[0]?.[opSafeKey]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (opInfo.opType === 'edit') {
|
||||
delete vals.file;
|
||||
const data = opReplace(opInfo?.opRecord?.[opSafeKey], vals);
|
||||
promptSet(data);
|
||||
hide();
|
||||
message.success('Data updated successfully');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleLog = () => {
|
||||
shell.open(logPath);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button
|
||||
style={{ marginBottom: 10 }}
|
||||
className="chat-add-btn"
|
||||
type="primary"
|
||||
onClick={opInfo.opNew}
|
||||
>
|
||||
Add Prompt
|
||||
</Button>
|
||||
<Button style={{ marginBottom: 10 }} onClick={handleLog}>
|
||||
View Log
|
||||
</Button>
|
||||
<Table
|
||||
key="id"
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
scroll={{ x: 800 }}
|
||||
dataSource={opData}
|
||||
pagination={TABLE_PAGINATION}
|
||||
/>
|
||||
<Modal
|
||||
open={isVisible}
|
||||
onCancel={hide}
|
||||
title="Add Prompt"
|
||||
onOk={handleOk}
|
||||
destroyOnClose
|
||||
maskClosable={false}
|
||||
>
|
||||
<SyncForm ref={formRef} record={opInfo?.opRecord} />
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function readFile(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let reader = new FileReader();
|
||||
reader.onload = (e: any) => resolve(e.target.result);
|
||||
reader.onerror = (e: any) => reject(e.target.error);
|
||||
reader.readAsText(file);
|
||||
});
|
||||
}
|
@ -7,7 +7,6 @@ export const syncColumns = () => [
|
||||
title: '/{cmd}',
|
||||
dataIndex: 'cmd',
|
||||
fixed: 'left',
|
||||
// width: 120,
|
||||
key: 'cmd',
|
||||
render: (_: string, row: Record<string, string>) => (
|
||||
<Tag color="#2a2a2a">/{genCmd(row.act)}</Tag>
|
||||
@ -17,20 +16,17 @@ export const syncColumns = () => [
|
||||
title: 'Act',
|
||||
dataIndex: 'act',
|
||||
key: 'act',
|
||||
// width: 200,
|
||||
},
|
||||
{
|
||||
title: 'Tags',
|
||||
dataIndex: 'tags',
|
||||
key: 'tags',
|
||||
// width: 150,
|
||||
render: () => <Tag>chatgpt-prompts</Tag>,
|
||||
render: () => <Tag>built-in</Tag>,
|
||||
},
|
||||
{
|
||||
title: 'Enable',
|
||||
dataIndex: 'enable',
|
||||
key: 'enable',
|
||||
// width: 80,
|
||||
render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => (
|
||||
<Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} />
|
||||
),
|
||||
@ -40,7 +36,6 @@ export const syncColumns = () => [
|
||||
title: 'Prompt',
|
||||
dataIndex: 'prompt',
|
||||
key: 'prompt',
|
||||
// width: 300,
|
||||
render: (v: string) => <span className="chat-prompts-val">{v}</span>,
|
||||
},
|
||||
];
|
@ -6,38 +6,39 @@ import useInit from '@/hooks/useInit';
|
||||
import useData from '@/hooks/useData';
|
||||
import useColumns from '@/hooks/useColumns';
|
||||
import FilePath from '@/components/FilePath';
|
||||
import useChatModel, { useCacheModel } from '@/hooks/useChatModel';
|
||||
import useChatPrompt, { useCachePrompt } from '@/hooks/useChatPrompt';
|
||||
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
|
||||
import { fmtDate, chatRoot } from '@/utils';
|
||||
import { syncColumns } from './config';
|
||||
import './index.scss';
|
||||
|
||||
const promptsURL = 'https://github.com/f/awesome-chatgpt-prompts/blob/main/prompts.csv';
|
||||
// const promptsURL = 'https://github.com/f/awesome-chatgpt-prompts/blob/main/prompts.csv';
|
||||
const promptsURL = 'https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv';
|
||||
|
||||
export default function SyncPrompts() {
|
||||
const { rowSelection, selectedRowIDs } = useTableRowSelection();
|
||||
const [jsonPath, setJsonPath] = useState('');
|
||||
const { modelJson, modelSet } = useChatModel('sync_prompts');
|
||||
const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath);
|
||||
const { promptJson, promptSet } = useChatPrompt('sync_prompts');
|
||||
const { promptCacheJson, promptCacheSet } = useCachePrompt(jsonPath);
|
||||
const { opData, opInit, opReplace, opReplaceItems, opSafeKey } = useData([]);
|
||||
const { columns, ...opInfo } = useColumns(syncColumns());
|
||||
const lastUpdated = modelJson?.sync_prompts?.last_updated;
|
||||
const lastUpdated = promptJson?.sync_prompts?.last_updated;
|
||||
const selectedItems = rowSelection.selectedRowKeys || [];
|
||||
|
||||
useInit(async () => {
|
||||
setJsonPath(await path.join(await chatRoot(), 'cache_model', 'chatgpt_prompts.json'));
|
||||
setJsonPath(await path.join(await chatRoot(), 'cache_prompts', 'chatgpt_prompts.json'));
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (modelCacheJson.length <= 0) return;
|
||||
opInit(modelCacheJson);
|
||||
}, [modelCacheJson.length]);
|
||||
if (promptCacheJson.length <= 0) return;
|
||||
opInit(promptCacheJson);
|
||||
}, [promptCacheJson.length]);
|
||||
|
||||
const handleSync = async () => {
|
||||
const data = await invoke('sync_prompts', { time: Date.now() });
|
||||
if (data) {
|
||||
opInit(data as any[]);
|
||||
modelSet({
|
||||
promptSet({
|
||||
id: 'chatgpt_prompts',
|
||||
last_updated: Date.now(),
|
||||
});
|
||||
@ -47,13 +48,13 @@ export default function SyncPrompts() {
|
||||
useEffect(() => {
|
||||
if (opInfo.opType === 'enable') {
|
||||
const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
|
||||
modelCacheSet(data);
|
||||
promptCacheSet(data);
|
||||
}
|
||||
}, [opInfo.opTime]);
|
||||
|
||||
const handleEnable = (isEnable: boolean) => {
|
||||
const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
|
||||
modelCacheSet(data);
|
||||
promptCacheSet(data);
|
||||
};
|
||||
|
||||
return (
|
||||
@ -83,8 +84,8 @@ export default function SyncPrompts() {
|
||||
</div>
|
||||
<div className="chat-table-tip">
|
||||
<div className="chat-sync-path">
|
||||
<FilePath url={promptsURL} content="f/awesome-chatgpt-prompts/prompts.csv" />
|
||||
<FilePath label="CACHE" paths="cache_model/chatgpt_prompts.json" />
|
||||
<FilePath label="URL" url={promptsURL} content="f/awesome-chatgpt-prompts/prompts.csv" />
|
||||
<FilePath label="CACHE" paths="cache_prompts/chatgpt_prompts.json" />
|
||||
</div>
|
||||
{lastUpdated && (
|
||||
<span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>
|
@ -7,7 +7,6 @@ export const syncColumns = () => [
|
||||
title: '/{cmd}',
|
||||
dataIndex: 'cmd',
|
||||
fixed: 'left',
|
||||
// width: 120,
|
||||
key: 'cmd',
|
||||
render: (_: string, row: Record<string, string>) => (
|
||||
<Tag color="#2a2a2a">/{row.cmd ? row.cmd : genCmd(row.act)}</Tag>
|
||||
@ -17,13 +16,11 @@ export const syncColumns = () => [
|
||||
title: 'Act',
|
||||
dataIndex: 'act',
|
||||
key: 'act',
|
||||
// width: 200,
|
||||
},
|
||||
{
|
||||
title: 'Tags',
|
||||
dataIndex: 'tags',
|
||||
key: 'tags',
|
||||
// width: 150,
|
||||
render: (v: string[]) => (
|
||||
<span className="chat-prompts-tags">
|
||||
{v?.map((i) => (
|
||||
@ -36,7 +33,6 @@ export const syncColumns = () => [
|
||||
title: 'Enable',
|
||||
dataIndex: 'enable',
|
||||
key: 'enable',
|
||||
// width: 80,
|
||||
render: (v: boolean = false, row: Record<string, any>, action: Record<string, any>) => (
|
||||
<Switch checked={v} onChange={(v) => action.setRecord({ ...row, enable: v }, 'enable')} />
|
||||
),
|
||||
@ -46,7 +42,6 @@ export const syncColumns = () => [
|
||||
title: 'Prompt',
|
||||
dataIndex: 'prompt',
|
||||
key: 'prompt',
|
||||
// width: 300,
|
||||
render: (v: string) => <span className="chat-prompts-val">{v}</span>,
|
||||
},
|
||||
];
|
@ -7,9 +7,9 @@ import { path } from '@tauri-apps/api';
|
||||
import useData from '@/hooks/useData';
|
||||
import useColumns from '@/hooks/useColumns';
|
||||
import FilePath from '@/components/FilePath';
|
||||
import { useCacheModel } from '@/hooks/useChatModel';
|
||||
import { useCachePrompt } from '@/hooks/useChatPrompt';
|
||||
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
|
||||
import { getPath } from '@/view/model/SyncCustom/config';
|
||||
import { getPath } from '@/view/prompts/SyncCustom/config';
|
||||
import { fmtDate, chatRoot } from '@/utils';
|
||||
import { syncColumns } from './config';
|
||||
import useInit from '@/hooks/useInit';
|
||||
@ -21,32 +21,36 @@ export default function SyncRecord() {
|
||||
const state = location?.state;
|
||||
|
||||
const { rowSelection, selectedRowIDs } = useTableRowSelection();
|
||||
const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath);
|
||||
const { promptCacheJson, promptCacheSet } = useCachePrompt(jsonPath);
|
||||
const { opData, opInit, opReplace, opReplaceItems, opSafeKey } = useData([]);
|
||||
const { columns, ...opInfo } = useColumns(syncColumns());
|
||||
|
||||
const selectedItems = rowSelection.selectedRowKeys || [];
|
||||
|
||||
useInit(async () => {
|
||||
setFilePath(await getPath(state));
|
||||
setJsonPath(await path.join(await chatRoot(), 'cache_model', `${state?.id}.json`));
|
||||
if (state.protocol === 'local') {
|
||||
setFilePath('');
|
||||
} else {
|
||||
setFilePath(await getPath(state));
|
||||
}
|
||||
setJsonPath(await path.join(await chatRoot(), 'cache_prompts', `${state?.id}.json`));
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (modelCacheJson.length <= 0) return;
|
||||
opInit(modelCacheJson);
|
||||
}, [modelCacheJson.length]);
|
||||
if (promptCacheJson.length <= 0) return;
|
||||
opInit(promptCacheJson);
|
||||
}, [promptCacheJson.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (opInfo.opType === 'enable') {
|
||||
const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
|
||||
modelCacheSet(data);
|
||||
promptCacheSet(data);
|
||||
}
|
||||
}, [opInfo.opTime]);
|
||||
|
||||
const handleEnable = (isEnable: boolean) => {
|
||||
const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
|
||||
modelCacheSet(data);
|
||||
promptCacheSet(data);
|
||||
};
|
||||
|
||||
return (
|
||||
@ -69,8 +73,8 @@ export default function SyncRecord() {
|
||||
</div>
|
||||
<div className="chat-table-tip">
|
||||
<div className="chat-sync-path">
|
||||
<FilePath url={filePath} />
|
||||
<FilePath label="CACHE" paths={`cache_model/${state?.id}.json`} />
|
||||
{filePath && <FilePath label="URL" url={filePath} />}
|
||||
<FilePath label="CACHE" paths={`cache_prompts/${state?.id}.json`} />
|
||||
</div>
|
||||
{state?.last_updated && (
|
||||
<span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>
|
@ -45,12 +45,6 @@ const UserCustomForm: ForwardRefRenderFunction<FormProps, UserCustomFormProps> =
|
||||
>
|
||||
<Input placeholder="Please enter the Act" {...DISABLE_AUTO_COMPLETE} />
|
||||
</Form.Item>
|
||||
<Form.Item label="Tags" name="tags">
|
||||
<Tags value={record?.tags} />
|
||||
</Form.Item>
|
||||
<Form.Item label="Enable" name="enable" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="Prompt"
|
||||
name="prompt"
|
||||
@ -58,6 +52,12 @@ const UserCustomForm: ForwardRefRenderFunction<FormProps, UserCustomFormProps> =
|
||||
>
|
||||
<Input.TextArea rows={4} placeholder="Please enter a prompt" {...DISABLE_AUTO_COMPLETE} />
|
||||
</Form.Item>
|
||||
<Form.Item label="Enable" name="enable" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
<Form.Item label="Tags" name="tags">
|
||||
<Tags value={record?.tags} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
);
|
||||
};
|
@ -1,6 +1,6 @@
|
||||
import { Tag, Switch, Space, Popconfirm, Table } from 'antd';
|
||||
|
||||
export const modelColumns = () => [
|
||||
export const promptColumns = () => [
|
||||
{
|
||||
title: '/{cmd}',
|
||||
dataIndex: 'cmd',
|
||||
@ -54,7 +54,7 @@ export const modelColumns = () => [
|
||||
<Space size="middle">
|
||||
<a onClick={() => actions.setRecord(row, 'edit')}>Edit</a>
|
||||
<Popconfirm
|
||||
title="Are you sure to delete this model?"
|
||||
title="Are you sure to delete this prompt?"
|
||||
onConfirm={() => actions.setRecord(row, 'delete')}
|
||||
okText="Yes"
|
||||
cancelText="No"
|
@ -6,32 +6,32 @@ import useInit from '@/hooks/useInit';
|
||||
import useData from '@/hooks/useData';
|
||||
import useColumns from '@/hooks/useColumns';
|
||||
import FilePath from '@/components/FilePath';
|
||||
import useChatModel, { useCacheModel } from '@/hooks/useChatModel';
|
||||
import useChatPrompt, { useCachePrompt } from '@/hooks/useChatPrompt';
|
||||
import { useTableRowSelection, TABLE_PAGINATION } from '@/hooks/useTable';
|
||||
import { chatRoot, fmtDate } from '@/utils';
|
||||
import { modelColumns } from './config';
|
||||
import { promptColumns } from './config';
|
||||
import UserCustomForm from './Form';
|
||||
|
||||
export default function UserCustom() {
|
||||
const { rowSelection, selectedRowIDs } = useTableRowSelection();
|
||||
const [isVisible, setVisible] = useState(false);
|
||||
const [jsonPath, setJsonPath] = useState('');
|
||||
const { modelJson, modelSet } = useChatModel('user_custom');
|
||||
const { modelCacheJson, modelCacheSet } = useCacheModel(jsonPath);
|
||||
const { promptJson, promptSet } = useChatPrompt('user_custom');
|
||||
const { promptCacheJson, promptCacheSet } = useCachePrompt(jsonPath);
|
||||
const { opData, opInit, opReplaceItems, opAdd, opRemove, opReplace, opSafeKey } = useData([]);
|
||||
const { columns, ...opInfo } = useColumns(modelColumns());
|
||||
const lastUpdated = modelJson?.user_custom?.last_updated;
|
||||
const { columns, ...opInfo } = useColumns(promptColumns());
|
||||
const lastUpdated = promptJson?.user_custom?.last_updated;
|
||||
const selectedItems = rowSelection.selectedRowKeys || [];
|
||||
const formRef = useRef<any>(null);
|
||||
|
||||
useInit(async () => {
|
||||
setJsonPath(await path.join(await chatRoot(), 'cache_model', 'user_custom.json'));
|
||||
setJsonPath(await path.join(await chatRoot(), 'cache_prompts', 'user_custom.json'));
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (modelCacheJson.length <= 0) return;
|
||||
opInit(modelCacheJson);
|
||||
}, [modelCacheJson.length]);
|
||||
if (promptCacheJson.length <= 0) return;
|
||||
opInit(promptCacheJson);
|
||||
}, [promptCacheJson.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!opInfo.opType) return;
|
||||
@ -40,7 +40,7 @@ export default function UserCustom() {
|
||||
}
|
||||
if (['delete'].includes(opInfo.opType)) {
|
||||
const data = opRemove(opInfo?.opRecord?.[opSafeKey]);
|
||||
modelCacheSet(data);
|
||||
promptCacheSet(data);
|
||||
opInfo.resetRecord();
|
||||
}
|
||||
}, [opInfo.opType, formRef]);
|
||||
@ -48,13 +48,13 @@ export default function UserCustom() {
|
||||
useEffect(() => {
|
||||
if (opInfo.opType === 'enable') {
|
||||
const data = opReplace(opInfo?.opRecord?.[opSafeKey], opInfo?.opRecord);
|
||||
modelCacheSet(data);
|
||||
promptCacheSet(data);
|
||||
}
|
||||
}, [opInfo.opTime]);
|
||||
|
||||
const handleEnable = (isEnable: boolean) => {
|
||||
const data = opReplaceItems(selectedRowIDs, { enable: isEnable });
|
||||
modelCacheSet(data);
|
||||
promptCacheSet(data);
|
||||
};
|
||||
|
||||
const hide = () => {
|
||||
@ -65,7 +65,7 @@ export default function UserCustom() {
|
||||
const handleOk = () => {
|
||||
formRef.current?.form?.validateFields().then(async (vals: Record<string, any>) => {
|
||||
if (
|
||||
modelCacheJson.map((i: any) => i.cmd).includes(vals.cmd) &&
|
||||
promptCacheJson.map((i: any) => i.cmd).includes(vals.cmd) &&
|
||||
opInfo?.opRecord?.cmd !== vals.cmd
|
||||
) {
|
||||
message.warning(
|
||||
@ -84,9 +84,9 @@ export default function UserCustom() {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
await modelCacheSet(data);
|
||||
await promptCacheSet(data);
|
||||
opInit(data);
|
||||
modelSet({
|
||||
promptSet({
|
||||
id: 'user_custom',
|
||||
last_updated: Date.now(),
|
||||
});
|
||||
@ -94,13 +94,13 @@ export default function UserCustom() {
|
||||
});
|
||||
};
|
||||
|
||||
const modalTitle = `${{ new: 'Create', edit: 'Edit' }[opInfo.opType]} Model`;
|
||||
const modalTitle = `${{ new: 'Create', edit: 'Edit' }[opInfo.opType]} Prompt`;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="chat-table-btns">
|
||||
<Button className="chat-add-btn" type="primary" onClick={opInfo.opNew}>
|
||||
Add Model
|
||||
Add Prompt
|
||||
</Button>
|
||||
<div>
|
||||
{selectedItems.length > 0 && (
|
||||
@ -115,7 +115,7 @@ export default function UserCustom() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="chat-table-tip">
|
||||
<FilePath label="CACHE" paths="cache_model/user_custom.json" />
|
||||
<FilePath label="CACHE" paths="cache_prompts/user_custom.json" />
|
||||
{lastUpdated && (
|
||||
<span style={{ marginLeft: 10, color: '#888', fontSize: 12 }}>
|
||||
Last updated on {fmtDate(lastUpdated)}
|
76
src/view/scripts/Editor.tsx
vendored
Normal file
76
src/view/scripts/Editor.tsx
vendored
Normal file
@ -0,0 +1,76 @@
|
||||
import { FC, useState } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import Editor from '@monaco-editor/react';
|
||||
import { Breadcrumb, Tag, Popconfirm } from 'antd';
|
||||
import { ArrowLeftOutlined } from '@ant-design/icons';
|
||||
import { fs, shell, dialog, process } from '@tauri-apps/api';
|
||||
|
||||
import useInit from '@/hooks/useInit';
|
||||
import { getPath } from './config';
|
||||
|
||||
interface ScriptEditorProps {
|
||||
onChange?: (v: string) => void;
|
||||
}
|
||||
|
||||
const ScriptEditor: FC<ScriptEditorProps> = ({ onChange }) => {
|
||||
const [filePath, setFilePath] = useState('');
|
||||
const [source, setSource] = useState('// write your script here\n');
|
||||
const location = useLocation();
|
||||
const state = location?.state;
|
||||
|
||||
useInit(async () => {
|
||||
const file = await getPath(state);
|
||||
setFilePath(file);
|
||||
setSource(await fs.readTextFile(file));
|
||||
});
|
||||
|
||||
const handleEdit = (e: any) => {
|
||||
setSource(e);
|
||||
onChange && onChange(e);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
await fs.writeTextFile(filePath, source);
|
||||
const isOk = await dialog.ask(
|
||||
'The script will take effect after the application is restarted. Do you want to restart now?',
|
||||
{
|
||||
title: 'Script saved successfully',
|
||||
},
|
||||
);
|
||||
|
||||
if (isOk) {
|
||||
process.relaunch();
|
||||
}
|
||||
};
|
||||
|
||||
const handleReset = async () => {
|
||||
setSource(await fs.readTextFile(filePath));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="script-editor">
|
||||
<Breadcrumb className="editor-task" separator="">
|
||||
<Breadcrumb.Item onClick={() => history.go(-1)}>
|
||||
<ArrowLeftOutlined />
|
||||
</Breadcrumb.Item>
|
||||
<Popconfirm
|
||||
placement="topRight"
|
||||
title="Are you sure you want to save the changes? It is a risky operation, but you can restore it through the sync button."
|
||||
onConfirm={handleSave}
|
||||
onCancel={handleReset}
|
||||
okText="Yes"
|
||||
cancelText="No"
|
||||
overlayStyle={{ width: 300 }}
|
||||
>
|
||||
<Tag className="editor-btn" color="#108ee9">
|
||||
Save
|
||||
</Tag>
|
||||
</Popconfirm>
|
||||
<Breadcrumb.Item onClick={() => shell.open(filePath)}>{filePath}</Breadcrumb.Item>
|
||||
</Breadcrumb>
|
||||
<Editor height="80vh" language="javascript" value={source} onChange={handleEdit} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ScriptEditor;
|
94
src/view/scripts/config.tsx
vendored
Normal file
94
src/view/scripts/config.tsx
vendored
Normal file
@ -0,0 +1,94 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Tag, Space, Popconfirm } from 'antd';
|
||||
import { ArrowRightOutlined } from '@ant-design/icons';
|
||||
import { path, shell } from '@tauri-apps/api';
|
||||
|
||||
import useInit from '@/hooks/useInit';
|
||||
import { fmtDate, chatRoot } from '@/utils';
|
||||
|
||||
export const scriptColumns = ({ scriptsMap }: any) => [
|
||||
{
|
||||
title: 'File Name',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
fixed: 'left',
|
||||
width: 160,
|
||||
render: (v: string) => <Tag color={v === 'main.js' ? 'green' : 'default'}>{v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: 'Version',
|
||||
width: 200,
|
||||
render: (_: string, row: any) => {
|
||||
const next = scriptsMap?.[row.name]?.next_version;
|
||||
const curr = scriptsMap?.[row.name]?.curr_version;
|
||||
return (
|
||||
row.name !== 'main.js' && (
|
||||
<Space>
|
||||
{curr && <Tag style={{ marginRight: 0 }}>{curr}</Tag>}
|
||||
{next && next !== curr && <ArrowRightOutlined style={{ color: '#989898' }} />}
|
||||
{next && next !== curr && <Tag color="green-inverse">{next}</Tag>}
|
||||
</Space>
|
||||
)
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Path',
|
||||
dataIndex: 'path',
|
||||
key: 'path',
|
||||
width: 200,
|
||||
render: (_: string, row: any) => <RenderPath row={row} />,
|
||||
},
|
||||
{
|
||||
title: 'Remote File',
|
||||
width: 200,
|
||||
render: (_: string, row: any) => {
|
||||
const uri = `https://raw.githubusercontent.com/lencx/ChatGPT/main/scripts/${row.name}`;
|
||||
return <a onClick={() => shell.open(uri)}>{uri}</a>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Action',
|
||||
fixed: 'right',
|
||||
width: 100,
|
||||
render: (_: any, row: any, actions: any) => {
|
||||
const isExternal = row.name === 'main.js';
|
||||
return (
|
||||
<Space>
|
||||
<Link
|
||||
to={`/scripts/${row.id}`}
|
||||
state={row}
|
||||
style={{ color: !isExternal ? '#ff4d4f' : '' }}
|
||||
>
|
||||
Edit
|
||||
</Link>
|
||||
{!isExternal && (
|
||||
<Popconfirm
|
||||
placement="topLeft"
|
||||
title="Are you sure you want to synchronize? It will overwrite all previous modifications made to this file."
|
||||
onConfirm={() => actions.setRecord(row, 'sync')}
|
||||
okText="Yes"
|
||||
cancelText="No"
|
||||
overlayStyle={{ width: 300 }}
|
||||
>
|
||||
<a>Sync</a>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const RenderPath = ({ row }: any) => {
|
||||
const [filePath, setFilePath] = useState('');
|
||||
useInit(async () => {
|
||||
setFilePath(await getPath(row));
|
||||
});
|
||||
return <a onClick={() => shell.open(filePath)}>{filePath}</a>;
|
||||
};
|
||||
|
||||
export const getPath = async (row: any) => {
|
||||
return await path.join(await chatRoot(), 'scripts', `${row.name}`);
|
||||
};
|
80
src/view/scripts/index.tsx
vendored
Normal file
80
src/view/scripts/index.tsx
vendored
Normal file
@ -0,0 +1,80 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Table, message } from 'antd';
|
||||
import { path, fs, invoke } from '@tauri-apps/api';
|
||||
|
||||
import useInit from '@/hooks/useInit';
|
||||
import useColumns from '@/hooks/useColumns';
|
||||
import { TABLE_PAGINATION } from '@/hooks/useTable';
|
||||
import { scriptRoot } from '@/utils';
|
||||
import { scriptColumns } from './config';
|
||||
|
||||
const SCRIPTS = [
|
||||
'main.js',
|
||||
'core.js',
|
||||
'chat.js',
|
||||
'cmd.js',
|
||||
'dalle2.js',
|
||||
'export.js',
|
||||
'markdown.export.js',
|
||||
'popup.core.js',
|
||||
];
|
||||
|
||||
export default function Scripts() {
|
||||
const [scriptsMap, setScriptsMap] = useState({});
|
||||
const { columns, ...opInfo } = useColumns(scriptColumns({ scriptsMap }));
|
||||
|
||||
const handleInit = async () => {
|
||||
try {
|
||||
const manifestPath = await path.join(await scriptRoot(), 'manifest.json');
|
||||
const data = await fs.readTextFile(manifestPath);
|
||||
const { scripts } = JSON.parse(data);
|
||||
const infoMap: Record<string, any> = {};
|
||||
|
||||
for (const script of scripts) {
|
||||
const scriptInfo: any = await invoke('get_script_info', { name: script.name });
|
||||
infoMap[script.name] = {
|
||||
curr_version: scriptInfo?.version,
|
||||
next_version: script.version,
|
||||
};
|
||||
}
|
||||
setScriptsMap(infoMap);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
useInit(handleInit);
|
||||
|
||||
useEffect(() => {
|
||||
if (!opInfo.opType) return;
|
||||
(async () => {
|
||||
if (opInfo.opType === 'sync') {
|
||||
const isOk = await invoke('sync_scripts', { name: opInfo?.opRecord?.name });
|
||||
if (isOk) {
|
||||
await handleInit();
|
||||
opInfo.resetRecord();
|
||||
message.success(
|
||||
`The ${opInfo?.opRecord?.name} script has been synchronized successfully`,
|
||||
);
|
||||
} else {
|
||||
message.error(
|
||||
`The ${opInfo?.opRecord?.name} script synchronization failed. You can try editing the script and click the Remote File link to copy the source code.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [opInfo.opType]);
|
||||
|
||||
return (
|
||||
<div className="chatgpt-script">
|
||||
<Table
|
||||
rowKey="name"
|
||||
scroll={{ x: 800 }}
|
||||
columns={columns}
|
||||
dataSource={SCRIPTS.map((i) => ({ name: i }))}
|
||||
{...TABLE_PAGINATION}
|
||||
pagination={false}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
8
src/view/settings/General.tsx
vendored
8
src/view/settings/General.tsx
vendored
@ -25,19 +25,19 @@ export default function General() {
|
||||
<Form.Item label="Stay On Top" name="stay_on_top" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
<Form.Item label="Save Window State" name="save_window_state" valuePropName="checked">
|
||||
{/* <Form.Item label="Save Window State" name="save_window_state" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Form.Item> */}
|
||||
{platformInfo === 'darwin' && (
|
||||
<Form.Item label="Titlebar" name="titlebar" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
)}
|
||||
{platformInfo === 'darwin' && (
|
||||
{/* {platformInfo === 'darwin' && (
|
||||
<Form.Item label="Hide Dock Icon" name="hide_dock_icon" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
)}
|
||||
)} */}
|
||||
<Form.Item label="Theme" name="theme">
|
||||
<Radio.Group>
|
||||
<Radio value="light">Light</Radio>
|
||||
|
4
src/view/settings/MainWindow.tsx
vendored
4
src/view/settings/MainWindow.tsx
vendored
@ -1,7 +1,7 @@
|
||||
import { Form, Switch, Input, InputNumber, Tooltip } from 'antd';
|
||||
import { QuestionCircleOutlined } from '@ant-design/icons';
|
||||
|
||||
import SwitchOrigin from '@/components/SwitchOrigin';
|
||||
// import SwitchOrigin from '@/components/SwitchOrigin';
|
||||
import { DISABLE_AUTO_COMPLETE } from '@/utils';
|
||||
|
||||
const PopupSearchLabel = () => {
|
||||
@ -56,7 +56,7 @@ export default function MainWindow() {
|
||||
<Form.Item label="Default Height" name="main_height">
|
||||
<InputNumber />
|
||||
</Form.Item>
|
||||
<SwitchOrigin name="main" />
|
||||
{/* <SwitchOrigin name="main" /> */}
|
||||
<Form.Item label="User Agent (Main)" name="ua_window">
|
||||
<Input.TextArea
|
||||
autoSize={{ minRows: 4, maxRows: 4 }}
|
||||
|
4
src/view/settings/TrayWindow.tsx
vendored
4
src/view/settings/TrayWindow.tsx
vendored
@ -2,7 +2,7 @@ import { Form, Switch, Input, InputNumber, Tooltip } from 'antd';
|
||||
import { QuestionCircleOutlined } from '@ant-design/icons';
|
||||
|
||||
import { DISABLE_AUTO_COMPLETE } from '@/utils';
|
||||
import SwitchOrigin from '@/components/SwitchOrigin';
|
||||
// import SwitchOrigin from '@/components/SwitchOrigin';
|
||||
|
||||
const UALabel = () => {
|
||||
return (
|
||||
@ -29,7 +29,7 @@ export default function TrayWindow() {
|
||||
<Form.Item label="Default Height" name="tray_height">
|
||||
<InputNumber />
|
||||
</Form.Item>
|
||||
<SwitchOrigin name="tray" />
|
||||
{/* <SwitchOrigin name="tray" /> */}
|
||||
<Form.Item label={<UALabel />} name="ua_tray">
|
||||
<Input.TextArea
|
||||
autoSize={{ minRows: 4, maxRows: 4 }}
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"target": "ES2015",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
||||
"allowJs": false,
|
||||
|
Loading…
Reference in New Issue
Block a user