refractor: dont import chatEntry into each api

This commit is contained in:
end-4
2025-04-03 16:41:37 +02:00
parent 98fd391b88
commit c03d24741d
5 changed files with 78 additions and 80 deletions
+3 -4
View File
@@ -8,7 +8,6 @@ import { MaterialIcon } from '../../.commonwidgets/materialicon.js';
import { MarginRevealer } from '../../.widgethacks/advancedrevealers.js'; import { MarginRevealer } from '../../.widgethacks/advancedrevealers.js';
import { setupCursorHover, setupCursorHoverInfo } from '../../.widgetutils/cursorhover.js'; import { setupCursorHover, setupCursorHoverInfo } from '../../.widgetutils/cursorhover.js';
import BooruService from '../../../services/booru.js'; import BooruService from '../../../services/booru.js';
import { chatEntry } from '../apiwidgets.js';
import { ConfigToggle } from '../../.commonwidgets/configwidgets.js'; import { ConfigToggle } from '../../.commonwidgets/configwidgets.js';
import { SystemMessage } from './ai_chatmessage.js'; import { SystemMessage } from './ai_chatmessage.js';
@@ -19,7 +18,7 @@ const USER_CACHE_DIR = GLib.get_user_cache_dir();
Utils.exec(`bash -c 'mkdir -p ${USER_CACHE_DIR}/ags/media/waifus'`); Utils.exec(`bash -c 'mkdir -p ${USER_CACHE_DIR}/ags/media/waifus'`);
Utils.exec(`bash -c 'rm ${USER_CACHE_DIR}/ags/media/waifus/*'`); Utils.exec(`bash -c 'rm ${USER_CACHE_DIR}/ags/media/waifus/*'`);
const TagButton = (command) => Button({ const TagButton = (command, chatEntry) => Button({
className: 'sidebar-chat-chip sidebar-chat-chip-action txt txt-small', className: 'sidebar-chat-chip sidebar-chat-chip-action txt txt-small',
onClicked: () => { chatEntry.buffer.text += `${command} ` }, onClicked: () => { chatEntry.buffer.text += `${command} ` },
setup: setupCursorHover, setup: setupCursorHover,
@@ -453,7 +452,7 @@ const booruContent = Box({
, ,
}); });
export const booruView = Scrollable({ export const BooruView = (chatEntry) => Scrollable({
className: 'sidebar-chat-viewport', className: 'sidebar-chat-viewport',
vexpand: true, vexpand: true,
child: Box({ child: Box({
@@ -533,7 +532,7 @@ const clearChat = () => { // destroy!!
}); });
} }
export const sendMessage = (text) => { export const sendMessage = (text, booruView) => {
// Commands // Commands
if (text.startsWith('+')) { // Next page if (text.startsWith('+')) { // Next page
const lastQuery = BooruService.queries.at(-1); const lastQuery = BooruService.queries.at(-1);
+8 -10
View File
@@ -1,5 +1,4 @@
const { Gtk } = imports.gi; const { Gtk } = imports.gi;
import App from 'resource:///com/github/Aylur/ags/app.js';
import Widget from 'resource:///com/github/Aylur/ags/widget.js'; import Widget from 'resource:///com/github/Aylur/ags/widget.js';
import * as Utils from 'resource:///com/github/Aylur/ags/utils.js'; import * as Utils from 'resource:///com/github/Aylur/ags/utils.js';
@@ -11,7 +10,6 @@ import { ConfigToggle, ConfigSegmentedSelection, ConfigGap } from '../../.common
import { markdownTest } from '../../.miscutils/md2pango.js'; import { markdownTest } from '../../.miscutils/md2pango.js';
import { MarginRevealer } from '../../.widgethacks/advancedrevealers.js'; import { MarginRevealer } from '../../.widgethacks/advancedrevealers.js';
import { MaterialIcon } from '../../.commonwidgets/materialicon.js'; import { MaterialIcon } from '../../.commonwidgets/materialicon.js';
import { chatEntry } from '../apiwidgets.js';
export const chatGPTTabIcon = Icon({ export const chatGPTTabIcon = Icon({
hpack: 'center', hpack: 'center',
@@ -280,19 +278,19 @@ export const sendMessage = (text) => {
if (text.length == 0) return; if (text.length == 0) return;
if (GPTService.key.length == 0) { if (GPTService.key.length == 0) {
GPTService.key = text; GPTService.key = text;
chatContent.add(SystemMessage(`Key saved to\n\`${GPTService.keyPath}\``, 'API Key', chatGPTView)); chatContent.add(SystemMessage(`Key saved to\n\`${GPTService.keyPath}\``, 'API Key', ChatGPTView));
text = ''; text = '';
return; return;
} }
// Commands // Commands
if (text.startsWith('/')) { if (text.startsWith('/')) {
if (text.startsWith('/clear')) clearChat(); if (text.startsWith('/clear')) clearChat();
else if (text.startsWith('/model')) chatContent.add(SystemMessage(`${getString("Currently using")} \`${GPTService.modelName}\``, '/model', chatGPTView)) else if (text.startsWith('/model')) chatContent.add(SystemMessage(`${getString("Currently using")} \`${GPTService.modelName}\``, '/model', ChatGPTView))
else if (text.startsWith('/prompt')) { else if (text.startsWith('/prompt')) {
const firstSpaceIndex = text.indexOf(' '); const firstSpaceIndex = text.indexOf(' ');
const prompt = text.slice(firstSpaceIndex + 1); const prompt = text.slice(firstSpaceIndex + 1);
if (firstSpaceIndex == -1 || prompt.length < 1) { if (firstSpaceIndex == -1 || prompt.length < 1) {
chatContent.add(SystemMessage(`Usage: \`/prompt MESSAGE\``, '/prompt', chatGPTView)) chatContent.add(SystemMessage(`Usage: \`/prompt MESSAGE\``, '/prompt', ChatGPTView))
} }
else { else {
GPTService.addMessage('user', prompt) GPTService.addMessage('user', prompt)
@@ -303,23 +301,23 @@ export const sendMessage = (text) => {
if (parts.length == 1) chatContent.add(SystemMessage( if (parts.length == 1) chatContent.add(SystemMessage(
`${getString("Key stored in:")}\n\`${GPTService.keyPath}\`\n${getString("To update this key, type")} \`/key YOUR_API_KEY\``, `${getString("Key stored in:")}\n\`${GPTService.keyPath}\`\n${getString("To update this key, type")} \`/key YOUR_API_KEY\``,
'/key', '/key',
chatGPTView)); ChatGPTView));
else { else {
GPTService.key = parts[1]; GPTService.key = parts[1];
chatContent.add(SystemMessage(`${getString("Updated API Key at")}\n\`${GPTService.keyPath}\``, '/key', chatGPTView)); chatContent.add(SystemMessage(`${getString("Updated API Key at")}\n\`${GPTService.keyPath}\``, '/key', ChatGPTView));
} }
} }
else if (text.startsWith('/test')) else if (text.startsWith('/test'))
chatContent.add(SystemMessage(markdownTest, `Markdown test`, chatGPTView)); chatContent.add(SystemMessage(markdownTest, `Markdown test`, ChatGPTView));
else else
chatContent.add(SystemMessage(getString("Invalid command."), 'Error', chatGPTView)) chatContent.add(SystemMessage(getString("Invalid command."), 'Error', ChatGPTView))
} }
else { else {
GPTService.send(text); GPTService.send(text);
} }
} }
export const chatGPTView = Box({ export const ChatGPTView = (chatEntry) => Box({
vertical: true, vertical: true,
children: [ children: [
ProviderSwitcher(), ProviderSwitcher(),
+8 -10
View File
@@ -1,5 +1,4 @@
const { Gtk } = imports.gi; const { Gtk } = imports.gi;
import App from 'resource:///com/github/Aylur/ags/app.js';
import Widget from 'resource:///com/github/Aylur/ags/widget.js'; import Widget from 'resource:///com/github/Aylur/ags/widget.js';
import * as Utils from 'resource:///com/github/Aylur/ags/utils.js'; import * as Utils from 'resource:///com/github/Aylur/ags/utils.js';
@@ -10,7 +9,6 @@ import { SystemMessage, ChatMessage } from "./ai_chatmessage.js";
import { ConfigToggle, ConfigSegmentedSelection, ConfigGap } from '../../.commonwidgets/configwidgets.js'; import { ConfigToggle, ConfigSegmentedSelection, ConfigGap } from '../../.commonwidgets/configwidgets.js';
import { markdownTest } from '../../.miscutils/md2pango.js'; import { markdownTest } from '../../.miscutils/md2pango.js';
import { MarginRevealer } from '../../.widgethacks/advancedrevealers.js'; import { MarginRevealer } from '../../.widgethacks/advancedrevealers.js';
import { chatEntry } from '../apiwidgets.js';
const MODEL_NAME = `Gemini`; const MODEL_NAME = `Gemini`;
@@ -212,7 +210,7 @@ export const sendMessage = (text) => {
if (text.length == 0) return; if (text.length == 0) return;
if (GeminiService.key.length == 0) { if (GeminiService.key.length == 0) {
GeminiService.key = text; GeminiService.key = text;
chatContent.add(SystemMessage(`Key saved to\n\`${GeminiService.keyPath}\``, 'API Key', geminiView)); chatContent.add(SystemMessage(`Key saved to\n\`${GeminiService.keyPath}\``, 'API Key', GeminiView));
text = ''; text = '';
return; return;
} }
@@ -223,12 +221,12 @@ export const sendMessage = (text) => {
clearChat(); clearChat();
GeminiService.loadHistory(); GeminiService.loadHistory();
} }
else if (text.startsWith('/model')) chatContent.add(SystemMessage(`${getString("Currently using")} \`${GeminiService.modelName}\``, '/model', geminiView)) else if (text.startsWith('/model')) chatContent.add(SystemMessage(`${getString("Currently using")} \`${GeminiService.modelName}\``, '/model', GeminiView))
else if (text.startsWith('/prompt')) { else if (text.startsWith('/prompt')) {
const firstSpaceIndex = text.indexOf(' '); const firstSpaceIndex = text.indexOf(' ');
const prompt = text.slice(firstSpaceIndex + 1); const prompt = text.slice(firstSpaceIndex + 1);
if (firstSpaceIndex == -1 || prompt.length < 1) { if (firstSpaceIndex == -1 || prompt.length < 1) {
chatContent.add(SystemMessage(`Usage: \`/prompt MESSAGE\``, '/prompt', geminiView)) chatContent.add(SystemMessage(`Usage: \`/prompt MESSAGE\``, '/prompt', GeminiView))
} }
else { else {
GeminiService.addMessage('user', prompt) GeminiService.addMessage('user', prompt)
@@ -239,23 +237,23 @@ export const sendMessage = (text) => {
if (parts.length == 1) chatContent.add(SystemMessage( if (parts.length == 1) chatContent.add(SystemMessage(
`${getString("Key stored in:")} \n\`${GeminiService.keyPath}\`\n${getString("To update this key, type")} \`/key YOUR_API_KEY\``, `${getString("Key stored in:")} \n\`${GeminiService.keyPath}\`\n${getString("To update this key, type")} \`/key YOUR_API_KEY\``,
'/key', '/key',
geminiView)); GeminiView));
else { else {
GeminiService.key = parts[1]; GeminiService.key = parts[1];
chatContent.add(SystemMessage(`${getString("Updated API Key at")}\n\`${GeminiService.keyPath}\``, '/key', geminiView)); chatContent.add(SystemMessage(`${getString("Updated API Key at")}\n\`${GeminiService.keyPath}\``, '/key', GeminiView));
} }
} }
else if (text.startsWith('/test')) else if (text.startsWith('/test'))
chatContent.add(SystemMessage(markdownTest, `Markdown test`, geminiView)); chatContent.add(SystemMessage(markdownTest, `Markdown test`, GeminiView));
else else
chatContent.add(SystemMessage(getString(`Invalid command.`), 'Error', geminiView)) chatContent.add(SystemMessage(getString(`Invalid command.`), 'Error', GeminiView))
} }
else { else {
GeminiService.send(text); GeminiService.send(text);
} }
} }
export const geminiView = Box({ export const GeminiView = (chatEntry) => Box({
homogeneous: true, homogeneous: true,
children: [Scrollable({ children: [Scrollable({
className: 'sidebar-chat-viewport', className: 'sidebar-chat-viewport',
+1 -2
View File
@@ -12,7 +12,6 @@ import { MarginRevealer } from '../../.widgethacks/advancedrevealers.js';
import { setupCursorHover, setupCursorHoverInfo } from '../../.widgetutils/cursorhover.js'; import { setupCursorHover, setupCursorHoverInfo } from '../../.widgetutils/cursorhover.js';
import WaifuService from '../../../services/waifus.js'; import WaifuService from '../../../services/waifus.js';
import { darkMode } from '../../.miscutils/system.js'; import { darkMode } from '../../.miscutils/system.js';
import { chatEntry } from '../apiwidgets.js';
async function getImageViewerApp(preferredApp) { async function getImageViewerApp(preferredApp) {
Utils.execAsync(['bash', '-c', `command -v ${preferredApp}`]) Utils.execAsync(['bash', '-c', `command -v ${preferredApp}`])
@@ -302,7 +301,7 @@ const waifuContent = Box({
, ,
}); });
export const waifuView = Scrollable({ export const WaifuView = (chatEntry) => Scrollable({
className: 'sidebar-chat-viewport', className: 'sidebar-chat-viewport',
vexpand: true, vexpand: true,
child: Box({ child: Box({
+58 -54
View File
@@ -7,10 +7,10 @@ import { setupCursorHover } from '../.widgetutils/cursorhover.js';
// APIs // APIs
import GPTService from '../../services/gpt.js'; import GPTService from '../../services/gpt.js';
import Gemini from '../../services/gemini.js'; import Gemini from '../../services/gemini.js';
import { geminiView, geminiCommands, sendMessage as geminiSendMessage, geminiTabIcon } from './apis/gemini.js'; import { GeminiView, geminiCommands, sendMessage as geminiSendMessage, geminiTabIcon } from './apis/gemini.js';
import { chatGPTView, chatGPTCommands, sendMessage as chatGPTSendMessage, chatGPTTabIcon } from './apis/chatgpt.js'; import { ChatGPTView, chatGPTCommands, sendMessage as chatGPTSendMessage, chatGPTTabIcon } from './apis/chatgpt.js';
import { waifuView, waifuCommands, sendMessage as waifuSendMessage, waifuTabIcon } from './apis/waifu.js'; import { WaifuView, waifuCommands, sendMessage as waifuSendMessage, waifuTabIcon } from './apis/waifu.js';
import { booruView, booruCommands, sendMessage as booruSendMessage, booruTabIcon } from './apis/booru.js'; import { BooruView, booruCommands, sendMessage as booruSendMessage, booruTabIcon } from './apis/booru.js';
import { enableClickthrough } from "../.widgetutils/clickthrough.js"; import { enableClickthrough } from "../.widgetutils/clickthrough.js";
import { checkKeybind } from '../.widgetutils/keybind.js'; import { checkKeybind } from '../.widgetutils/keybind.js';
const TextView = Widget.subclass(Gtk.TextView, "AgsTextView"); const TextView = Widget.subclass(Gtk.TextView, "AgsTextView");
@@ -19,56 +19,6 @@ import { widgetContent } from './sideleft.js';
import { IconTabContainer } from '../.commonwidgets/tabcontainer.js'; import { IconTabContainer } from '../.commonwidgets/tabcontainer.js';
const EXPAND_INPUT_THRESHOLD = 30; const EXPAND_INPUT_THRESHOLD = 30;
const APILIST = {
'gemini': {
name: 'Assistant (Gemini Pro)',
sendCommand: geminiSendMessage,
contentWidget: geminiView,
commandBar: geminiCommands,
tabIcon: geminiTabIcon,
placeholderText: getString('Message Gemini...'),
},
'gpt': {
name: 'Assistant (GPTs)',
sendCommand: chatGPTSendMessage,
contentWidget: chatGPTView,
commandBar: chatGPTCommands,
tabIcon: chatGPTTabIcon,
placeholderText: getString('Message the model...'),
},
'waifu': {
name: 'Waifus',
sendCommand: waifuSendMessage,
contentWidget: waifuView,
commandBar: waifuCommands,
tabIcon: waifuTabIcon,
placeholderText: getString('Enter tags'),
},
'booru': {
name: 'Booru',
sendCommand: booruSendMessage,
contentWidget: booruView,
commandBar: booruCommands,
tabIcon: booruTabIcon,
placeholderText: getString('Enter tags and/or page number'),
},
}
const APIS = userOptions.sidebar.pages.apis.order.map((apiName) => APILIST[apiName]);
let currentApiId = 0;
function apiSendMessage(textView) {
// Get text
const buffer = textView.get_buffer();
const [start, end] = buffer.get_bounds();
const text = buffer.get_text(start, end, true).trimStart();
if (!text || text.length == 0) return;
// Send
APIS[currentApiId].sendCommand(text)
// Reset
buffer.set_text("", -1);
chatEntryWrapper.toggleClassName('sidebar-chat-wrapper-extended', false);
chatEntry.set_valign(Gtk.Align.CENTER);
}
export const chatEntry = TextView({ export const chatEntry = TextView({
hexpand: true, hexpand: true,
@@ -117,6 +67,60 @@ export const chatEntry = TextView({
, ,
}); });
const APILIST = {
'gemini': {
name: 'Assistant (Gemini Pro)',
sendCommand: geminiSendMessage,
contentWidget: GeminiView(chatEntry),
commandBar: geminiCommands,
tabIcon: geminiTabIcon,
placeholderText: getString('Message Gemini...'),
},
'gpt': {
name: 'Assistant (GPTs)',
sendCommand: chatGPTSendMessage,
contentWidget: ChatGPTView(chatEntry),
commandBar: chatGPTCommands,
tabIcon: chatGPTTabIcon,
placeholderText: getString('Message the model...'),
},
'waifu': {
name: 'Waifus',
sendCommand: waifuSendMessage,
contentWidget: WaifuView(chatEntry),
commandBar: waifuCommands,
tabIcon: waifuTabIcon,
placeholderText: getString('Enter tags'),
},
'booru': {
name: 'Booru',
sendCommand: booruSendMessage,
contentWidget: BooruView(chatEntry),
commandBar: booruCommands,
tabIcon: booruTabIcon,
placeholderText: getString('Enter tags and/or page number'),
},
}
const APIS = userOptions.sidebar.pages.apis.order.map((apiName) => APILIST[apiName]);
let currentApiId = 0;
function apiSendMessage(textView) {
// Get text
const buffer = textView.get_buffer();
const [start, end] = buffer.get_bounds();
const text = buffer.get_text(start, end, true).trimStart();
if (!text || text.length == 0) return;
// Send
if (APIS[currentApiId].name == APILIST['booru'].name)
APIS[currentApiId].sendCommand(text, APILIST['booru'].contentWidget)
else
APIS[currentApiId].sendCommand(text)
// Reset
buffer.set_text("", -1);
chatEntryWrapper.toggleClassName('sidebar-chat-wrapper-extended', false);
chatEntry.set_valign(Gtk.Align.CENTER);
}
chatEntry.get_buffer().connect("changed", (buffer) => { chatEntry.get_buffer().connect("changed", (buffer) => {
const bufferText = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), true); const bufferText = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), true);
chatSendButton.toggleClassName('sidebar-chat-send-available', bufferText.length > 0); chatSendButton.toggleClassName('sidebar-chat-send-available', bufferText.length > 0);