back to working after merge,

formatting should match
fixed bug with send butting showing up midway through long pyg generations
optimized changeMainAPI function
This commit is contained in:
RossAsscends
2023-03-18 07:01:25 +09:00
parent 5f2c6b8853
commit bd60065e90
2 changed files with 572 additions and 556 deletions

View File

@ -363,7 +363,7 @@ function newMesPattern(name) {
////////////////////////////////////////// //////////////////////////////////////////
function checkOnlineStatus() { function checkOnlineStatus() {
///////// REMOVED LINES THAT DUPLICATE RA_CHeckOnlineStatus FEATURES ///////// REMOVED LINES THAT DUPLICATE RA_CHeckOnlineStatus FEATURES
if (online_status == "no_connection") { if (online_status == "no_connection") {
$("#online_status_indicator2").css("background-color", "red"); //Kobold $("#online_status_indicator2").css("background-color", "red"); //Kobold
@ -822,31 +822,31 @@ function addOneMessage(mes, type = "normal") {
var HTMLForEachMes = var HTMLForEachMes =
'<div class="mes" mesid="' + count_view_mes + '" ch_name="' + characterName + '" is_user="' + mes["is_user"] + '">' + '<div class="mes" mesid="' + count_view_mes + '" ch_name="' + characterName + '" is_user="' + mes["is_user"] + '">' +
'<div class="for_checkbox"></div>' + '<div class="for_checkbox"></div>' +
'<input type="checkbox" class="del_checkbox">' + '<input type="checkbox" class="del_checkbox">' +
'<div class="avatar">' + '<div class="avatar">' +
'<img src="' + avatarImg + '">' + '<img src="' + avatarImg + '">' +
'</div>' + '</div>' +
'<div class="swipe_left">' + '<div class="swipe_left">' +
'<img src="img/swipe_left.png">' + '<img src="img/swipe_left.png">' +
'</div>' + '</div>' +
'<div class="mes_block">' + '<div class="mes_block">' +
'<div class="ch_name">' + '<div class="ch_name">' +
characterName + characterName +
'<div title=Edit class=mes_edit></div>' + '<div title=Edit class=mes_edit></div>' +
'<div class=mes_edit_cancel>'+ '<div class=mes_edit_cancel>' +
'<img src=img/cancel.png>'+ '<img src=img/cancel.png>' +
'</div>' + '</div>' +
'<div class=mes_edit_done>'+ '<div class=mes_edit_done>' +
'<img src=img/done.png>'+ '<img src=img/done.png>' +
'</div>' + '</div>' +
'</div>' + '</div>' +
'<div class=mes_text></div>' + '<div class=mes_text></div>' +
'</div>' + '</div>' +
'<div class="mes_bias">' + bias + '</div>' + '<div class="mes_bias">' + bias + '</div>' +
'<div class="swipe_right">' + '<div class="swipe_right">' +
' <img src="img/swipe_right.png">' + ' <img src="img/swipe_right.png">' +
'</div>' + '</div>' +
'</div>'; '</div>';
if (type !== 'swipe') { if (type !== 'swipe') {
@ -971,9 +971,9 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
//$('#chat').children().last().css({'transition':'all 0.5s ease-in-out'}); //$('#chat').children().last().css({'transition':'all 0.5s ease-in-out'});
//$('#chat').children().last().css({'transform':'translateX(100vh) scale(0.1,0.1)'}); //$('#chat').children().last().css({'transform':'translateX(100vh) scale(0.1,0.1)'});
//$('#chat').children().last().css({'opacity':'0'}); //$('#chat').children().last().css({'opacity':'0'});
setTimeout(function(){ setTimeout(function () {
$('#chat').children().last().remove(); $('#chat').children().last().remove();
},1000); }, 1000);
} }
} }
@ -1039,7 +1039,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
console.log('Generate calls addOneMessage'); console.log('Generate calls addOneMessage');
addOneMessage(chat[chat.length - 1]); addOneMessage(chat[chat.length - 1]);
} }
//////////////////////////////////// ////////////////////////////////////
var chatString = ''; var chatString = '';
var arrMes = []; var arrMes = [];
var mesSend = []; var mesSend = [];
@ -1066,10 +1066,10 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
} }
function appendToStoryString(value, prefix) { function appendToStoryString(value, prefix) {
if (value !== undefined && value.length > 0) { if (value !== undefined && value.length > 0) {
return prefix + value + '\n'; return prefix + value + '\n';
} }
return ''; return '';
} }
if (is_pygmalion) { if (is_pygmalion) {
@ -1077,29 +1077,29 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
storyString += appendToStoryString(charPersonality, 'Personality: '); storyString += appendToStoryString(charPersonality, 'Personality: ');
storyString += appendToStoryString(Scenario, 'Scenario: '); storyString += appendToStoryString(Scenario, 'Scenario: ');
} else { } else {
if (charDescription !== undefined) { if (charDescription !== undefined) {
if (charPersonality.length > 0) { if (charPersonality.length > 0) {
charPersonality = name2 + "'s personality: " + charPersonality; charPersonality = name2 + "'s personality: " + charPersonality;
}
}
storyString += appendToStoryString(charDescription, '');
if (storyString.endsWith('\n')) {
storyString = storyString.slice(0, -1);
}
if (count_view_mes < topAnchorDepth) {
storyString += '\n' + appendToStoryString(charPersonality, '');
} }
} }
//////////////////////////////////
storyString += appendToStoryString(charDescription, '');
if (storyString.endsWith('\n')) {
storyString = storyString.slice(0, -1);
}
if (count_view_mes < topAnchorDepth) {
storyString += '\n' + appendToStoryString(charPersonality, '');
}
}
//////////////////////////////////
var count_exm_add = 0; var count_exm_add = 0;
console.log('emptying chat2'); console.log('emptying chat2');
var chat2 = []; var chat2 = [];
var j = 0; var j = 0;
console.log('pre-replace chat.length = '+chat.length); console.log('pre-replace chat.length = ' + chat.length);
for (var i = chat.length - 1; i >= 0; i--) { for (var i = chat.length - 1; i >= 0; i--) {
if (j == 0) { if (j == 0) {
@ -1129,7 +1129,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
//console.log('replacing chat2 {}s'); //console.log('replacing chat2 {}s');
j++; j++;
} }
console.log('post replace chat.length = '+chat.length); console.log('post replace chat.length = ' + chat.length);
//chat2 = chat2.reverse(); //chat2 = chat2.reverse();
var this_max_context = 1487; var this_max_context = 1487;
if (main_api == 'kobold') this_max_context = max_context; if (main_api == 'kobold') this_max_context = max_context;
@ -1158,23 +1158,23 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
extension_prompt += '\n'; extension_prompt += '\n';
} }
/////////////////////// swipecode /////////////////////// swipecode
if(type == 'swipe'){ if (type == 'swipe') {
console.log('pre swipe shift: ' + chat2.length); console.log('pre swipe shift: ' + chat2.length);
console.log('shifting swipe chat2'); console.log('shifting swipe chat2');
chat2.shift(); chat2.shift();
} }
console.log('post swipe shift:'+chat2.length); console.log('post swipe shift:' + chat2.length);
var i = 0; var i = 0;
for (var item of chat2) {//console.log(encode("dsfs").length); for (var item of chat2) {//console.log(encode("dsfs").length);
chatString = item + chatString; chatString = item + chatString;
if (encode(JSON.stringify( if (encode(JSON.stringify(
worldInfoString + storyString + chatString + worldInfoString + storyString + chatString +
anchorTop + anchorBottom + anchorTop + anchorBottom +
charPersonality + promptBias + extension_prompt charPersonality + promptBias + extension_prompt
)).length + 120 < this_max_context) { //(The number of tokens in the entire promt) need fix, it must count correctly (added +120, so that the description of the character does not hide) )).length + 120 < this_max_context) { //(The number of tokens in the entire promt) need fix, it must count correctly (added +120, so that the description of the character does not hide)
//if (is_pygmalion && i == chat2.length-1) item='<START>\n'+item; //if (is_pygmalion && i == chat2.length-1) item='<START>\n'+item;
arrMes[arrMes.length] = item; arrMes[arrMes.length] = item;
} else { } else {
@ -1183,7 +1183,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
} }
await delay(1); //For disable slow down (encode gpt-2 need fix) await delay(1); //For disable slow down (encode gpt-2 need fix)
// console.log(i+' '+chat.length); // console.log(i+' '+chat.length);
count_exm_add = 0; count_exm_add = 0;
@ -1213,7 +1213,8 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
return; return;
function runGenerate(cycleGenerationPromt = '') { function runGenerate(cycleGenerationPromt = '') {
console.log('rungenerate entered');
is_send_press = true;
generatedPromtCache += cycleGenerationPromt; generatedPromtCache += cycleGenerationPromt;
if (generatedPromtCache.length == 0) { if (generatedPromtCache.length == 0) {
@ -1325,7 +1326,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
} }
finalPromt = worldInfoBefore + storyString + worldInfoAfter + extension_prompt + mesExmString + mesSendString + generatedPromtCache + promptBias; finalPromt = worldInfoBefore + storyString + worldInfoAfter + extension_prompt + mesExmString + mesSendString + generatedPromtCache + promptBias;
finalPromt = finalPromt.replace(/\r/gm, ''); finalPromt = finalPromt.replace(/\r/gm, '');
console.log('final prompt decided'); //console.log('final prompt decided');
//if we aren't using the kobold GUI settings... //if we aren't using the kobold GUI settings...
if (main_api == 'textgenerationwebui' || main_api == 'kobold' && preset_settings != 'gui') { if (main_api == 'textgenerationwebui' || main_api == 'kobold' && preset_settings != 'gui') {
@ -1456,7 +1457,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
dataType: "json", dataType: "json",
contentType: "application/json", contentType: "application/json",
success: function (data) { success: function (data) {
console.log('generation success'); //console.log('generation success');
tokens_already_generated += this_amount_gen; // add new gen amt to any prev gen counter.. tokens_already_generated += this_amount_gen; // add new gen amt to any prev gen counter..
@ -1496,7 +1497,8 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
message_already_generated.indexOf('<|endoftext|>') === -1 && //if there is no <endoftext> stamp in the response msg message_already_generated.indexOf('<|endoftext|>') === -1 && //if there is no <endoftext> stamp in the response msg
tokens_already_generated < parseInt(amount_gen) && //if the gen'd msg is less than the max response length.. tokens_already_generated < parseInt(amount_gen) && //if the gen'd msg is less than the max response length..
getMessage.length > 0) { //if we actually have gen'd text at all... getMessage.length > 0) { //if we actually have gen'd text at all...
runGenerate(getMessage); //generate again with the 'GetMessage' argument.. runGenerate(getMessage);
console.log('returning to make pyg generate again'); //generate again with the 'GetMessage' argument..
return; return;
} }
@ -1546,21 +1548,21 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
if (type === 'force_name2') this_mes_is_name = true; if (type === 'force_name2') this_mes_is_name = true;
//getMessage = getMessage.replace(/^\s+/g, ''); //getMessage = getMessage.replace(/^\s+/g, '');
if (getMessage.length > 0) { if (getMessage.length > 0) {
if(chat[chat.length-1]['swipe_id'] === undefined || if (chat[chat.length - 1]['swipe_id'] === undefined ||
chat[chat.length-1]['is_user']){type = 'normal';} chat[chat.length - 1]['is_user']) { type = 'normal'; }
if(type === 'swipe'){ if (type === 'swipe') {
chat[chat.length-1]['swipes'][chat[chat.length-1]['swipes'].length] = getMessage; chat[chat.length - 1]['swipes'][chat[chat.length - 1]['swipes'].length] = getMessage;
if(chat[chat.length-1]['swipe_id'] === chat[chat.length-1]['swipes'].length-1){ if (chat[chat.length - 1]['swipe_id'] === chat[chat.length - 1]['swipes'].length - 1) {
//console.log(getMessage); //console.log(getMessage);
chat[chat.length-1]['mes'] = getMessage; chat[chat.length - 1]['mes'] = getMessage;
console.log('runGenerate calls addOneMessage for swipe'); console.log('runGenerate calls addOneMessage for swipe');
addOneMessage(chat[chat.length-1], 'swipe'); addOneMessage(chat[chat.length - 1], 'swipe');
}else{ } else {
chat[chat.length-1]['mes'] = getMessage; chat[chat.length - 1]['mes'] = getMessage;
} }
is_send_press = false; is_send_press = false;
}else{ } else {
console.log('entering chat update routine for non-swipe post'); console.log('entering chat update routine for non-swipe post');
is_send_press = false; is_send_press = false;
chat[chat.length] = {}; chat[chat.length] = {};
@ -1582,7 +1584,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
} }
console.log('runGenerate calls addOneMessage'); console.log('runGenerate calls addOneMessage');
addOneMessage(chat[chat.length - 1]); addOneMessage(chat[chat.length - 1]);
console.log('should hide loading mes and return with send button now');
$("#send_but").css("display", "inline"); $("#send_but").css("display", "inline");
$("#loading_mes").css("display", "none"); $("#loading_mes").css("display", "none");
@ -1599,7 +1601,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
Generate('force_name2'); Generate('force_name2');
} }
} else { } else {
console.log('final re-setting of send button due to error');
$("#send_but").css("display", "inline"); $("#send_but").css("display", "inline");
$("#loading_mes").css("display", "none"); $("#loading_mes").css("display", "none");
showSwipeButtons(); showSwipeButtons();
@ -1610,7 +1612,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
//console.log('AI Response: +'+getMessage+ '('+final_message_length+' tokens)'); //console.log('AI Response: +'+getMessage+ '('+final_message_length+' tokens)');
$("#send_but").css("display", "inline"); $("#send_but").css("display", "inline");
console.log('attempting to show swipes');
showSwipeButtons(); showSwipeButtons();
$("#loading_mes").css("display", "none"); $("#loading_mes").css("display", "none");
@ -1618,6 +1620,7 @@ async function Generate(type, automatic_trigger) {//encode("dsfs").length
}, },
error: function (jqXHR, exception) { error: function (jqXHR, exception) {
$("#send_textarea").removeAttr('disabled'); $("#send_textarea").removeAttr('disabled');
is_send_press = false; is_send_press = false;
$("#send_but").css("display", "inline"); $("#send_but").css("display", "inline");
@ -1748,7 +1751,8 @@ async function getChat() {
data: JSON.stringify({ data: JSON.stringify({
ch_name: characters[this_chid].name, ch_name: characters[this_chid].name,
file_name: characters[this_chid].chat, file_name: characters[this_chid].chat,
avatar_url: characters[this_chid].avatar }), avatar_url: characters[this_chid].avatar
}),
dataType: 'json', dataType: 'json',
contentType: 'application/json', contentType: 'application/json',
}); });
@ -1797,39 +1801,50 @@ function openNavToggle() {
} }
} }
////////// OPTIMZED MAIN API CHANGE FUNCTION ////////////
function changeMainAPI() { function changeMainAPI() {
if ($("#main_api").find(":selected").val() == "kobold") { const selectedVal = $("#main_api").val();
$("#kobold_api").css("display", "block"); const apiElements = {
$("#novel_api").css("display", "none"); "kobold": {
$("#textgenerationwebui_api").css("display", "none"); apiElem: $("#kobold_api"),
main_api = "kobold"; maxContextElem: $("#max_context_block"),
$("#max_context_block").css("display", "block"); amountGenElem: $("#amount_gen_block"),
$("#amount_gen_block").css("display", "block"); softPromptElem: $("#softprompt_block")
$("#softprompt_block").css("display", "block"); },
} "textgenerationwebui": {
if ($("#main_api").find(":selected").val() == "textgenerationwebui") { apiElem: $("#textgenerationwebui_api"),
$("#kobold_api").css("display", "none"); maxContextElem: $("#max_context_block"),
$("#novel_api").css("display", "none"); amountGenElem: $("#amount_gen_block"),
$("#textgenerationwebui_api").css("display", "block"); softPromptElem: $("#softprompt_block")
main_api = "textgenerationwebui"; },
$("#max_context_block").css("display", "block"); "novel": {
$("#amount_gen_block").css("display", "block"); apiElem: $("#novel_api"),
$("#softprompt_block").css("display", "block"); maxContextElem: $("#max_context_block"),
$("#amount_gen_block").children().prop("disabled", false); amountGenElem: $("#amount_gen_block"),
$("#amount_gen_block").css("opacity", 1.0); softPromptElem: $("#softprompt_block")
}
};
for (const apiName in apiElements) {
const apiObj = apiElements[apiName];
const isCurrentApi = selectedVal === apiName;
apiObj.apiElem.css("display", isCurrentApi ? "block" : "none");
apiObj.maxContextElem.css("display", isCurrentApi && apiName !== "novel" ? "block" : "none");
apiObj.amountGenElem.css("display", isCurrentApi && apiName !== "novel" ? "block" : "none");
apiObj.softPromptElem.css("display", isCurrentApi && apiName !== "novel" ? "block" : "none");
if (isCurrentApi && apiName === "textgenerationwebui") {
apiObj.amountGenElem.children().prop("disabled", false);
apiObj.amountGenElem.css("opacity", 1.0);
}
} }
if ($("#main_api").find(":selected").val() == "novel") { main_api = selectedVal;
$("#kobold_api").css("display", "none");
$("#novel_api").css("display", "block");
$("#textgenerationwebui_api").css("display", "none");
main_api = "novel";
$("#max_context_block").css("display", "none");
$("#amount_gen_block").css("display", "none");
$("#softprompt_block").css("display", "none");
}
} }
////////////////////////////////////////////////////
async function getUserAvatars() { async function getUserAvatars() {
$("#user_avatar_block").html(""); //RossAscends: necessary to avoid doubling avatars each QuickRefresh. $("#user_avatar_block").html(""); //RossAscends: necessary to avoid doubling avatars each QuickRefresh.
$("#user_avatar_block").append('<div class="avatar_upload">+</div>'); $("#user_avatar_block").append('<div class="avatar_upload">+</div>');
@ -2723,34 +2738,34 @@ $(document).ready(function () {
///// SWIPE BUTTON CLICKS /////// ///// SWIPE BUTTON CLICKS ///////
$(document).on('click', '.swipe_right', function(){ //when we click swipe right button $(document).on('click', '.swipe_right', function () { //when we click swipe right button
const swipe_duration = 120; const swipe_duration = 120;
const swipe_range = 700; const swipe_range = 700;
//console.log(swipe_range); //console.log(swipe_range);
let run_generate = false; let run_generate = false;
let run_swipe_right = false; let run_swipe_right = false;
if(chat[chat.length-1]['swipe_id'] === undefined){ // if there is no swipe-message in the last spot of the chat array if (chat[chat.length - 1]['swipe_id'] === undefined) { // if there is no swipe-message in the last spot of the chat array
chat[chat.length-1]['swipe_id'] = 0; // set it to id 0 chat[chat.length - 1]['swipe_id'] = 0; // set it to id 0
chat[chat.length-1]['swipes'] = []; // empty the array chat[chat.length - 1]['swipes'] = []; // empty the array
chat[chat.length-1]['swipes'][0] = chat[chat.length-1]['mes']; //assign swipe array with last message from chat chat[chat.length - 1]['swipes'][0] = chat[chat.length - 1]['mes']; //assign swipe array with last message from chat
} }
chat[chat.length-1]['swipe_id']++; //make new slot in array chat[chat.length - 1]['swipe_id']++; //make new slot in array
//console.log(chat[chat.length-1]['swipes']); //console.log(chat[chat.length-1]['swipes']);
if(parseInt(chat[chat.length-1]['swipe_id']) === chat[chat.length-1]['swipes'].length){ //if swipe id of last message is the same as the length of the 'swipes' array if (parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) { //if swipe id of last message is the same as the length of the 'swipes' array
run_generate = true; run_generate = true;
}else if(parseInt(chat[chat.length-1]['swipe_id']) < chat[chat.length-1]['swipes'].length){ //otherwise, if the id is less than the number of swipes } else if (parseInt(chat[chat.length - 1]['swipe_id']) < chat[chat.length - 1]['swipes'].length) { //otherwise, if the id is less than the number of swipes
chat[chat.length-1]['mes'] = chat[chat.length-1]['swipes'][chat[chat.length-1]['swipe_id']]; //load the last mes box with the latest generation chat[chat.length - 1]['mes'] = chat[chat.length - 1]['swipes'][chat[chat.length - 1]['swipe_id']]; //load the last mes box with the latest generation
run_swipe_right = true; //then swipe run_swipe_right = true; //then swipe
} }
if(chat[chat.length-1]['swipe_id'] > chat[chat.length-1]['swipes'].length){ //if we swipe right while generating (the swipe ID is greater than what we are viewing now) if (chat[chat.length - 1]['swipe_id'] > chat[chat.length - 1]['swipes'].length) { //if we swipe right while generating (the swipe ID is greater than what we are viewing now)
chat[chat.length-1]['swipe_id'] = chat[chat.length-1]['swipes'].length; //show that message slot (will be '...' while generating) chat[chat.length - 1]['swipe_id'] = chat[chat.length - 1]['swipes'].length; //show that message slot (will be '...' while generating)
} }
if(run_generate){ //hide swipe arrows while generating if (run_generate) { //hide swipe arrows while generating
$(this).css('display', 'none'); $(this).css('display', 'none');
} }
if(run_generate || run_swipe_right){ // handles animated transitions when swipe right, specifically height transitions between messages if (run_generate || run_swipe_right) { // handles animated transitions when swipe right, specifically height transitions between messages
let this_mes_div = $(this).parent(); let this_mes_div = $(this).parent();
let this_mes_block = $(this).parent().children('.mes_block').children('.mes_text'); let this_mes_block = $(this).parent().children('.mes_block').children('.mes_text');
@ -2759,103 +2774,103 @@ $(document).ready(function () {
this_mes_div.children('.swipe_left').css('display', 'flex'); this_mes_div.children('.swipe_left').css('display', 'flex');
this_mes_div.children('.mes_block').transition({ // this moves the div back and forth this_mes_div.children('.mes_block').transition({ // this moves the div back and forth
x: '-'+swipe_range, x: '-' + swipe_range,
duration: swipe_duration, duration: swipe_duration,
easing: animation_rm_easing, easing: animation_rm_easing,
queue:false, queue: false,
complete: function() { complete: function () {
const is_animation_scroll = ($('#chat').scrollTop() >= ($('#chat').prop("scrollHeight") - $('#chat').outerHeight()) - 10); const is_animation_scroll = ($('#chat').scrollTop() >= ($('#chat').prop("scrollHeight") - $('#chat').outerHeight()) - 10);
//console.log(parseInt(chat[chat.length-1]['swipe_id'])); //console.log(parseInt(chat[chat.length-1]['swipe_id']));
//console.log(chat[chat.length-1]['swipes'].length); //console.log(chat[chat.length-1]['swipes'].length);
if(run_generate && parseInt(chat[chat.length-1]['swipe_id']) === chat[chat.length-1]['swipes'].length){ if (run_generate && parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) {
//console.log('showing ...'); //console.log('showing ...');
$("#chat").children().filter('[mesid="'+(count_view_mes-1)+'"]').children('.mes_block').children('.mes_text').html('...'); //shows ... while generating $("#chat").children().filter('[mesid="' + (count_view_mes - 1) + '"]').children('.mes_block').children('.mes_text').html('...'); //shows ... while generating
}else{ } else {
//console.log('showing previously generated swipe candidate, or "..."'); //console.log('showing previously generated swipe candidate, or "..."');
addOneMessage(chat[chat.length-1], 'swipe'); addOneMessage(chat[chat.length - 1], 'swipe');
}
let new_height = this_mes_div_height-(this_mes_block_height - this_mes_block[0].scrollHeight);
if(new_height < 103) new_height = 103;
this_mes_div.animate({height: new_height+'px'}, {
duration: 100,
queue:false,
progress: function() {
// Scroll the chat down as the message expands
if(is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
},
complete: function() {
this_mes_div.css('height', 'auto');
// Scroll the chat down to the bottom once the animation is complete
if(is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
}
});
this_mes_div.children('.mes_block').transition({
x: swipe_range,
duration: 0,
easing: animation_rm_easing,
queue:false,
complete: function() {
this_mes_div.children('.mes_block').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
queue:false,
complete: function() {
if(run_generate && !is_send_press && parseInt(chat[chat.length-1]['swipe_id']) === chat[chat.length-1]['swipes'].length){
console.log('caught here 2');
is_send_press = true;
Generate('swipe');
}else{
if(parseInt(chat[chat.length-1]['swipe_id']) !== chat[chat.length-1]['swipes'].length){
console.log('caught here 3');
saveChat();
}
}
}
});
}
});
} }
let new_height = this_mes_div_height - (this_mes_block_height - this_mes_block[0].scrollHeight);
if (new_height < 103) new_height = 103;
this_mes_div.animate({ height: new_height + 'px' }, {
duration: 100,
queue: false,
progress: function () {
// Scroll the chat down as the message expands
if (is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
},
complete: function () {
this_mes_div.css('height', 'auto');
// Scroll the chat down to the bottom once the animation is complete
if (is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
}
});
this_mes_div.children('.mes_block').transition({
x: swipe_range,
duration: 0,
easing: animation_rm_easing,
queue: false,
complete: function () {
this_mes_div.children('.mes_block').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
queue: false,
complete: function () {
if (run_generate && !is_send_press && parseInt(chat[chat.length - 1]['swipe_id']) === chat[chat.length - 1]['swipes'].length) {
console.log('caught here 2');
is_send_press = true;
Generate('swipe');
} else {
if (parseInt(chat[chat.length - 1]['swipe_id']) !== chat[chat.length - 1]['swipes'].length) {
console.log('caught here 3');
saveChat();
}
}
}
});
}
});
}
}); });
$(this).parent().children('.avatar').transition({ // moves avatar aong with swipe $(this).parent().children('.avatar').transition({ // moves avatar aong with swipe
x: '-'+swipe_range, x: '-' + swipe_range,
duration: swipe_duration, duration: swipe_duration,
easing: animation_rm_easing, easing: animation_rm_easing,
queue:false, queue: false,
complete: function() { complete: function () {
$(this).parent().children('.avatar').transition({ $(this).parent().children('.avatar').transition({
x: swipe_range, x: swipe_range,
duration: 0, duration: 0,
easing: animation_rm_easing,
queue: false,
complete: function () {
$(this).parent().children('.avatar').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing, easing: animation_rm_easing,
queue:false, queue: false,
complete: function() { complete: function () {
$(this).parent().children('.avatar').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
queue:false,
complete: function() {
}
});
} }
}); });
} }
});
}
}); });
} }
}); });
$(document).on('click', '.swipe_left', function(){ // when we swipe left..but no generation. $(document).on('click', '.swipe_left', function () { // when we swipe left..but no generation.
const swipe_duration = 120; const swipe_duration = 120;
const swipe_range = '700px'; const swipe_range = '700px';
chat[chat.length-1]['swipe_id']--; chat[chat.length - 1]['swipe_id']--;
if(chat[chat.length-1]['swipe_id'] >= 0){ // hide the left arrow if we are viewing the first candidate of the last message block if (chat[chat.length - 1]['swipe_id'] >= 0) { // hide the left arrow if we are viewing the first candidate of the last message block
$(this).parent().children('swipe_right_button').css('display', 'flex'); $(this).parent().children('swipe_right_button').css('display', 'flex');
if(chat[chat.length-1]['swipe_id'] === 0){ if (chat[chat.length - 1]['swipe_id'] === 0) {
$(this).css('display', 'none'); $(this).css('display', 'none');
} }
@ -2865,80 +2880,80 @@ $(document).ready(function () {
this_mes_div.css('height', this_mes_div_height); this_mes_div.css('height', this_mes_div_height);
const this_mes_block_height = this_mes_block[0].scrollHeight; const this_mes_block_height = this_mes_block[0].scrollHeight;
chat[chat.length-1]['mes'] = chat[chat.length-1]['swipes'][chat[chat.length-1]['swipe_id']]; chat[chat.length - 1]['mes'] = chat[chat.length - 1]['swipes'][chat[chat.length - 1]['swipe_id']];
$(this).parent().children('.mes_block').transition({ $(this).parent().children('.mes_block').transition({
x: swipe_range, x: swipe_range,
duration: swipe_duration, duration: swipe_duration,
easing: animation_rm_easing, easing: animation_rm_easing,
queue:false, queue: false,
complete: function() { complete: function () {
const is_animation_scroll = ($('#chat').scrollTop() >= ($('#chat').prop("scrollHeight") - $('#chat').outerHeight()) - 10); const is_animation_scroll = ($('#chat').scrollTop() >= ($('#chat').prop("scrollHeight") - $('#chat').outerHeight()) - 10);
console.log('sipwing left after tr5ansition calls addOneMessage'); console.log('sipwing left after tr5ansition calls addOneMessage');
addOneMessage(chat[chat.length-1], 'swipe'); addOneMessage(chat[chat.length - 1], 'swipe');
let new_height = this_mes_div_height-(this_mes_block_height - this_mes_block[0].scrollHeight); let new_height = this_mes_div_height - (this_mes_block_height - this_mes_block[0].scrollHeight);
if(new_height < 103) new_height = 103; if (new_height < 103) new_height = 103;
this_mes_div.animate({height: new_height+'px'}, { this_mes_div.animate({ height: new_height + 'px' }, {
duration: 100, duration: 100,
queue:false, queue: false,
progress: function() { progress: function () {
// Scroll the chat down as the message expands // Scroll the chat down as the message expands
if(is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight); if (is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
}, },
complete: function() { complete: function () {
this_mes_div.css('height', 'auto'); this_mes_div.css('height', 'auto');
// Scroll the chat down to the bottom once the animation is complete // Scroll the chat down to the bottom once the animation is complete
if(is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight); if (is_animation_scroll) $("#chat").scrollTop($("#chat")[0].scrollHeight);
} }
}); });
$(this).parent().children('.mes_block').transition({ $(this).parent().children('.mes_block').transition({
x: '-'+swipe_range, x: '-' + swipe_range,
duration: 0, duration: 0,
easing: animation_rm_easing,
queue: false,
complete: function () {
$(this).parent().children('.mes_block').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing, easing: animation_rm_easing,
queue:false, queue: false,
complete: function() { complete: function () {
$(this).parent().children('.mes_block').transition({ saveChat();
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
queue:false,
complete: function() {
saveChat();
}
});
} }
}); });
} }
});
}
}); });
$(this).parent().children('.avatar').transition({ $(this).parent().children('.avatar').transition({
x: swipe_range, x: swipe_range,
duration: swipe_duration, duration: swipe_duration,
easing: animation_rm_easing, easing: animation_rm_easing,
queue:false, queue: false,
complete: function() { complete: function () {
$(this).parent().children('.avatar').transition({ $(this).parent().children('.avatar').transition({
x: '-'+swipe_range, x: '-' + swipe_range,
duration: 0, duration: 0,
easing: animation_rm_easing,
queue: false,
complete: function () {
$(this).parent().children('.avatar').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing, easing: animation_rm_easing,
queue:false, queue: false,
complete: function() { complete: function () {
$(this).parent().children('.avatar').transition({
x: '0px',
duration: swipe_duration,
easing: animation_rm_easing,
queue:false,
complete: function() {
}
});
} }
}); });
} }
});
}
}); });
} }
if(chat[chat.length-1]['swipe_id'] < 0){ if (chat[chat.length - 1]['swipe_id'] < 0) {
chat[chat.length-1]['swipe_id'] = 0; chat[chat.length - 1]['swipe_id'] = 0;
} }
}); });
@ -3447,7 +3462,7 @@ console.log('sipwing left after tr5ansition calls addOneMessage');
select_rm_characters(); select_rm_characters();
}); });
//////// OPTIMIZED ALL CHAR CREATION/EDITING TEXTAREA LISTENERS /////////////// //////// OPTIMIZED ALL CHAR CREATION/EDITING TEXTAREA LISTENERS ///////////////
$("#character_name_pole").on("change keyup paste", function () { $("#character_name_pole").on("change keyup paste", function () {
if (menu_type == "create") { if (menu_type == "create") {
@ -3455,9 +3470,9 @@ console.log('sipwing left after tr5ansition calls addOneMessage');
} }
}); });
$("#description_textarea, #personality_textarea, #scenario_pole"+ $("#description_textarea, #personality_textarea, #scenario_pole" +
"#mes_example_textarea, #firstmessage_textarea") "#mes_example_textarea, #firstmessage_textarea")
.on("keyup paste cut", function () { .on("keyup paste cut", function () {
if (menu_type == "create") { if (menu_type == "create") {
create_save_description = $("#description_textarea").val(); create_save_description = $("#description_textarea").val();
create_save_personality = $("#personality_textarea").val(); create_save_personality = $("#personality_textarea").val();
@ -3477,7 +3492,7 @@ console.log('sipwing left after tr5ansition calls addOneMessage');
} }
}); });
/////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////
$("#api_button").click(function () { $("#api_button").click(function () {
if ($("#api_url_text").val() != "") { if ($("#api_url_text").val() != "") {
@ -3565,67 +3580,67 @@ console.log('sipwing left after tr5ansition calls addOneMessage');
} }
}); });
///////////// OPTIMIZED LISTENERS FOR LEFT SIDE OPTIONS POPUP MENU ////////////////////// ///////////// OPTIMIZED LISTENERS FOR LEFT SIDE OPTIONS POPUP MENU //////////////////////
$("#options_button [id]").on("click", function() { $("#options_button [id]").on("click", function () {
var id = $(this).attr("id"); var id = $(this).attr("id");
if (id == "option_select_chat") { if (id == "option_select_chat") {
if (selected_group) { if (selected_group) {
// will open a chat selection screen // will open a chat selection screen
openNavToggle(); openNavToggle();
$("#rm_button_characters").trigger("click"); $("#rm_button_characters").trigger("click");
return; return;
} }
if (this_chid != undefined && !is_send_press) { if (this_chid != undefined && !is_send_press) {
getAllCharaChats(); getAllCharaChats();
$("#shadow_select_chat_popup").css("display", "block"); $("#shadow_select_chat_popup").css("display", "block");
$("#shadow_select_chat_popup").css("opacity", 0.0); $("#shadow_select_chat_popup").css("opacity", 0.0);
$("#shadow_select_chat_popup").transition({ $("#shadow_select_chat_popup").transition({
opacity: 1.0, opacity: 1.0,
duration: animation_rm_duration, duration: animation_rm_duration,
easing: animation_rm_easing, easing: animation_rm_easing,
}); });
} }
} }
else if (id == "option_start_new_chat") { else if (id == "option_start_new_chat") {
if (selected_group) { if (selected_group) {
// will open a group creation screen // will open a group creation screen
openNavToggle(); openNavToggle();
$("#rm_button_group_chats").trigger("click"); $("#rm_button_group_chats").trigger("click");
return; return;
} }
if (this_chid != undefined && !is_send_press) { if (this_chid != undefined && !is_send_press) {
popup_type = "new_chat"; popup_type = "new_chat";
callPopup("<h3>Start new chat?</h3>"); callPopup("<h3>Start new chat?</h3>");
} }
} }
else if (id == "option_regenerate") { else if (id == "option_regenerate") {
if (is_send_press == false) { if (is_send_press == false) {
hideSwipeButtons(); hideSwipeButtons();
is_send_press = true; is_send_press = true;
Generate("regenerate"); Generate("regenerate");
} }
} }
else if (id == "option_delete_mes") { else if (id == "option_delete_mes") {
hideSwipeButtons(); hideSwipeButtons();
if ((this_chid != undefined && !is_send_press) || (selected_group && !is_group_generating)) { if ((this_chid != undefined && !is_send_press) || (selected_group && !is_group_generating)) {
$("#dialogue_del_mes").css("display", "block"); $("#dialogue_del_mes").css("display", "block");
$("#send_form").css("display", "none"); $("#send_form").css("display", "none");
$(".del_checkbox").each(function () { $(".del_checkbox").each(function () {
if ($(this).parent().attr("mesid") != 0) { if ($(this).parent().attr("mesid") != 0) {
$(this).css("display", "block"); $(this).css("display", "block");
$(this).parent().children(".for_checkbox").css("display", "none"); $(this).parent().children(".for_checkbox").css("display", "none");
} }
}); });
} }
} }
}); });
////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////
//functionality for the cancel delete messages button, reverts to normal display of input form //functionality for the cancel delete messages button, reverts to normal display of input form
$("#dialogue_del_mes_cancel").click(function () { $("#dialogue_del_mes_cancel").click(function () {
@ -3802,60 +3817,60 @@ console.log('sipwing left after tr5ansition calls addOneMessage');
}); });
} }
////////////////// OPTIMIZED RANGE SLIDER LISTENERS//////////////// ////////////////// OPTIMIZED RANGE SLIDER LISTENERS////////////////
const sliders = [ const sliders = [
{ {
sliderId: "#temp", sliderId: "#temp",
counterId: "#temp_counter", counterId: "#temp_counter",
format: (val) => isInt(val) ? val + ".00" : val format: (val) => isInt(val) ? val + ".00" : val
}, },
{ {
sliderId: "#amount_gen", sliderId: "#amount_gen",
counterId: "#amount_gen_counter", counterId: "#amount_gen_counter",
format: (val) => val format: (val) => val
}, },
{ {
sliderId: "#max_context", sliderId: "#max_context",
counterId: "#max_context_counter", counterId: "#max_context_counter",
format: (val) => val + " Tokens" format: (val) => val + " Tokens"
}, },
{ {
sliderId: "#rep_pen", sliderId: "#rep_pen",
counterId: "#rep_pen_counter", counterId: "#rep_pen_counter",
format: (val) => isInt(val) ? val + ".00" : val format: (val) => isInt(val) ? val + ".00" : val
}, },
{ {
sliderId: "#rep_pen_size", sliderId: "#rep_pen_size",
counterId: "#rep_pen_size_counter", counterId: "#rep_pen_size_counter",
format: (val) => val + " Tokens" format: (val) => val + " Tokens"
}, },
{ {
sliderId: "#temp_novel", sliderId: "#temp_novel",
counterId: "#temp_counter_novel", counterId: "#temp_counter_novel",
format: (val) => isInt(val) ? val + ".00" : val format: (val) => isInt(val) ? val + ".00" : val
}, },
{ {
sliderId: "#rep_pen_novel", sliderId: "#rep_pen_novel",
counterId: "#rep_pen_counter_novel", counterId: "#rep_pen_counter_novel",
format: (val) => isInt(val) ? val + ".00" : val format: (val) => isInt(val) ? val + ".00" : val
}, },
{ {
sliderId: "#rep_pen_size_novel", sliderId: "#rep_pen_size_novel",
counterId: "#rep_pen_size_counter_novel", counterId: "#rep_pen_size_counter_novel",
format: (val) => val + " Tokens" format: (val) => val + " Tokens"
} }
]; ];
sliders.forEach(slider => { sliders.forEach(slider => {
$(document).on("input", slider.sliderId, function () { $(document).on("input", slider.sliderId, function () {
const value = $(this).val(); const value = $(this).val();
const formattedValue = slider.format(value); const formattedValue = slider.format(value);
$(slider.counterId).html(formattedValue); $(slider.counterId).html(formattedValue);
console.log('saving'); console.log('saving');
saveSettingsDebounced(); saveSettingsDebounced();
}); });
}); });
////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////

View File

@ -1,14 +1,14 @@
import { encode } from "../scripts/gpt-2-3-tokenizer/mod.js"; import { encode } from "../scripts/gpt-2-3-tokenizer/mod.js";
import { import {
Generate, Generate,
this_chid, this_chid,
characters, characters,
online_status, online_status,
main_api, main_api,
api_server, api_server,
api_key_novel, api_key_novel,
is_send_press, is_send_press,
} from "../script.js"; } from "../script.js";
@ -23,7 +23,7 @@ var AdvancedCharDefsPopup = document.getElementById("character_popup");
var ConfirmationPopup = document.getElementById("dialogue_popup"); var ConfirmationPopup = document.getElementById("dialogue_popup");
var AutoConnectCheckbox = document.getElementById("auto-connect-checkbox"); var AutoConnectCheckbox = document.getElementById("auto-connect-checkbox");
var AutoLoadChatCheckbox = document.getElementById("auto-load-chat-checkbox"); var AutoLoadChatCheckbox = document.getElementById("auto-load-chat-checkbox");
var SelectedNavTab = ("#"+LoadLocal('SelectedNavTab')); var SelectedNavTab = ("#" + LoadLocal('SelectedNavTab'));
var create_save_name; var create_save_name;
var create_save_description; var create_save_description;
@ -36,14 +36,14 @@ var perm_tokens;
const observerConfig = { childList: true, subtree: true }; const observerConfig = { childList: true, subtree: true };
const observer = new MutationObserver(function(mutations) { const observer = new MutationObserver(function (mutations) {
mutations.forEach(function(mutation) { mutations.forEach(function (mutation) {
if (mutation.target.id === "online_status_text2") { if (mutation.target.id === "online_status_text2") {
RA_checkOnlineStatus(); RA_checkOnlineStatus();
} else if (mutation.target.parentNode === SelectedCharacterTab) { } else if (mutation.target.parentNode === SelectedCharacterTab) {
setTimeout(RA_CountCharTokens, 200); setTimeout(RA_CountCharTokens, 200);
} }
}); });
}); });
observer.observe(document.documentElement, observerConfig); observer.observe(document.documentElement, observerConfig);
@ -54,19 +54,19 @@ observer.observe(document.documentElement, observerConfig);
//Does not break old characters/chats, as the code just uses whatever timestamp exists in the chat. //Does not break old characters/chats, as the code just uses whatever timestamp exists in the chat.
//New chats made with characters will use this new formatting. //New chats made with characters will use this new formatting.
export function humanizedDateTime() { export function humanizedDateTime() {
let baseDate = new Date(Date.now()); let baseDate = new Date(Date.now());
let humanYear = baseDate.getFullYear(); let humanYear = baseDate.getFullYear();
let humanMonth = baseDate.getMonth() + 1; let humanMonth = baseDate.getMonth() + 1;
let humanDate = baseDate.getDate(); let humanDate = baseDate.getDate();
let humanHour = (baseDate.getHours() < 10 ? "0" : "") + baseDate.getHours(); let humanHour = (baseDate.getHours() < 10 ? "0" : "") + baseDate.getHours();
let humanMinute = let humanMinute =
(baseDate.getMinutes() < 10 ? "0" : "") + baseDate.getMinutes(); (baseDate.getMinutes() < 10 ? "0" : "") + baseDate.getMinutes();
let humanSecond = let humanSecond =
(baseDate.getSeconds() < 10 ? "0" : "") + baseDate.getSeconds(); (baseDate.getSeconds() < 10 ? "0" : "") + baseDate.getSeconds();
let humanMillisecond = let humanMillisecond =
(baseDate.getMilliseconds() < 10 ? "0" : "") + baseDate.getMilliseconds(); (baseDate.getMilliseconds() < 10 ? "0" : "") + baseDate.getMilliseconds();
let HumanizedDateTime = let HumanizedDateTime =
humanYear +"-" +humanMonth +"-" +humanDate +" @" +humanHour +"h " +humanMinute +"m " +humanSecond +"s " +humanMillisecond +"ms"; humanYear + "-" + humanMonth + "-" + humanDate + " @" + humanHour + "h " + humanMinute + "m " + humanSecond + "s " + humanMillisecond + "ms";
return HumanizedDateTime; return HumanizedDateTime;
} }
@ -76,58 +76,59 @@ $("#rm_button_create").on("click", function () { //when "+New Character" is
$(SelectedCharacterTab).children("h2").html(''); // empty nav's 3rd panel tab $(SelectedCharacterTab).children("h2").html(''); // empty nav's 3rd panel tab
//empty temp vars to store new char data for counting //empty temp vars to store new char data for counting
create_save_name=""; create_save_name = "";
create_save_description=""; create_save_description = "";
create_save_personality=""; create_save_personality = "";
create_save_first_message=""; create_save_first_message = "";
create_save_scenario=""; create_save_scenario = "";
create_save_mes_example=""; create_save_mes_example = "";
$("#result_info").html('Type to start counting tokens!'); $("#result_info").html('Type to start counting tokens!');
}); });
$("#rm_ch_create_block").on("input", function () {RA_CountCharTokens();}); //when any input is made to the create/edit character form textareas $("#rm_ch_create_block").on("input", function () { RA_CountCharTokens(); }); //when any input is made to the create/edit character form textareas
$("#character_popup").on("input", function () {RA_CountCharTokens();}); //when any input is made to the advanced editing popup textareas $("#character_popup").on("input", function () { RA_CountCharTokens(); }); //when any input is made to the advanced editing popup textareas
//function: //function:
function RA_CountCharTokens() { function RA_CountCharTokens() {
$("#result_info").html(""); $("#result_info").html("");
console.log('RA_TC -- starting with this_chid = '+this_chid); console.log('RA_TC -- starting with this_chid = ' + this_chid);
if (document.getElementById('name_div').style.display == "block"){ //if new char if (document.getElementById('name_div').style.display == "block") { //if new char
$("#form_create").on("input", function () { //fill temp vars with form_create values $("#form_create").on("input", function () { //fill temp vars with form_create values
create_save_name = $("#character_name_pole").val(); create_save_name = $("#character_name_pole").val();
create_save_description = $("#description_textarea").val(); create_save_description = $("#description_textarea").val();
create_save_first_message = $("#firstmessage_textarea").val(); create_save_first_message = $("#firstmessage_textarea").val();
}); });
$("#character_popup").on("input", function () { //fill temp vars with advanced popup values $("#character_popup").on("input", function () { //fill temp vars with advanced popup values
create_save_personality = $("#personality_textarea").val(); create_save_personality = $("#personality_textarea").val();
create_save_scenario = $("#scenario_pole").val(); create_save_scenario = $("#scenario_pole").val();
create_save_mes_example = $("#mes_example_textarea").val(); create_save_mes_example = $("#mes_example_textarea").val();
}); });
//count total tokens, including those that will be removed from context once chat history is long //count total tokens, including those that will be removed from context once chat history is long
count_tokens = encode(JSON.stringify( count_tokens = encode(JSON.stringify(
create_save_name + create_save_name +
create_save_description + create_save_description +
create_save_personality + create_save_personality +
create_save_scenario + create_save_scenario +
create_save_first_message + create_save_first_message +
create_save_mes_example create_save_mes_example
)).length; )).length;
//count permanent tokens that will never get flushed out of context //count permanent tokens that will never get flushed out of context
perm_tokens = encode(JSON.stringify( perm_tokens = encode(JSON.stringify(
create_save_name + create_save_name +
create_save_description + create_save_description +
create_save_personality + create_save_personality +
create_save_scenario create_save_scenario
)).length; )).length;
} else {if (this_chid !== undefined && this_chid !== "invalid-safety-id") { // if we are counting a valid pre-saved char } else {
if (this_chid !== undefined && this_chid !== "invalid-safety-id") { // if we are counting a valid pre-saved char
//same as above, all tokens including temporary ones //same as above, all tokens including temporary ones
count_tokens = encode( count_tokens = encode(
JSON.stringify( JSON.stringify(
characters[this_chid].description + characters[this_chid].description +
characters[this_chid].personality + characters[this_chid].personality +
characters[this_chid].scenario + characters[this_chid].scenario +
characters[this_chid].first_mes + characters[this_chid].first_mes +
@ -137,102 +138,102 @@ function RA_CountCharTokens() {
//permanent tokens count //permanent tokens count
perm_tokens = encode( perm_tokens = encode(
JSON.stringify( JSON.stringify(
characters[this_chid].name + characters[this_chid].name +
characters[this_chid].description + characters[this_chid].description +
characters[this_chid].personality + characters[this_chid].personality +
characters[this_chid].scenario characters[this_chid].scenario
)).length; )).length;
} else {console.log("RA_TC -- no valid char found, closing.");} // if neither, probably safety char or some error in loading } else { console.log("RA_TC -- no valid char found, closing."); } // if neither, probably safety char or some error in loading
} }
// display the counted tokens // display the counted tokens
if (count_tokens < 1024 && perm_tokens < 1024) { if (count_tokens < 1024 && perm_tokens < 1024) {
$("#result_info").html(count_tokens + " Tokens (" + perm_tokens + " Permanent Tokens)"); //display normal if both counts are under 1024 $("#result_info").html(count_tokens + " Tokens (" + perm_tokens + " Permanent Tokens)"); //display normal if both counts are under 1024
} else {$("#result_info").html("<font color=red>" +count_tokens +" Tokens (" +perm_tokens +" Permanent Tokens)(TOO MANY)</font>");} //warn if either are over 1024 } else { $("#result_info").html("<font color=red>" + count_tokens + " Tokens (" + perm_tokens + " Permanent Tokens)(TOO MANY)</font>"); } //warn if either are over 1024
} }
//Auto Load Last Charcter -- (fires when active_character is defined and auto_load_chat is true) //Auto Load Last Charcter -- (fires when active_character is defined and auto_load_chat is true)
async function RA_autoloadchat() { async function RA_autoloadchat() {
if (document.getElementById('CharID0') !== null){ if (document.getElementById('CharID0') !== null) {
console.log('char list loaded! clicking activeChar') console.log('char list loaded! clicking activeChar')
var CharToAutoLoad = document.getElementById('CharID'+LoadLocal('ActiveChar')); var CharToAutoLoad = document.getElementById('CharID' + LoadLocal('ActiveChar'));
if (CharToAutoLoad !=null){ if (CharToAutoLoad != null) {
CharToAutoLoad.click(); CharToAutoLoad.click();
}else{ } else {
console.log(CharToAutoLoad + ' ActiveChar local var - not found: '+LoadLocal('ActiveChar')); console.log(CharToAutoLoad + ' ActiveChar local var - not found: ' + LoadLocal('ActiveChar'));
} }
RestoreNavTab(); RestoreNavTab();
}else{ } else {
console.log('no char list yet..') console.log('no char list yet..')
setTimeout(RA_autoloadchat,100) // if the charcter list hadn't been loaded yet, try again. setTimeout(RA_autoloadchat, 100) // if the charcter list hadn't been loaded yet, try again.
} }
} }
//only triggers when AutoLoadChat is enabled, consider adding this as an independent feature later. //only triggers when AutoLoadChat is enabled, consider adding this as an independent feature later.
function RestoreNavTab(){ function RestoreNavTab() {
if($(rm_button_selected_ch).children("h2").text()!==''){ //check for a change in the character edit tab name if ($(rm_button_selected_ch).children("h2").text() !== '') { //check for a change in the character edit tab name
console.log('detected ALC char finished loaded, proceeding to restore tab.'); console.log('detected ALC char finished loaded, proceeding to restore tab.');
$(SelectedNavTab).click() //click to restore saved tab when name has changed (signalling char load is done) $(SelectedNavTab).click() //click to restore saved tab when name has changed (signalling char load is done)
}else{ } else {
setTimeout(RestoreNavTab,100) //if not changed yet, check again after 100ms setTimeout(RestoreNavTab, 100) //if not changed yet, check again after 100ms
} }
} }
//changes input bar and send button display depending on connection status //changes input bar and send button display depending on connection status
function RA_checkOnlineStatus() { function RA_checkOnlineStatus() {
if (online_status == "no_connection") { if (online_status == "no_connection") {
$("#send_textarea").attr("placeholder", "Not connected to API!"); //Input bar placeholder tells users they are not connected $("#send_textarea").attr("placeholder", "Not connected to API!"); //Input bar placeholder tells users they are not connected
$("#send_form").css("background-color", "rgba(100,0,0,0.7)"); //entire input form area is red when not connected $("#send_form").css("background-color", "rgba(100,0,0,0.7)"); //entire input form area is red when not connected
$("#send_but").css("display", "none"); //send button is hidden when not connected; $("#send_but").css("display", "none"); //send button is hidden when not connected;
} else { } else {
if (online_status !== undefined && online_status !== "no_connection") { if (online_status !== undefined && online_status !== "no_connection") {
$("#send_textarea").attr("placeholder", "Type a message..."); //on connect, placeholder tells user to type message $("#send_textarea").attr("placeholder", "Type a message..."); //on connect, placeholder tells user to type message
$("#send_form").css("background-color", "rgba(0,0,0,0.7)"); //on connect, form BG changes to transprent black $("#send_form").css("background-color", "rgba(0,0,0,0.7)"); //on connect, form BG changes to transprent black
if (!is_send_press && !(selected_group && is_group_generating)) { if (!is_send_press && !(selected_group && is_group_generating)) {
$("#send_but").css("display", "inline"); //on connect, send button shows $("#send_but").css("display", "inline"); //on connect, send button shows
} }
} }
} }
} }
//Auto-connect to API (when set to kobold, API URL exists, and auto_connect is true) //Auto-connect to API (when set to kobold, API URL exists, and auto_connect is true)
function RA_autoconnect() { function RA_autoconnect() {
if (typeof online_status !== 'undefined' && (api_server !== '' || api_key_novel !== '')) { if (typeof online_status !== 'undefined' && (api_server !== '' || api_key_novel !== '')) {
if (online_status === "no_connection" && LoadLocalBool('AutoConnectEnabled')) { if (online_status === "no_connection" && LoadLocalBool('AutoConnectEnabled')) {
if (isUrlOrAPIKey(api_server) && main_api === "kobold") { if (isUrlOrAPIKey(api_server) && main_api === "kobold") {
$("#api_url_text").val(api_server); $("#api_url_text").val(api_server);
$("#api_button").click(); $("#api_button").click();
//} else if (isUrlOrAPIKey(api_key_novel) && main_api === "novel") { //} else if (isUrlOrAPIKey(api_key_novel) && main_api === "novel") {
// $("#api_key_novel").val(api_key_novel); // $("#api_key_novel").val(api_key_novel);
// $("#api_button").click(); // $("#api_button").click();
} }
}
} else {
setTimeout(RA_autoconnect, 100);
} }
} } else {
setTimeout(RA_autoconnect, 100);
}
}
function isUrlOrAPIKey(string) { function isUrlOrAPIKey(string) {
//const pattern = /^\d{3}-\d{3}-\d{3}-\d{3}$/; //need a sample novelAI key to set this format //const pattern = /^\d{3}-\d{3}-\d{3}-\d{3}$/; //need a sample novelAI key to set this format
try { try {
new URL(string); new URL(string);
return true; return true;
} catch (_) { } catch (_) {
// return pattern.test(string); // return pattern.test(string);
} }
} }
$("document").ready(function () { $("document").ready(function () {
// read the state of Nav Lock and whether the nav was open or not before page load. // read the state of Nav Lock and whether the nav was open or not before page load.
$(PanelPin).prop('checked', LoadLocalBool("NavLockOn")); $(PanelPin).prop('checked', LoadLocalBool("NavLockOn"));
if (LoadLocalBool("NavLockOn") == true){$(NavToggle).prop("checked", LoadLocalBool("NavOpened"));} if (LoadLocalBool("NavLockOn") == true) { $(NavToggle).prop("checked", LoadLocalBool("NavOpened")); }
// read the state of AutoConnect and AutoLoadChat. // read the state of AutoConnect and AutoLoadChat.
$(AutoConnectCheckbox).prop("checked",LoadLocalBool("AutoConnectEnabled")); $(AutoConnectCheckbox).prop("checked", LoadLocalBool("AutoConnectEnabled"));
$(AutoLoadChatCheckbox).prop("checked",LoadLocalBool("AutoLoadChatEnabled")); $(AutoLoadChatCheckbox).prop("checked", LoadLocalBool("AutoLoadChatEnabled"));
if (LoadLocalBool('AutoLoadChatEnabled') == true) {RA_autoloadchat();} if (LoadLocalBool('AutoLoadChatEnabled') == true) { RA_autoloadchat(); }
//Autoconnect on page load if enabled, or when api type is changed //Autoconnect on page load if enabled, or when api type is changed
if (LoadLocalBool("AutoConnectEnabled") == true) {RA_autoconnect()} if (LoadLocalBool("AutoConnectEnabled") == true) { RA_autoconnect() }
$("#main_api").change(function () {RA_autoconnect();}); $("#main_api").change(function () { RA_autoconnect(); });
$("#api_button").click(function () {setTimeout(RA_checkOnlineStatus, 100);}); $("#api_button").click(function () { setTimeout(RA_checkOnlineStatus, 100); });
//close the RightNav panel when user clicks outside of it or related panels (adv editing popup, or dialog popups) //close the RightNav panel when user clicks outside of it or related panels (adv editing popup, or dialog popups)
$("html").click(function (e) { $("html").click(function (e) {
@ -242,29 +243,29 @@ $("document").ready(function () {
!RightNavPanel.contains(e.target) && !RightNavPanel.contains(e.target) &&
!AdvancedCharDefsPopup.contains(e.target) && !AdvancedCharDefsPopup.contains(e.target) &&
!ConfirmationPopup.contains(e.target)) { !ConfirmationPopup.contains(e.target)) {
NavToggle.click(); NavToggle.click();
} }
}); });
//save NavLock prefs and record state of the Nav being open or closed //save NavLock prefs and record state of the Nav being open or closed
$(NavToggle).on("change", function () {SaveLocal("NavOpened", $(NavToggle).prop("checked")); }); $(NavToggle).on("change", function () { SaveLocal("NavOpened", $(NavToggle).prop("checked")); });
$(PanelPin).on("change",function () {SaveLocal("NavLockOn", $(PanelPin).prop("checked")); }); $(PanelPin).on("change", function () { SaveLocal("NavLockOn", $(PanelPin).prop("checked")); });
//save AutoConnect and AutoLoadChat prefs //save AutoConnect and AutoLoadChat prefs
$(AutoConnectCheckbox).on("change",function () {SaveLocal("AutoConnectEnabled", $(AutoConnectCheckbox).prop("checked")); }); $(AutoConnectCheckbox).on("change", function () { SaveLocal("AutoConnectEnabled", $(AutoConnectCheckbox).prop("checked")); });
$(AutoLoadChatCheckbox).on("change",function () {SaveLocal("AutoLoadChatEnabled", $(AutoLoadChatCheckbox).prop("checked")); }); $(AutoLoadChatCheckbox).on("change", function () { SaveLocal("AutoLoadChatEnabled", $(AutoLoadChatCheckbox).prop("checked")); });
$("#rm_button_extensions").click(function() { $("#rm_button_extensions").click(function () {
SaveLocal('SelectedNavTab','rm_button_extensions'); SaveLocal('SelectedNavTab', 'rm_button_extensions');
}); });
$("#rm_button_settings").click( function (){SaveLocal('SelectedNavTab','rm_button_settings'); }); $("#rm_button_settings").click(function () { SaveLocal('SelectedNavTab', 'rm_button_settings'); });
$(SelectedCharacterTab).click(function () {SaveLocal('SelectedNavTab','rm_button_selected_ch'); }); $(SelectedCharacterTab).click(function () { SaveLocal('SelectedNavTab', 'rm_button_selected_ch'); });
$("#rm_button_characters").click( function () { //if char list is clicked, in addition to saving it... $("#rm_button_characters").click(function () { //if char list is clicked, in addition to saving it...
SaveLocal('SelectedNavTab','rm_button_characters'); SaveLocal('SelectedNavTab', 'rm_button_characters');
characters.sort(Intl.Collator().compare); // we sort the list characters.sort(Intl.Collator().compare); // we sort the list
}); });
// when a char is selected from the list, save them as the auto-load character for next page load // when a char is selected from the list, save them as the auto-load character for next page load
$(document).on("click", ".character_select",function () {SaveLocal('ActiveChar',$(this).attr('chid')); }); $(document).on("click", ".character_select", function () { SaveLocal('ActiveChar', $(this).attr('chid')); });
//this makes the chat input text area resize vertically to match the text size (limited by CSS at 50% window height) //this makes the chat input text area resize vertically to match the text size (limited by CSS at 50% window height)
$('#send_textarea').on('input', function () { $('#send_textarea').on('input', function () {
@ -274,20 +275,20 @@ $("document").ready(function () {
//Regenerate if user swipes on the last mesage in chat //Regenerate if user swipes on the last mesage in chat
document.addEventListener('swiped-left', function(e) { document.addEventListener('swiped-left', function (e) {
var SwipeButR = $('.swipe_right:last'); var SwipeButR = $('.swipe_right:last');
var SwipeTargetMesClassParent = e.target.closest('.last_mes'); var SwipeTargetMesClassParent = e.target.closest('.last_mes');
if (SwipeTargetMesClassParent !== null){ if (SwipeTargetMesClassParent !== null) {
if(SwipeButR.attr('style')=='display: flex;' == true){ if (SwipeButR.attr('style') == 'display: flex;' == true) {
SwipeButR.click(); SwipeButR.click();
} }
} }
}); });
document.addEventListener('swiped-right', function(e) { document.addEventListener('swiped-right', function (e) {
var SwipeButL = $('.swipe_left:last'); var SwipeButL = $('.swipe_left:last');
var SwipeTargetMesClassParent = e.target.closest('.last_mes'); var SwipeTargetMesClassParent = e.target.closest('.last_mes');
if (SwipeTargetMesClassParent !== null){ if (SwipeTargetMesClassParent !== null) {
if(SwipeButL.attr('style')=='display: flex;' == true){ if (SwipeButL.attr('style') == 'display: flex;' == true) {
SwipeButL.click(); SwipeButL.click();
} }
} }
@ -296,7 +297,7 @@ $("document").ready(function () {
//Additional hotkeys CTRL+ENTER and CTRL+UPARROW //Additional hotkeys CTRL+ENTER and CTRL+UPARROW
document.addEventListener("keydown", (event) => { document.addEventListener("keydown", (event) => {
if (event.ctrlKey && event.key == "Enter") { if (event.ctrlKey && event.key == "Enter") {
// Ctrl+Enter for Regeneration Last Response // Ctrl+Enter for Regeneration Last Response
if (is_send_press == false) { if (is_send_press == false) {
Generate("regenerate"); Generate("regenerate");
@ -305,7 +306,7 @@ $("document").ready(function () {
if (event.ctrlKey && event.key == "ArrowUp") { if (event.ctrlKey && event.key == "ArrowUp") {
//Ctrl+UpArrow for Connect to last server //Ctrl+UpArrow for Connect to last server
if (online_status === "no_connection") { if (online_status === "no_connection") {
document.getElementById("api_button").click(); document.getElementById("api_button").click();
} }
} }
if (event.ctrlKey && event.key == "ArrowLeft") { //for debug, show all local stored vars if (event.ctrlKey && event.key == "ArrowLeft") { //for debug, show all local stored vars