diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a90ef58 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 变更记录 + +## 2026-11-26 · 初始同步 + +- 同步插件源代码到新 Gitea 仓库。 +- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。 +- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..428f0a0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) 2026 GI-OBSIDIAN + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 68d23d9..a42b790 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,31 @@ -# Writing +# AI 写作助手 +> 仓库:`Writing` · 类型:Obsidian 插件 · 版本:`1.0.0` · 作者:GI-OBSIDIAN + +右键菜单与侧边栏对话,一键重写、润色、补充、缩减中文文本。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `manifest.json` +- `src/` +- `styles.css` + +## 安装与使用 + +1. 本仓库仅包含插件源代码,未包含依赖与构建工具;请先按 Obsidian 插件标准流程构建生成 `main.js`。 +2. 将 `manifest.json`、构建后的 `main.js`、`styles.css` 及源码目录放入 `/.obsidian/plugins/<插件 id>/`。 +3. 在 Obsidian「设置 → 第三方插件」中启用该插件。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..0b61195 --- /dev/null +++ b/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "writing-assistant", + "name": "AI 写作助手", + "version": "1.0.0", + "minAppVersion": "0.15.0", + "description": "右键菜单 + 侧边栏对话,一键重写/润色/补充/缩减中文文本", + "author": "Your Name", + "authorUrl": "", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..e3e4087 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,1083 @@ +import { + App, + Editor, + Plugin, + PluginSettingTab, + Setting, + Notice, + WorkspaceLeaf, + View, + MarkdownView, + Menu, + TextComponent, + TextAreaComponent, + DropdownComponent +} from 'obsidian'; + +// API类型枚举 +enum ApiType { + DEEPSEEK = 'deepseek', + ZHIPU = 'zhipu' +} + +interface Action { + id: string; + name: string; + icon: string; + prompt: string; +} + +interface ChatMessage { + role: 'user' | 'assistant' | 'system'; + content: string; + timestamp: number; +} + +interface PluginSettings { + apiType: ApiType; + // DeepSeek 配置 + deepseekApiKey: string; + deepseekBaseUrl: string; + deepseekModel: string; + // 智谱清言配置 + zhipuApiKey: string; + zhipuModel: string; + // 通用 + actions: Action[]; + chatHistory: ChatMessage[]; + currentModel: string; + // 记录每个消息使用的模型,用于切换时保持上下文 + messageModelMap?: Record; +} + +const DEFAULT_ACTIONS: Action[] = [ + { + id: 'rewrite', + name: '重写', + icon: '🔄', + prompt: '请用不同表达方式重写以下中文文本,保持原意,使表达更生动多样。只返回重写后的文本,不要添加任何解释。' + }, + { + id: 'polish', + name: '润色', + icon: '✨', + prompt: '请优化以下中文文本,使语言更流畅、逻辑更清晰、用词更精准。只返回润色后的文本。' + }, + { + id: 'expand', + name: '补充', + icon: '📖', + prompt: '请扩充以下中文文本,添加更多细节、例证和解释,使内容更丰富。只返回扩充后的文本。' + }, + { + id: 'condense', + name: '缩减', + icon: '✂️', + prompt: '请精简以下中文文本,删除冗余信息,只保留核心内容。只返回缩减后的文本。' + }, + { + id: 'correct', + name: '纠正', + icon: '🔧', + prompt: '请修正以下中文文本的错别字、语法错误和标点误用。只返回修正后的文本。' + } +]; + +const DEFAULT_SETTINGS: PluginSettings = { + apiType: ApiType.DEEPSEEK, + deepseekApiKey: '', + deepseekBaseUrl: 'https://api.deepseek.com/v1', + deepseekModel: 'deepseek-chat', + zhipuApiKey: '', + zhipuModel: 'glm-4.7-flash', + actions: DEFAULT_ACTIONS, + chatHistory: [], + currentModel: 'deepseek-chat', + messageModelMap: {} +}; + +const VIEW_TYPE_CHAT = 'writing-assistant-chat'; + +// 模型配置 +interface ModelConfig { + displayName: string; + apiType: ApiType; + modelId: string; +} + +function getAvailableModels(settings: PluginSettings): ModelConfig[] { + const models: ModelConfig[] = []; + + if (settings.deepseekApiKey) { + models.push({ + displayName: `DeepSeek: ${settings.deepseekModel}`, + apiType: ApiType.DEEPSEEK, + modelId: settings.deepseekModel + }); + } + + if (settings.zhipuApiKey) { + models.push({ + displayName: `智谱清言: ${settings.zhipuModel}`, + apiType: ApiType.ZHIPU, + modelId: settings.zhipuModel + }); + } + + return models; +} + +class ChatView extends View { + plugin: WritingAssistantPlugin; + messagesContainer: HTMLElement; + inputArea: HTMLTextAreaElement; + isProcessing: boolean = false; + modelDropdown: DropdownComponent | null = null; + // 添加一个标志来跟踪是否需要重新构建对话上下文 + private contextNeedsRebuild: boolean = false; + + constructor(leaf: WorkspaceLeaf, plugin: WritingAssistantPlugin) { + super(leaf); + this.plugin = plugin; + } + + getViewType(): string { + return VIEW_TYPE_CHAT; + } + + getDisplayText(): string { + return '写作助手'; + } + + getIcon(): string { + return 'message-square'; + } + + async onOpen() { + const container = this.containerEl; + container.empty(); + container.addClass('chat-container'); + + const header = container.createEl('div', { cls: 'chat-header' }); + header.createEl('h4', { text: '写作助手' }); + + const headerActions = header.createEl('div', { cls: 'chat-header-actions' }); + + // 模型切换下拉菜单 + const modelSelectWrapper = headerActions.createEl('div', { + cls: 'chat-model-selector' + }); + modelSelectWrapper.style.display = 'flex'; + modelSelectWrapper.style.alignItems = 'center'; + modelSelectWrapper.style.gap = '8px'; + modelSelectWrapper.style.marginRight = '12px'; + + const labelEl = modelSelectWrapper.createEl('span', { text: '模型:' }); + labelEl.style.fontSize = '13px'; + labelEl.style.color = 'var(--text-muted)'; + + const modelSelect = new DropdownComponent(modelSelectWrapper); + this.modelDropdown = modelSelect; + this.updateModelDropdown(modelSelect); + + modelSelect.onChange(async (value) => { + const parts = value.split('||'); + if (parts.length === 2) { + const apiType = parts[0] as ApiType; + const modelId = parts[1]; + + // 检查模型是否真的发生了变化 + const oldApiType = this.plugin.settings.apiType; + const oldModel = this.plugin.settings.currentModel; + const isChanged = (apiType !== oldApiType || modelId !== oldModel); + + this.plugin.settings.currentModel = modelId; + this.plugin.settings.apiType = apiType; + await this.plugin.saveSettings(); + + // 模型切换后,标记需要重建上下文,但不清除历史 + if (isChanged) { + this.contextNeedsRebuild = true; + new Notice(`已切换到: ${modelSelect.getValue()},对话将在下一条消息时使用新模型`); + } + } + }); + + const clearBtn = headerActions.createEl('button', { + text: '清空', + cls: 'chat-clear-btn' + }); + clearBtn.addEventListener('click', () => { + this.plugin.settings.chatHistory = []; + this.plugin.settings.messageModelMap = {}; + this.contextNeedsRebuild = false; + this.plugin.saveSettings(); + this.renderMessages(); + new Notice('已清空对话历史'); + }); + + this.messagesContainer = container.createEl('div', { cls: 'chat-messages' }); + this.renderMessages(); + + const inputSection = container.createEl('div', { cls: 'chat-input-section' }); + const inputRow = inputSection.createEl('div', { cls: 'chat-input-row' }); + + this.inputArea = inputRow.createEl('textarea', { + cls: 'chat-input', + placeholder: '输入指令,按 Enter 发送...' + }); + this.inputArea.rows = 2; + + this.inputArea.addEventListener('keydown', (e) => { + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + this.sendMessage(); + } + }); + + this.inputArea.addEventListener('input', () => { + this.inputArea.style.height = 'auto'; + this.inputArea.style.height = Math.min(this.inputArea.scrollHeight, 120) + 'px'; + }); + } + + updateModelDropdown(dropdown: DropdownComponent) { + const settings = this.plugin.settings; + const models = getAvailableModels(settings); + + dropdown.selectEl.empty(); + + if (models.length === 0) { + dropdown.addOption('none', '请先在设置中配置API'); + dropdown.setValue('none'); + dropdown.selectEl.disabled = true; + return; + } + + dropdown.selectEl.disabled = false; + let foundCurrent = false; + + models.forEach(model => { + const value = `${model.apiType}||${model.modelId}`; + const label = model.displayName; + dropdown.addOption(value, label); + + if (model.modelId === settings.currentModel && + model.apiType === settings.apiType) { + foundCurrent = true; + } + }); + + if (foundCurrent) { + dropdown.setValue(`${settings.apiType}||${settings.currentModel}`); + } else if (models.length > 0) { + const first = models[0]; + dropdown.setValue(`${first.apiType}||${first.modelId}`); + settings.apiType = first.apiType; + settings.currentModel = first.modelId; + this.plugin.saveSettings(); + } + } + + renderMessages() { + this.messagesContainer.empty(); + const history = this.plugin.settings.chatHistory; + + if (history.length === 0) { + this.messagesContainer.createEl('div', { + text: '开始对话吧!\n输入指令,按 Enter 发送', + cls: 'chat-empty' + }); + return; + } + + // 获取当前使用的模型信息用于显示 + const currentModelName = this.getCurrentModelDisplayName(); + + history.forEach((msg, index) => { + const msgDiv = this.messagesContainer.createEl('div', { + cls: `chat-message chat-${msg.role}` + }); + + const labelDiv = msgDiv.createEl('div', { + cls: 'chat-message-label' + }); + + const labelText = msg.role === 'user' ? '你' : 'AI'; + labelDiv.setText(labelText); + + // 如果是AI消息,显示使用的模型(如果有记录) + if (msg.role === 'assistant' && this.plugin.settings.messageModelMap) { + const modelForMessage = this.plugin.settings.messageModelMap[index]; + if (modelForMessage) { + const modelLabel = labelDiv.createEl('span', { + cls: 'chat-model-tag', + text: ` ${modelForMessage}` + }); + modelLabel.style.fontSize = '10px'; + modelLabel.style.color = 'var(--text-muted)'; + modelLabel.style.marginLeft = '8px'; + modelLabel.style.opacity = '0.7'; + } + } + + const content = msgDiv.createEl('div', { cls: 'chat-message-content' }); + content.innerHTML = this.formatMessage(msg.content); + + if (msg.role === 'assistant') { + const btnGroup = msgDiv.createEl('div', { cls: 'chat-btn-group' }); + + const copyBtn = btnGroup.createEl('button', { + cls: 'chat-action-btn', + text: '复制' + }); + copyBtn.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(msg.content); + new Notice('已复制到剪贴板'); + } catch (err) { + new Notice('复制失败: ' + err.message); + } + }); + + const insertBtn = btnGroup.createEl('button', { + cls: 'chat-action-btn', + text: '插入编辑器' + }); + insertBtn.addEventListener('click', () => { + const leaves = this.app.workspace.getLeavesOfType('markdown'); + + if (leaves.length === 0) { + new Notice('没有打开的 Markdown 文件'); + return; + } + + let activeView = this.app.workspace.getActiveViewOfType(MarkdownView); + + if (!activeView) { + const leaf = leaves[0]; + if (leaf && leaf.view instanceof MarkdownView) { + activeView = leaf.view; + } + } + + if (activeView) { + const editor = activeView.editor; + const cursor = editor.getCursor(); + editor.replaceRange(msg.content, cursor); + new Notice('已插入到当前编辑器'); + } else { + new Notice('没有找到可用的编辑器'); + } + }); + } + }); + + this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight; + } + + getCurrentModelDisplayName(): string { + const settings = this.plugin.settings; + if (settings.apiType === ApiType.DEEPSEEK) { + return `DeepSeek: ${settings.deepseekModel}`; + } else if (settings.apiType === ApiType.ZHIPU) { + return `智谱清言: ${settings.zhipuModel}`; + } + return '未知模型'; + } + + formatMessage(content: string): string { + return content + .replace(/\n/g, '
') + .replace(/```(\w+)?\n([\s\S]*?)```/g, '
$2
') + .replace(/`([^`]+)`/g, '$1'); + } + + async sendMessage() { + const text = this.inputArea.value.trim(); + if (!text) { + return; + } + + const userMsg: ChatMessage = { + role: 'user', + content: text, + timestamp: Date.now() + }; + + // 记录当前使用的模型信息 + const currentModelKey = `${this.plugin.settings.apiType}||${this.plugin.settings.currentModel}`; + const userMsgIndex = this.plugin.settings.chatHistory.length; + if (!this.plugin.settings.messageModelMap) { + this.plugin.settings.messageModelMap = {}; + } + this.plugin.settings.messageModelMap[userMsgIndex] = currentModelKey; + + this.plugin.settings.chatHistory.push(userMsg); + await this.plugin.saveSettings(); + this.renderMessages(); + + this.inputArea.value = ''; + this.inputArea.style.height = 'auto'; + this.setProcessing(true); + + try { + const result = await this.callAIWithHistory(text); + + const assistantMsg: ChatMessage = { + role: 'assistant', + content: result, + timestamp: Date.now() + }; + const assistantMsgIndex = this.plugin.settings.chatHistory.length; + this.plugin.settings.messageModelMap[assistantMsgIndex] = currentModelKey; + + this.plugin.settings.chatHistory.push(assistantMsg); + await this.plugin.saveSettings(); + + // 切换模型后首次发送成功,清除重建标志 + this.contextNeedsRebuild = false; + + this.renderMessages(); + } catch (error) { + new Notice(`失败: ${error.message}`); + } finally { + this.setProcessing(false); + } + } + + setProcessing(processing: boolean) { + this.isProcessing = processing; + this.inputArea.disabled = processing; + this.inputArea.placeholder = processing ? '处理中...' : '输入指令,按 Enter 发送...'; + } + + // 获取适合当前模型的对话历史 + getFilteredHistoryForCurrentModel(): ChatMessage[] { + const history = this.plugin.settings.chatHistory; + const currentModelKey = `${this.plugin.settings.apiType}||${this.plugin.settings.currentModel}`; + const modelMap = this.plugin.settings.messageModelMap || {}; + + // 如果不需要重建上下文,返回所有历史 + if (!this.contextNeedsRebuild) { + return history; + } + + // 需要重建:从最后一条匹配当前模型的消息开始截取 + // 找到最后一个使用当前模型的消息索引 + let lastMatchingIndex = -1; + for (let i = history.length - 1; i >= 0; i--) { + if (modelMap[i] === currentModelKey) { + lastMatchingIndex = i; + break; + } + } + + if (lastMatchingIndex === -1) { + // 没有匹配的消息,使用最近的消息(最多10条) + return history.slice(-10); + } + + // 从匹配的消息开始,确保上下文连续 + return history.slice(lastMatchingIndex); + } + + async callAIWithHistory(userMessage: string): Promise { + // 获取适合当前模型的对话历史 + const filteredHistory = this.getFilteredHistoryForCurrentModel(); + + // 如果过滤后的历史与原始历史不同,说明发生了模型切换,给用户提示 + if (filteredHistory.length < this.plugin.settings.chatHistory.length) { + // 在日志中记录,但不打扰用户 + console.log(`模型切换后,使用从第 ${filteredHistory.length} 条消息开始的上下文`); + } + + // 构建消息列表,保留系统提示词的上下文 + const messages = filteredHistory.map(msg => ({ + role: msg.role, + content: msg.content + })); + + // 添加用户的新消息 + messages.push({ role: 'user', content: userMessage }); + + const apiType = this.plugin.settings.apiType; + + if (apiType === ApiType.DEEPSEEK) { + return this.callDeepSeek(messages); + } else if (apiType === ApiType.ZHIPU) { + return this.callZhipu(messages); + } else { + throw new Error('不支持的 API 类型'); + } + } + + async callDeepSeek(messages: any[]): Promise { + const response = await fetch(`${this.plugin.settings.deepseekBaseUrl}/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${this.plugin.settings.deepseekApiKey}` + }, + body: JSON.stringify({ + model: this.plugin.settings.deepseekModel, + messages: messages, + temperature: 0.7, + max_tokens: 2000 + }) + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new Error(`DeepSeek API 请求失败 (${response.status}): ${errorText}`); + } + + const data = await response.json(); + if (!data.choices || !data.choices[0] || !data.choices[0].message) { + throw new Error('DeepSeek API 返回格式异常'); + } + return data.choices[0].message.content.trim(); + } + + async callZhipu(messages: any[]): Promise { + const zhipuMessages = messages.map(msg => ({ + role: msg.role, + content: msg.content + })); + + const response = await fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${this.plugin.settings.zhipuApiKey}` + }, + body: JSON.stringify({ + model: this.plugin.settings.zhipuModel, + messages: zhipuMessages, + temperature: 0.7, + max_tokens: 2000 + }) + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new Error(`智谱清言 API 请求失败 (${response.status}): ${errorText}`); + } + + const data = await response.json(); + if (!data.choices || !data.choices[0] || !data.choices[0].message) { + throw new Error('智谱清言 API 返回格式异常'); + } + return data.choices[0].message.content.trim(); + } + + async onClose() {} +} + +export default class WritingAssistantPlugin extends Plugin { + settings: PluginSettings; + chatView: ChatView | null = null; + + async onload() { + await this.loadSettings(); + + this.registerView(VIEW_TYPE_CHAT, (leaf) => { + this.chatView = new ChatView(leaf, this); + return this.chatView; + }); + + this.addRibbonIcon('message-square', '打开写作助手', () => { + this.activateView(); + }); + + this.registerEvent( + this.app.workspace.on('editor-menu', (menu: Menu, editor: Editor) => { + const selectedText = editor.getSelection(); + if (!selectedText) return; + + menu.addSeparator(); + + const actions = this.settings.actions; + actions.forEach((action: Action) => { + menu.addItem((item) => { + item + .setTitle(action.name) + .onClick(async () => { + await this.processWithAction(editor, selectedText, action); + }); + }); + }); + + menu.addSeparator(); + menu.addItem((item) => { + item + .setTitle('发送到对话') + .onClick(() => { + this.sendToChat(selectedText); + }); + }); + }) + ); + + this.addCommand({ + id: 'open-chat', + name: '打开写作助手', + callback: () => this.activateView() + }); + + this.addSettingTab(new SettingTab(this.app, this)); + } + + async processWithAction(editor: Editor, text: string, action: Action) { + const from = editor.getCursor('from'); + new Notice(`${action.icon} 正在${action.name}...`); + + try { + const result = await this.callAI(text, action.prompt); + editor.replaceSelection(result); + editor.setSelection(from, editor.getCursor('to')); + new Notice(`${action.name}完成`); + + this.addToHistory(`[${action.name}] ${text}`, result); + } catch (error) { + new Notice(`失败: ${error.message}`); + } + } + + async callAI(text: string, systemPrompt: string): Promise { + const messages = [ + { role: 'system', content: systemPrompt }, + { role: 'user', content: text } + ]; + + const apiType = this.settings.apiType; + + if (apiType === ApiType.DEEPSEEK) { + return this.callDeepSeek(messages); + } else if (apiType === ApiType.ZHIPU) { + return this.callZhipu(messages); + } else { + throw new Error('不支持的 API 类型'); + } + } + + async callDeepSeek(messages: any[]): Promise { + const response = await fetch(`${this.settings.deepseekBaseUrl}/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${this.settings.deepseekApiKey}` + }, + body: JSON.stringify({ + model: this.settings.deepseekModel, + messages: messages, + temperature: 0.7, + max_tokens: 2000 + }) + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new Error(`DeepSeek API 请求失败 (${response.status}): ${errorText}`); + } + + const data = await response.json(); + if (!data.choices || !data.choices[0] || !data.choices[0].message) { + throw new Error('DeepSeek API 返回格式异常'); + } + return data.choices[0].message.content.trim(); + } + + async callZhipu(messages: any[]): Promise { + const response = await fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${this.settings.zhipuApiKey}` + }, + body: JSON.stringify({ + model: this.settings.zhipuModel, + messages: messages, + temperature: 0.7, + max_tokens: 2000 + }) + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new Error(`智谱清言 API 请求失败 (${response.status}): ${errorText}`); + } + + const data = await response.json(); + if (!data.choices || !data.choices[0] || !data.choices[0].message) { + throw new Error('智谱清言 API 返回格式异常'); + } + return data.choices[0].message.content.trim(); + } + + addToHistory(userContent: string, assistantContent: string) { + const currentModelKey = `${this.settings.apiType}||${this.settings.currentModel}`; + if (!this.settings.messageModelMap) { + this.settings.messageModelMap = {}; + } + + const userIndex = this.settings.chatHistory.length; + this.settings.messageModelMap[userIndex] = currentModelKey; + + this.settings.chatHistory.push( + { role: 'user', content: userContent, timestamp: Date.now() } + ); + + const assistantIndex = this.settings.chatHistory.length; + this.settings.messageModelMap[assistantIndex] = currentModelKey; + + this.settings.chatHistory.push( + { role: 'assistant', content: assistantContent, timestamp: Date.now() } + ); + + this.saveSettings(); + if (this.chatView) { + this.chatView.renderMessages(); + } + } + + sendToChat(text: string) { + this.activateView(); + setTimeout(() => { + if (this.chatView) { + this.chatView.inputArea.value = text; + this.chatView.inputArea.focus(); + } + }, 100); + } + + async activateView() { + const { workspace } = this.app; + let leaf = workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]; + + if (!leaf) { + const rightLeaf = workspace.getRightLeaf(false); + if (rightLeaf) { + leaf = rightLeaf; + await leaf.setViewState({ + type: VIEW_TYPE_CHAT, + active: true + }); + } else { + new Notice('无法创建侧边栏视图'); + return; + } + } + + if (leaf) { + workspace.revealLeaf(leaf); + } + } + + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + if (!this.settings.actions || this.settings.actions.length === 0) { + this.settings.actions = DEFAULT_ACTIONS; + } + if (!this.settings.messageModelMap) { + this.settings.messageModelMap = {}; + } + const oldData = await this.loadData(); + if (oldData && oldData.apiKey && !oldData.deepseekApiKey) { + this.settings.deepseekApiKey = oldData.apiKey; + } + if (oldData && oldData.baseUrl && !oldData.deepseekBaseUrl) { + this.settings.deepseekBaseUrl = oldData.baseUrl; + } + if (oldData && oldData.model && !oldData.deepseekModel) { + this.settings.deepseekModel = oldData.model; + } + // 兼容旧版 zhipuModel 设置 - 将旧版本映射到新版本 + if (this.settings.zhipuModel === 'glm-4-flash') { + this.settings.zhipuModel = 'glm-4.7-flash'; + } + } + + async saveSettings() { + await this.saveData(this.settings); + if (this.chatView && this.chatView.modelDropdown) { + this.chatView.updateModelDropdown(this.chatView.modelDropdown); + } + } + + onunload() {} +} + +class SettingTab extends PluginSettingTab { + plugin: WritingAssistantPlugin; + private configContainer: HTMLElement | null = null; + + constructor(app: App, plugin: WritingAssistantPlugin) { + super(app, plugin); + this.plugin = plugin; + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + + const title = containerEl.createEl('h2', { text: '写作助手' }); + title.style.marginLeft = '0'; + title.style.paddingLeft = '0'; + + containerEl.createEl('p', { + text: '配置 API 和自定义功能列表', + cls: 'wa-settings-desc' + }); + + // ============ API 类型选择 ============ + const apiTitle = containerEl.createEl('h3', { text: 'API 配置' }); + apiTitle.style.marginLeft = '0'; + apiTitle.style.paddingLeft = '0'; + + // 创建下拉框容器 - 使用原生 select + const dropdownContainer = containerEl.createEl('div'); + const setting = new Setting(dropdownContainer) + .setName('API 服务商') + .setDesc('选择要使用的 AI API 服务商'); + + // 直接创建 select 元素 + const selectEl = setting.settingEl.createEl('select'); + selectEl.style.width = '100%'; + selectEl.style.maxWidth = '200px'; + selectEl.style.marginLeft = 'auto'; + selectEl.style.display = 'block'; + + // 添加选项 + const option1 = selectEl.createEl('option'); + option1.value = ApiType.DEEPSEEK; + option1.textContent = 'DeepSeek'; + + const option2 = selectEl.createEl('option'); + option2.value = ApiType.ZHIPU; + option2.textContent = '智谱清言'; + + // 设置当前值 + selectEl.value = this.plugin.settings.apiType; + + // 监听变化事件 + selectEl.addEventListener('change', (e) => { + const target = e.target as HTMLSelectElement; + const value = target.value as ApiType; + this.plugin.settings.apiType = value; + this.plugin.saveSettings(); + this.renderConfigSection(); + }); + + // ============ 配置区域容器 ============ + this.configContainer = containerEl.createEl('div', { + cls: 'wa-config-container' + }); + this.renderConfigSection(); + + // ============ 功能列表 ============ + this.renderFunctionList(containerEl); + } + + // 渲染配置区域 + renderConfigSection(): void { + if (!this.configContainer) return; + this.configContainer.empty(); + + const currentApiType = this.plugin.settings.apiType; + + if (currentApiType === ApiType.DEEPSEEK) { + this.renderDeepSeekConfig(this.configContainer); + } else if (currentApiType === ApiType.ZHIPU) { + this.renderZhipuConfig(this.configContainer); + } + } + + // 渲染 DeepSeek 配置 + renderDeepSeekConfig(container: HTMLElement): void { + const section = container.createEl('div', { cls: 'wa-api-section' }); + + new Setting(section) + .setName('API Key') + .setDesc('你的 DeepSeek API Key') + .addText((text: TextComponent) => text + .setPlaceholder('sk-...') + .setValue(this.plugin.settings.deepseekApiKey) + .onChange(async (value: string) => { + this.plugin.settings.deepseekApiKey = value; + await this.plugin.saveSettings(); + })); + + new Setting(section) + .setName('Base URL') + .setDesc('DeepSeek API 地址') + .addText((text: TextComponent) => text + .setPlaceholder('https://api.deepseek.com/v1') + .setValue(this.plugin.settings.deepseekBaseUrl) + .onChange(async (value: string) => { + this.plugin.settings.deepseekBaseUrl = value; + await this.plugin.saveSettings(); + })); + + new Setting(section) + .setName('模型') + .setDesc('使用的 DeepSeek 模型') + .addText((text: TextComponent) => text + .setPlaceholder('deepseek-chat') + .setValue(this.plugin.settings.deepseekModel) + .onChange(async (value: string) => { + this.plugin.settings.deepseekModel = value; + await this.plugin.saveSettings(); + })); + } + + // 渲染智谱清言配置 + renderZhipuConfig(container: HTMLElement): void { + const section = container.createEl('div', { cls: 'wa-api-section' }); + + new Setting(section) + .setName('API Key') + .setDesc('你的智谱清言 API Key(从 https://open.bigmodel.cn 获取)') + .addText((text: TextComponent) => text + .setPlaceholder('请填入你的智谱清言 API Key') + .setValue(this.plugin.settings.zhipuApiKey) + .onChange(async (value: string) => { + this.plugin.settings.zhipuApiKey = value; + await this.plugin.saveSettings(); + })); + + new Setting(section) + .setName('模型') + .setDesc('使用的智谱清言模型') + .addDropdown((dropdown: DropdownComponent) => { + dropdown + + // 新一代旗舰系列 - 适合复杂长文/编程任务 + .addOption('glm-5.2', 'GLM-5.2 (长程专家)') + .addOption('glm-5.1', 'GLM-5.1 (持续工作者)') + .addOption('glm-5', 'GLM-5 (全能助手)') + // 免费版 - 推荐日常使用 + .addOption('glm-4.7-flash', 'GLM-4.7-Flash (免费推荐)') + // 基础付费版 + .addOption('glm-4.7', 'GLM-4.7(编程旗舰)') + .addOption('glm-4', 'GLM-4(速度最快)') + .setValue(this.plugin.settings.zhipuModel) + .onChange(async (value: string) => { + this.plugin.settings.zhipuModel = value; + await this.plugin.saveSettings(); + }); + }); + } + + // 渲染功能列表 + renderFunctionList(containerEl: HTMLElement): void { + const funcTitle = containerEl.createEl('h3', { text: '功能列表' }); + funcTitle.style.marginLeft = '0'; + funcTitle.style.paddingLeft = '0'; + funcTitle.style.marginTop = '24px'; + + containerEl.createEl('p', { + text: '这些功能会出现在右键菜单中', + cls: 'wa-settings-desc' + }); + + this.plugin.settings.actions.forEach((action, index) => { + const wrapper = containerEl.createEl('div', { cls: 'wa-action-wrapper' }); + + const header = wrapper.createEl('div', { cls: 'wa-action-header' }); + const summary = header.createEl('span', { cls: 'wa-action-summary' }); + summary.setText(`${action.icon} ${action.name}`); + + const toggleBtn = header.createEl('button', { + text: '展开', + cls: 'wa-toggle-btn' + }); + + const body = wrapper.createEl('div', { cls: 'wa-action-body' }); + body.style.display = 'none'; + + let expanded = false; + toggleBtn.addEventListener('click', () => { + expanded = !expanded; + body.style.display = expanded ? 'block' : 'none'; + toggleBtn.textContent = expanded ? '收起' : '展开'; + }); + + const nameSetting = new Setting(body) + .setName('名称') + .addText((text: TextComponent) => text + .setValue(action.name) + .onChange(async (value: string) => { + this.plugin.settings.actions[index].name = value; + await this.plugin.saveSettings(); + summary.setText(`${this.plugin.settings.actions[index].icon} ${value}`); + })); + nameSetting.settingEl.style.borderTop = 'none'; + nameSetting.settingEl.style.background = 'transparent'; + + const iconSetting = new Setting(body) + .setName('图标') + .addText((text: TextComponent) => text + .setValue(action.icon) + .onChange(async (value: string) => { + this.plugin.settings.actions[index].icon = value; + await this.plugin.saveSettings(); + summary.setText(`${value} ${this.plugin.settings.actions[index].name}`); + })); + iconSetting.settingEl.style.borderTop = 'none'; + iconSetting.settingEl.style.background = 'transparent'; + + const promptSetting = new Setting(body) + .setName('系统提示词') + .setDesc('AI 处理时的指令') + .addTextArea((text: TextAreaComponent) => text + .setValue(action.prompt) + .onChange(async (value: string) => { + this.plugin.settings.actions[index].prompt = value; + await this.plugin.saveSettings(); + })); + promptSetting.settingEl.style.borderTop = 'none'; + promptSetting.settingEl.style.background = 'transparent'; + + const deleteSetting = new Setting(body) + .addButton(btn => btn + .setButtonText('删除') + .setWarning() + .onClick(async () => { + this.plugin.settings.actions.splice(index, 1); + await this.plugin.saveSettings(); + this.display(); + })); + deleteSetting.settingEl.style.borderTop = 'none'; + deleteSetting.settingEl.style.background = 'transparent'; + }); + + const addBtnContainer = containerEl.createEl('div', { + cls: 'wa-add-btn-container' + }); + addBtnContainer.style.display = 'flex'; + addBtnContainer.style.justifyContent = 'center'; + addBtnContainer.style.marginTop = '12px'; + + const addBtn = addBtnContainer.createEl('button', { + text: '添加新功能', + cls: 'mod-cta' + }); + addBtn.style.padding = '6px 24px'; + addBtn.style.cursor = 'pointer'; + addBtn.style.borderRadius = '4px'; + addBtn.style.border = 'none'; + addBtn.style.background = 'var(--interactive-accent)'; + addBtn.style.color = 'var(--text-on-accent)'; + addBtn.addEventListener('click', () => { + this.plugin.settings.actions.push({ + id: `custom-${Date.now()}`, + name: '新功能', + icon: '📌', + prompt: '请输入你的系统提示词...' + }); + this.plugin.saveSettings(); + this.display(); + }); + } +} \ No newline at end of file diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..c9bd597 --- /dev/null +++ b/styles.css @@ -0,0 +1,317 @@ +/* ===== 侧边栏对话样式 ===== */ +.chat-container { + display: flex; + flex-direction: column; + height: 100%; + padding: 12px; + gap: 10px; + font-size: 14px; + background: var(--background-primary); +} + +.chat-header { + display: flex; + justify-content: space-between; + align-items: center; + padding-bottom: 10px; + border-bottom: 1px solid var(--background-modifier-border); +} + +.chat-header h4 { + margin: 0; + font-size: 15px; + font-weight: 600; + color: var(--text-normal); +} + +.chat-header-actions { + display: flex; + gap: 6px; +} + +.chat-clear-btn { + background: none; + border: none; + color: var(--text-muted); + cursor: pointer; + font-size: 13px; + padding: 4px 10px; + border-radius: 4px; + transition: all 0.2s; +} + +.chat-clear-btn:hover { + background: var(--background-modifier-hover); + color: var(--text-error); +} + +.chat-messages { + flex: 1; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 12px; + padding: 4px 0; + min-height: 200px; + max-height: 500px; +} + +.chat-messages::-webkit-scrollbar { + width: 4px; +} + +.chat-messages::-webkit-scrollbar-track { + background: var(--background-secondary); + border-radius: 4px; +} + +.chat-messages::-webkit-scrollbar-thumb { + background: var(--background-modifier-border); + border-radius: 4px; +} + +.chat-empty { + color: var(--text-muted); + text-align: center; + padding: 40px 16px; + white-space: pre-line; + font-size: 13px; + line-height: 1.8; +} + +.chat-message { + padding: 10px 14px; + border-radius: 10px; + max-width: 92%; + animation: fadeIn 0.25s ease; + word-wrap: break-word; + user-select: text !important; + -webkit-user-select: text !important; +} + +.chat-message.user { + background: var(--background-secondary); + align-self: flex-end; + border-bottom-right-radius: 4px; +} + +.chat-message.assistant { + background: var(--background-primary-alt); + align-self: flex-start; + border-bottom-left-radius: 4px; + border: 1px solid var(--background-modifier-border); +} + +.chat-message-label { + font-size: 11px; + font-weight: 600; + color: var(--text-muted); + margin-bottom: 4px; + letter-spacing: 0.3px; +} + +.chat-message-content { + word-break: break-word; + line-height: 1.7; + font-size: 14px; + color: var(--text-normal); + user-select: text !important; + -webkit-user-select: text !important; + cursor: text; +} + +.chat-message-content * { + user-select: text !important; + -webkit-user-select: text !important; +} + +.chat-message-content code { + background: var(--background-secondary); + padding: 1px 6px; + border-radius: 3px; + font-size: 13px; + font-family: var(--font-monospace); +} + +.chat-message-content pre { + background: var(--background-secondary); + padding: 10px 12px; + border-radius: 6px; + overflow-x: auto; + margin: 6px 0; +} + +.chat-message-content pre code { + background: none; + padding: 0; +} + +.chat-btn-group { + display: flex; + gap: 6px; + margin-top: 8px; + flex-wrap: wrap; +} + +.chat-action-btn { + padding: 3px 12px; + font-size: 12px; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-muted); + cursor: pointer; + transition: all 0.2s; + user-select: none; + -webkit-user-select: none; +} + +.chat-action-btn:hover { + background: var(--interactive-accent); + color: var(--text-on-accent); + border-color: var(--interactive-accent); +} + +.chat-input-section { + border-top: 1px solid var(--background-modifier-border); + padding-top: 10px; +} + +.chat-input-row { + display: flex; + gap: 8px; + align-items: flex-end; +} + +.chat-input { + flex: 1; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 8px; + padding: 10px 12px; + font-size: 13px; + font-family: inherit; + resize: none; + min-height: 36px; + max-height: 120px; + color: var(--text-normal); + transition: border-color 0.2s; + line-height: 1.6; +} + +.chat-input:focus { + outline: none; + border-color: var(--interactive-accent); + box-shadow: 0 0 0 2px var(--interactive-accent-hover); +} + +.chat-input:disabled { + opacity: 0.6; + cursor: not-allowed; +} + +@keyframes fadeIn { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} + +/* ===== 设置页面样式 ===== */ +.wa-settings-desc { + margin: 0 0 16px 0; + color: var(--text-muted); + font-size: 14px; +} + +.wa-action-wrapper { + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + margin: 8px 0; + overflow: hidden; +} + +.wa-action-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 14px; + cursor: default; + background: transparent; +} + +.wa-action-summary { + font-weight: 500; + font-size: 14px; + color: var(--text-normal); +} + +.wa-toggle-btn { + background: none; + border: none; + color: var(--text-muted); + cursor: pointer; + font-size: 12px; + padding: 2px 10px; + border-radius: 4px; + transition: all 0.2s; +} + +.wa-toggle-btn:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} + +.wa-action-body { + padding: 0 14px 14px 14px; + border-top: 1px solid var(--background-modifier-border); + background: transparent; +} + +.wa-action-body .setting-item { + border-top: none !important; + padding: 10px 0 !important; + background: transparent !important; +} + +.wa-action-body .setting-item:first-child { + padding-top: 14px !important; +} + +.wa-action-body .setting-item:last-child { + padding-bottom: 0 !important; +} + +.wa-action-body .setting-item .setting-item-info { + flex: 1 1 auto; + background: transparent !important; +} + +.wa-action-body .setting-item .setting-item-control { + flex: 2 1 auto; + background: transparent !important; +} + +/* ===== 系统提示词输入框放大 ===== */ +.wa-action-body .setting-item .setting-item-control textarea { + min-height: 80px; + width: 100%; +} + +/* ===== 添加新功能按钮容器 ===== */ +.wa-add-btn-container { + display: flex; + justify-content: center; + margin-top: 12px; +} + +.wa-add-btn-container .mod-cta { + padding: 6px 24px; + cursor: pointer; + border-radius: 4px; + border: none; + background: var(--interactive-accent); + color: var(--text-on-accent); +} + +.wa-add-btn-container .mod-cta:hover { + background: var(--interactive-accent-hover); +} \ No newline at end of file