unify import/export icons on prompt manager

This commit is contained in:
RossAscends 2023-08-20 03:54:30 +09:00
parent 93cb3bfee3
commit 4fe74f0041
1 changed files with 61 additions and 60 deletions

View File

@ -1,7 +1,7 @@
import {callPopup, event_types, eventSource, is_send_press, main_api, substituteParams} from "../script.js";
import { callPopup, event_types, eventSource, is_send_press, main_api, substituteParams } from "../script.js";
import { is_group_generating } from "./group-chats.js";
import {TokenHandler} from "./openai.js";
import {power_user} from "./power-user.js";
import { TokenHandler } from "./openai.js";
import { power_user } from "./power-user.js";
import { debounce, waitUntilCondition } from "./utils.js";
function debouncePromise(func, delay) {
@ -70,7 +70,7 @@ class Prompt {
* @param {string} param0.name - The name of the prompt.
* @param {boolean} param0.system_prompt - Indicates if the prompt is a system prompt.
*/
constructor({identifier, role, content, name, system_prompt} = {}) {
constructor({ identifier, role, content, name, system_prompt } = {}) {
this.identifier = identifier;
this.role = role;
this.content = content;
@ -101,8 +101,8 @@ class PromptCollection {
* @throws Will throw an error if one or more instances are not of the Prompt class.
*/
checkPromptInstance(...prompts) {
for(let prompt of prompts) {
if(!(prompt instanceof Prompt)) {
for (let prompt of prompts) {
if (!(prompt instanceof Prompt)) {
throw new Error('Only Prompt instances can be added to PromptCollection');
}
}
@ -250,7 +250,7 @@ function PromptManagerModule() {
this.handleCharacterExport = () => { };
/** Character reset button click*/
this.handleCharacterReset = () => {};
this.handleCharacterReset = () => { };
/** Debounced version of render */
this.renderDebounced = debounce(this.render.bind(this), 1000);
@ -382,7 +382,7 @@ PromptManagerModule.prototype.init = function (moduleConfiguration, serviceSetti
const promptID = document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt').value;
const prompt = this.getPromptById(promptID);
if (prompt){
if (prompt) {
this.appendPrompt(prompt, this.activeCharacter);
this.saveServiceSettings().then(() => this.render());
}
@ -390,7 +390,7 @@ PromptManagerModule.prototype.init = function (moduleConfiguration, serviceSetti
// Delete selected prompt from list form and close edit form
this.handleDeletePrompt = (event) => {
const promptID = document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt').value;
const promptID = document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt').value;
const prompt = this.getPromptById(promptID);
if (prompt && true === this.isPromptDeletionAllowed(prompt)) {
@ -427,7 +427,7 @@ PromptManagerModule.prototype.init = function (moduleConfiguration, serviceSetti
let promptOrder = [];
if ('global' === this.configuration.promptOrder.strategy) {
promptOrder = this.getPromptOrderForCharacter({id: this.configuration.promptOrder.dummyId});
promptOrder = this.getPromptOrderForCharacter({ id: this.configuration.promptOrder.dummyId });
} else if ('character' === this.configuration.promptOrder.strategy) {
promptOrder = [];
} else {
@ -490,10 +490,10 @@ PromptManagerModule.prototype.init = function (moduleConfiguration, serviceSetti
};
reader.readAsText(file);
});
});
fileOpener.click();
});
fileOpener.click();
});
}
// Restore default state of a characters prompt order
@ -556,7 +556,7 @@ PromptManagerModule.prototype.init = function (moduleConfiguration, serviceSetti
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_save').addEventListener('click', this.handleSavePrompt);
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_reset').addEventListener('click', this.handleResetPrompt);
const closeAndClearPopup = () => {
const closeAndClearPopup = () => {
this.hidePopup();
this.clearEditForm();
this.clearInspectForm();
@ -652,7 +652,7 @@ PromptManagerModule.prototype.updatePrompts = function (prompts) {
})
}
PromptManagerModule.prototype.getTokenHandler = function() {
PromptManagerModule.prototype.getTokenHandler = function () {
return this.tokenHandler;
}
@ -666,7 +666,7 @@ PromptManagerModule.prototype.appendPrompt = function (prompt, character) {
const promptOrder = this.getPromptOrderForCharacter(character);
const index = promptOrder.findIndex(entry => entry.identifier === prompt.identifier);
if (-1 === index) promptOrder.push({identifier: prompt.identifier, enabled: false});
if (-1 === index) promptOrder.push({ identifier: prompt.identifier, enabled: false });
}
/**
@ -713,7 +713,7 @@ PromptManagerModule.prototype.sanitizeServiceSettings = function () {
this.serviceSettings.prompt_order = this.serviceSettings.prompt_order ?? [];
if ('global' === this.configuration.promptOrder.strategy) {
const dummyCharacter = {id: this.configuration.promptOrder.dummyId};
const dummyCharacter = { id: this.configuration.promptOrder.dummyId };
const promptOrder = this.getPromptOrderForCharacter(dummyCharacter);
if (0 === promptOrder.length) this.addPromptOrderForCharacter(dummyCharacter, promptManagerDefaultPromptOrder);
@ -729,11 +729,11 @@ PromptManagerModule.prototype.sanitizeServiceSettings = function () {
if (this.activeCharacter) {
const promptReferences = this.getPromptOrderForCharacter(this.activeCharacter);
for(let i = promptReferences.length - 1; i >= 0; i--) {
const reference = promptReferences[i];
if(-1 === this.serviceSettings.prompts.findIndex(prompt => prompt.identifier === reference.identifier)) {
for (let i = promptReferences.length - 1; i >= 0; i--) {
const reference = promptReferences[i];
if (-1 === this.serviceSettings.prompts.findIndex(prompt => prompt.identifier === reference.identifier)) {
promptReferences.splice(i, 1);
this.log('Removed unused reference: ' + reference.identifier);
this.log('Removed unused reference: ' + reference.identifier);
}
}
}
@ -745,11 +745,11 @@ PromptManagerModule.prototype.sanitizeServiceSettings = function () {
*
* @param prompts
*/
PromptManagerModule.prototype.checkForMissingPrompts = function(prompts) {
const defaultPromptIdentifiers = chatCompletionDefaultPrompts.prompts.reduce((list, prompt) => { list.push(prompt.identifier); return list;}, []);
PromptManagerModule.prototype.checkForMissingPrompts = function (prompts) {
const defaultPromptIdentifiers = chatCompletionDefaultPrompts.prompts.reduce((list, prompt) => { list.push(prompt.identifier); return list; }, []);
const missingIdentifiers = defaultPromptIdentifiers.filter(identifier =>
!prompts.some(prompt =>prompt.identifier === identifier)
!prompts.some(prompt => prompt.identifier === identifier)
);
missingIdentifiers.forEach(identifier => {
@ -815,10 +815,10 @@ PromptManagerModule.prototype.handleCharacterDeleted = function (event) {
*/
PromptManagerModule.prototype.handleCharacterSelected = function (event) {
if ('global' === this.configuration.promptOrder.strategy) {
this.activeCharacter = {id: this.configuration.promptOrder.dummyId};
} else if ('character' === this.configuration.promptOrder.strategy) {
this.activeCharacter = { id: this.configuration.promptOrder.dummyId };
} else if ('character' === this.configuration.promptOrder.strategy) {
console.log('FOO')
this.activeCharacter = {id: event.detail.id, ...event.detail.character};
this.activeCharacter = { id: event.detail.id, ...event.detail.character };
const promptOrder = this.getPromptOrderForCharacter(this.activeCharacter);
// ToDo: These should be passed as parameter or attached to the manager as a set of default options.
@ -836,11 +836,11 @@ PromptManagerModule.prototype.handleCharacterSelected = function (event) {
*/
PromptManagerModule.prototype.handleCharacterUpdated = function (event) {
if ('global' === this.configuration.promptOrder.strategy) {
this.activeCharacter = {id: this.configuration.promptOrder.dummyId};
this.activeCharacter = { id: this.configuration.promptOrder.dummyId };
} else if ('character' === this.configuration.promptOrder.strategy) {
this.activeCharacter = {id: event.detail.id, ...event.detail.character};
this.activeCharacter = { id: event.detail.id, ...event.detail.character };
} else {
throw new Error ('Prompt order strategy not supported.')
throw new Error('Prompt order strategy not supported.')
}
}
@ -851,15 +851,15 @@ PromptManagerModule.prototype.handleCharacterUpdated = function (event) {
*/
PromptManagerModule.prototype.handleGroupSelected = function (event) {
if ('global' === this.configuration.promptOrder.strategy) {
this.activeCharacter = {id: this.configuration.promptOrder.dummyId};
this.activeCharacter = { id: this.configuration.promptOrder.dummyId };
} else if ('character' === this.configuration.promptOrder.strategy) {
const characterDummy = {id: event.detail.id, group: event.detail.group};
const characterDummy = { id: event.detail.id, group: event.detail.group };
this.activeCharacter = characterDummy;
const promptOrder = this.getPromptOrderForCharacter(characterDummy);
if (0 === promptOrder.length) this.addPromptOrderForCharacter(characterDummy, promptManagerDefaultPromptOrder)
} else {
throw new Error ('Prompt order strategy not supported.')
throw new Error('Prompt order strategy not supported.')
}
}
@ -868,7 +868,7 @@ PromptManagerModule.prototype.handleGroupSelected = function (event) {
*
* @returns {string[]}
*/
PromptManagerModule.prototype.getActiveGroupCharacters = function() {
PromptManagerModule.prototype.getActiveGroupCharacters = function () {
// ToDo: Ideally, this should return the actual characters.
return (this.activeCharacter?.group?.members || []).map(member => member && member.substring(0, member.lastIndexOf('.')));
}
@ -982,7 +982,7 @@ PromptManagerModule.prototype.preparePrompt = function (prompt, original = null)
* and handle input events to update the prompt content.
*
*/
PromptManagerModule.prototype.createQuickEdit = function(identifier, title) {
PromptManagerModule.prototype.createQuickEdit = function (identifier, title) {
const prompt = this.getPromptById(identifier);
const textareaIdentifier = `${identifier}_prompt_quick_edit_textarea`;
const html = `<div class="range-block m-t-1">
@ -1006,7 +1006,7 @@ PromptManagerModule.prototype.createQuickEdit = function(identifier, title) {
}
PromptManagerModule.prototype.updateQuickEdit = function(identifier, prompt) {
PromptManagerModule.prototype.updateQuickEdit = function (identifier, prompt) {
const textarea = document.getElementById(`${identifier}_prompt_quick_edit_textarea`);
textarea.value = prompt.content;
}
@ -1018,13 +1018,13 @@ PromptManagerModule.prototype.updateQuickEdit = function(identifier, prompt) {
* @param name
* @returns {boolean}
*/
PromptManagerModule.prototype.isValidName = function(name) {
PromptManagerModule.prototype.isValidName = function (name) {
const regex = /^[a-zA-Z0-9_]{1,64}$/;
return regex.test(name);
}
PromptManagerModule.prototype.sanitizeName = function(name) {
PromptManagerModule.prototype.sanitizeName = function (name) {
return name.replace(/[^a-zA-Z0-9_]/g, '_').substring(0, 64);
}
@ -1111,7 +1111,7 @@ PromptManagerModule.prototype.clearEditForm = function () {
roleField.disabled = false;
}
PromptManagerModule.prototype.clearInspectForm = function() {
PromptManagerModule.prototype.clearInspectForm = function () {
const inspectArea = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_inspect');
inspectArea.style.display = 'none';
const messageList = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_inspect_list');
@ -1150,7 +1150,7 @@ PromptManagerModule.prototype.setMessages = function (messages) {
*
* @param {ChatCompletion} chatCompletion
*/
PromptManagerModule.prototype.setChatCompletion = function(chatCompletion) {
PromptManagerModule.prototype.setChatCompletion = function (chatCompletion) {
const messages = chatCompletion.getMessages();
this.setMessages(messages);
@ -1163,7 +1163,7 @@ PromptManagerModule.prototype.setChatCompletion = function(chatCompletion) {
*
* @param {MessageCollection} messages
*/
PromptManagerModule.prototype.populateTokenCounts = function(messages) {
PromptManagerModule.prototype.populateTokenCounts = function (messages) {
this.tokenHandler.resetCounts();
const counts = this.tokenHandler.getCounts();
messages.getCollection().forEach(message => {
@ -1182,7 +1182,7 @@ PromptManagerModule.prototype.populateTokenCounts = function(messages) {
*
* @param {MessageCollection} messages
*/
PromptManagerModule.prototype.populateLegacyTokenCounts = function(messages) {
PromptManagerModule.prototype.populateLegacyTokenCounts = function (messages) {
// Update general token counts
const chatHistory = messages.getItemByIdentifier('chatHistory');
const startChat = chatHistory?.getCollection()[0].getTokens() || 0;
@ -1246,8 +1246,8 @@ PromptManagerModule.prototype.renderPromptManager = function () {
</select>
<a class="menu_button fa-chain fa-solid" title="Insert prompt" data-i18n="Insert"></a>
<a class="caution menu_button fa-x fa-solid" title="Delete prompt" data-i18n="Delete"></a>
<a class="menu_button fa-file-arrow-down fa-solid" id="prompt-manager-export" title="Export this prompt list" data-i18n="Export"></a>
<a class="menu_button fa-file-arrow-up fa-solid" id="prompt-manager-import" title="Import a prompt list" data-i18n="Import"></a>
<a class="menu_button fa-file-import fa-solid" id="prompt-manager-import" title="Import a prompt list" data-i18n="Import"></a>
<a class="menu_button fa-file-export fa-solid" id="prompt-manager-export" title="Export this prompt list" data-i18n="Export"></a>
<a class="menu_button fa-undo fa-solid" id="prompt-manager-reset-character" title="Reset current character" data-i18n="Reset current character"></a>
<a class="menu_button fa-plus-square fa-solid" title="New prompt" data-i18n="New"></a>
</div>
@ -1270,9 +1270,9 @@ PromptManagerModule.prototype.renderPromptManager = function () {
<a class="export-promptmanager-prompts-full list-group-item" data-i18n="Export all">Export all</a>
<span class="tooltip fa-solid fa-info-circle" title="Export all your prompts to a file"></span>
</div>
${ 'global' === this.configuration.promptOrder.strategy
? ''
: `<div class="row">
${'global' === this.configuration.promptOrder.strategy
? ''
: `<div class="row">
<a class="export-promptmanager-prompts-character list-group-item" data-i18n="Export for character">Export
for character</a>
<span class="tooltip fa-solid fa-info-circle"
@ -1287,7 +1287,7 @@ PromptManagerModule.prototype.renderPromptManager = function () {
let exportPopper = Popper.createPopper(
document.getElementById('prompt-manager-export'),
document.getElementById('prompt-manager-export-format-popup'),
{placement: 'bottom'}
{ placement: 'bottom' }
);
const showExportSelection = () => {
@ -1323,7 +1323,7 @@ PromptManagerModule.prototype.renderPromptManagerListItems = function () {
const promptManagerList = this.listElement;
promptManagerList.innerHTML = '';
const {prefix} = this.configuration;
const { prefix } = this.configuration;
let listItemHtml = `
<li class="${prefix}prompt_manager_list_head">
@ -1350,7 +1350,7 @@ PromptManagerModule.prototype.renderPromptManagerListItems = function () {
let warningTitle = '';
const tokenBudget = this.serviceSettings.openai_max_context - this.serviceSettings.openai_max_tokens;
if ( this.tokenUsage > tokenBudget * 0.8 &&
if (this.tokenUsage > tokenBudget * 0.8 &&
'chatHistory' === prompt.identifier) {
const warningThreshold = this.configuration.warningTokenThreshold;
const dangerThreshold = this.configuration.dangerTokenThreshold;
@ -1399,7 +1399,7 @@ PromptManagerModule.prototype.renderPromptManagerListItems = function () {
${prompt.marker ? '<span class="fa-solid fa-thumb-tack" title="Marker"></span>' : ''}
${!prompt.marker && prompt.system_prompt ? '<span class="fa-solid fa-square-poll-horizontal" title="Global Prompt"></span>' : ''}
${!prompt.marker && !prompt.system_prompt ? '<span class="fa-solid fa-user" title="User Prompt"></span>' : ''}
${this.isPromptInspectionAllowed(prompt) ? `<a class="prompt-manager-inspect-action">${prompt.name}</a>` : prompt.name }
${this.isPromptInspectionAllowed(prompt) ? `<a class="prompt-manager-inspect-action">${prompt.name}</a>` : prompt.name}
</span>
<span>
<span class="prompt_manager_prompt_controls">
@ -1449,7 +1449,7 @@ PromptManagerModule.prototype.export = function (data, type, name = 'export') {
};
const serializedObject = JSON.stringify(promptExport);
const blob = new Blob([serializedObject], {type: "application/json"});
const blob = new Blob([serializedObject], { type: "application/json" });
const url = URL.createObjectURL(blob);
const downloadLink = document.createElement('a');
downloadLink.href = url;
@ -1502,7 +1502,7 @@ PromptManagerModule.prototype.import = function (importData) {
let promptOrder = [];
if ('global' === this.configuration.promptOrder.strategy) {
const promptOrder = this.getPromptOrderForCharacter({id: this.configuration.promptOrder.dummyId});
const promptOrder = this.getPromptOrderForCharacter({ id: this.configuration.promptOrder.dummyId });
Object.assign(promptOrder, importData.data.prompt_order);
this.log(`Prompt order import succeeded`);
} else if ('character' === this.configuration.promptOrder.strategy) {
@ -1526,7 +1526,7 @@ PromptManagerModule.prototype.import = function (importData) {
* @param object
* @returns {boolean}
*/
PromptManagerModule.prototype.validateObject = function(controlObj, object) {
PromptManagerModule.prototype.validateObject = function (controlObj, object) {
for (let key in controlObj) {
if (!object.hasOwnProperty(key)) {
if (controlObj[key] === null) continue;
@ -1549,7 +1549,7 @@ PromptManagerModule.prototype.validateObject = function(controlObj, object) {
*
* @returns {`${string}_${string}_${string}`}
*/
PromptManagerModule.prototype.getFormattedDate = function() {
PromptManagerModule.prototype.getFormattedDate = function () {
const date = new Date();
let month = String(date.getMonth() + 1);
let day = String(date.getDate());
@ -1571,9 +1571,9 @@ PromptManagerModule.prototype.makeDraggable = function () {
$(`#${this.configuration.prefix}prompt_manager_list`).sortable({
delay: this.configuration.sortableDelay,
items: `.${this.configuration.prefix}prompt_manager_prompt_draggable`,
update: ( event, ui ) => {
update: (event, ui) => {
const promptOrder = this.getPromptOrderForCharacter(this.activeCharacter);
const promptListElement = $(`#${this.configuration.prefix}prompt_manager_list`).sortable('toArray', {attribute: 'data-pm-identifier'});
const promptListElement = $(`#${this.configuration.prefix}prompt_manager_list`).sortable('toArray', { attribute: 'data-pm-identifier' });
const idToObjectMap = new Map(promptOrder.map(prompt => [prompt.identifier, prompt]));
const updatedPromptOrder = promptListElement.map(identifier => idToObjectMap.get(identifier));
@ -1583,7 +1583,8 @@ PromptManagerModule.prototype.makeDraggable = function () {
this.log(`Prompt order updated for ${this.activeCharacter.name}.`);
this.saveServiceSettings();
}});
}
});
};
/**
@ -1594,7 +1595,7 @@ PromptManagerModule.prototype.showPopup = function (area = 'edit') {
const areaElement = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_' + area);
areaElement.style.display = 'block';
$('#'+this.configuration.prefix +'prompt_manager_popup').first()
$('#' + this.configuration.prefix + 'prompt_manager_popup').first()
.slideDown(200, "swing")
.addClass('openDrawer');
}
@ -1604,7 +1605,7 @@ PromptManagerModule.prototype.showPopup = function (area = 'edit') {
* @returns {void}
*/
PromptManagerModule.prototype.hidePopup = function () {
$('#'+this.configuration.prefix +'prompt_manager_popup').first()
$('#' + this.configuration.prefix + 'prompt_manager_popup').first()
.slideUp(200, "swing")
.removeClass('openDrawer');
}