Chore: Add code formatting conventions as eslint rules (#5158)

* Add code formatting conventions as eslint rules

* Improve formatting in addQuickReply
This commit is contained in:
Cohee
2026-02-15 01:16:34 +02:00
committed by GitHub
parent d118eee014
commit 357da3219b
94 changed files with 366 additions and 566 deletions
+23
View File
@@ -102,5 +102,28 @@ module.exports = {
// These rules should eventually be enabled.
'no-async-promise-executor': 'off',
'no-inner-declarations': 'off',
'brace-style': 'off',
// Additional formatting rules based on codebase conventions
'array-bracket-spacing': ['error', 'never'],
'computed-property-spacing': ['error', 'never'],
'block-spacing': ['error', 'always'],
'keyword-spacing': ['error', { before: true, after: true }],
'space-before-blocks': ['error', 'always'],
'space-before-function-paren': ['error', { anonymous: 'always', named: 'never', asyncArrow: 'always' }],
'space-in-parens': ['error', 'never'],
'comma-spacing': ['error', { before: false, after: true }],
'key-spacing': ['error', { beforeColon: false, afterColon: true }],
'func-call-spacing': ['error', 'never'],
'no-multiple-empty-lines': ['error', { max: 2, maxEOF: 1, maxBOF: 0 }],
'padded-blocks': ['error', 'never'],
'no-whitespace-before-property': 'error',
'space-unary-ops': ['error', { words: true, nonwords: false }],
'arrow-spacing': ['error', { before: true, after: true }],
'template-curly-spacing': ['error', 'never'],
'rest-spread-spacing': ['error', 'never'],
'generator-star-spacing': ['error', { before: false, after: true }],
'yield-star-spacing': ['error', { before: false, after: true }],
'template-tag-spacing': ['error', 'never'],
'switch-colon-spacing': ['error', { after: true, before: false }],
},
};
+2 -14
View File
@@ -2516,7 +2516,6 @@ export function addOneMessage(mes, { type = undefined, insertAfter = null, scrol
* @returns {JQuery<HTMLElement>} Rendered HTMLElement.
*/
export function updateMessageElement(mes, { messageId = chat.length - 1, messageElement = messageTemplate.clone(), adjustMediaScroll = SCROLL_BEHAVIOR.NONE } = {}) {
let avatarImg = getThumbnailUrl('persona', user_avatar);
//for non-user messages
@@ -3709,9 +3708,9 @@ class StreamingProcessor {
}
/**
* @returns {Generator<{ text: string, swipes: string[], logprobs: import('./scripts/logprobs.js').TokenLogprobs, toolCalls: any[], state: any }, void, void>}
* @returns {AsyncGenerator<{ text: string, swipes: string[], logprobs: import('./scripts/logprobs.js').TokenLogprobs, toolCalls: any[], state: any }, void, void>}
*/
*nullStreamingGeneration() {
async* nullStreamingGeneration() {
throw new Error('Generation function for streaming is not hooked up');
}
@@ -4862,7 +4861,6 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
// Add quiet generation prompt at depth 0
if (quiet_prompt && quiet_prompt.length) {
// here name1 is forced for all quiet prompts..why?
const name = name1;
//checks if we are in instruct, if so, formats the chat as such, otherwise just adds the quiet prompt
@@ -5399,7 +5397,6 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
if (!isAborted && power_user.auto_swipe && generatedTextFiltered(getMessage)) {
is_send_press = false;
return await swipe(null, SWIPE_DIRECTION.RIGHT, { source: SWIPE_SOURCE.AUTO_SWIPE, repeated: true, forceMesId: chat.length - 1 });
}
console.debug('/api/chats/save called by /Generate');
@@ -6517,7 +6514,6 @@ export async function saveReply({ type, getMessage, fromStreaming = false, title
!fromStreaming && await eventSource.emit(event_types.MESSAGE_RECEIVED, chat_id, type);
addOneMessage(chat[chat_id], { type: 'swipe' });
!fromStreaming && await eventSource.emit(event_types.CHARACTER_MESSAGE_RENDERED, chat_id, type);
} else {
console.debug('entering chat update routine for non-swipe post');
const newMessage = {};
@@ -8247,7 +8243,6 @@ export async function getChatsFromFiles(data, isGroupChat) {
currentChat.shift();
}
chat_dict[file_name] = currentChat;
} catch (error) {
console.error(error);
}
@@ -9588,7 +9583,6 @@ export async function createOrEditCharacter(e) {
select_rm_info('char_create', avatarId, oldSelectedChar);
crop_data = undefined;
} catch (error) {
console.error('Error creating character', error);
toastr.error(t`Failed to create character`);
@@ -9984,7 +9978,6 @@ export async function swipe(event, direction, { source, repeated, message = chat
duration: 0, //used to be 100 //Disabled on Cohee's request. https://github.com/SillyTavern/SillyTavern/pull/4610/files#r2408731744
queue: false,
progress: function (animation, progress, remainingMs) {
if (is_animation_scroll) chatElement.scrollTop(getMessageBottomHeight(thisMesDiv));
},
complete: function () {
@@ -10001,7 +9994,6 @@ export async function swipe(event, direction, { source, repeated, message = chat
* @param {boolean} [skipSwipeOut=false]
*/
async function animateSwipe(run_generate = false, skipSwipeOut = false) {
if (!skipSwipeOut) {
//Swipe out.
await animateSwipeTransition(mesId, { xEnd: `${swipeRange}px`, duration: swipeDuration });
@@ -10069,7 +10061,6 @@ export async function swipe(event, direction, { source, repeated, message = chat
//If the swipe is not being deleted.
if (source != SWIPE_SOURCE.DELETE && source != SWIPE_SOURCE.BACK) {
// Make sure ad-hoc changes to extras are saved before swiping away
syncMesToSwipe(mesId);
@@ -10382,7 +10373,6 @@ export async function doNewChat({ deleteCurrentChat = false } = {}) {
await createOrEditCharacter(new CustomEvent('newChat'));
if (deleteCurrentChat) await delChat(chat_file_for_del + '.jsonl');
}
}
/**
@@ -11407,9 +11397,7 @@ jQuery(async function () {
divchat.style.borderRadius = '';
divchat.style.backgroundColor = '';
} else {
divchat.style.borderRadius = '10px'; // Adjust the value to control the roundness of the corners
divchat.style.backgroundColor = ''; // Set the background color to your preference
-2
View File
@@ -986,7 +986,6 @@ class PromptManager {
* @returns {void}
*/
addPrompt(prompt, identifier) {
if (typeof prompt !== 'object' || prompt === null) throw new Error('Object is not a prompt');
const newPrompt = {
@@ -1318,7 +1317,6 @@ class PromptManager {
this.updatePromptByIdentifier(identifier, prompt);
debouncedSaveServiceSettings().then(() => this.render());
});
}
/**
-3
View File
@@ -101,7 +101,6 @@ observer.observe(document.documentElement, observerConfig);
* @returns {string} - A human-readable string that represents the time spent generating characters.
*/
export function humanizeGenTime(total_gen_time) {
//convert time_spent to humanized format of "_ Hours, _ Minutes, _ Seconds" from milliseconds
let time_spent = total_gen_time || 0;
time_spent = Math.floor(time_spent / 1000);
@@ -1274,8 +1273,6 @@ export function initRossMods() {
}
if (event.ctrlKey && /^[1-9]$/.test(event.key)) {
// This will eventually be to trigger quick replies
// event.preventDefault();
@@ -80,8 +80,6 @@ export class AutoComplete {
}
/**
* @param {HTMLTextAreaElement|HTMLInputElement} textarea The textarea to receive autocomplete.
* @param {() => boolean} checkIfActivate Function should return true only if under the current conditions, autocomplete should display (e.g., for slash commands: autoComplete.text[0] == '/')
@@ -414,7 +412,6 @@ export class AutoComplete {
});
if (this.isForceHidden) {
// hidden with escape
return this.hide();
@@ -465,7 +462,6 @@ export class AutoComplete {
}
/**
* Create updated DOM.
*/
@@ -514,7 +510,6 @@ export class AutoComplete {
}
/**
* Update position of DOM.
*/
@@ -1,6 +1,3 @@
export class AutoCompleteFuzzyScore {
/**@type {number}*/ start;
/**@type {number}*/ longestConsecutive;
@@ -2,7 +2,6 @@ import { AutoCompleteNameResultBase } from './AutoCompleteNameResultBase.js';
import { AutoCompleteSecondaryNameResult } from './AutoCompleteSecondaryNameResult.js';
export class AutoCompleteNameResult extends AutoCompleteNameResultBase {
/**
*
@@ -1,7 +1,6 @@
import { AutoCompleteOption } from './AutoCompleteOption.js';
export class AutoCompleteNameResultBase {
/**@type {string} */ name;
/**@type {number} */ start;
@@ -1,7 +1,6 @@
import { AutoCompleteFuzzyScore } from './AutoCompleteFuzzyScore.js';
export class AutoCompleteOption {
/** @type {string} */ name;
/** @type {string} */ typeIcon;
-1
View File
@@ -150,7 +150,6 @@ function onCfgMenuItemClick() {
setTimeout(function () {
$('#cfgConfig').hide();
}, animation_duration);
}
//duplicate options menu close handler from script.js
//because this listener takes priority
-1
View File
@@ -251,7 +251,6 @@ class DataMaidDialog {
categoryElement.remove();
this.displayEmptyPlaceholder();
});
});
categoryElement.querySelectorAll('.dataMaidItemDelete').forEach(button => {
button.addEventListener('click', async () => {
@@ -95,7 +95,6 @@ async function downloadAssetsList(url) {
fetch(url, { cache: 'no-cache' })
.then(response => response.json())
.then(async function (json) {
availableAssets = {};
$('#assets_menu').empty();
@@ -1414,7 +1414,6 @@ export async function getExpressionsList({ filterAvailable = false } = {}) {
});
if (apiResult.ok) {
const data = await apiResult.json();
expressionsList = data.labels;
return expressionsList;
@@ -1488,7 +1487,6 @@ function chooseSpriteForExpression(spriteFolderName, expression, { prevExpressio
}
return spriteFile;
}
/**
@@ -791,7 +791,6 @@ async function listGalleryCommand(args) {
const items = await getGalleryItems(url);
return JSON.stringify(items.map(it => it.src));
} catch (err) {
console.error(err);
}
@@ -10,16 +10,12 @@ export class QuickReplyApi {
/** @type {SettingsUi} */ settingsUi;
constructor(/** @type {QuickReplySettings} */settings, /** @type {SettingsUi} */settingsUi) {
this.settings = settings;
this.settingsUi = settingsUi;
}
/**
* @param {QuickReply} qr
* @returns {QuickReplySet}
@@ -53,8 +49,6 @@ export class QuickReplyApi {
}
/**
* Executes a quick reply by its index and returns the result.
*
@@ -14,8 +14,6 @@ import { selected_group } from '../../group-chats.js';
export { debounceAsync };
const _VERBOSE = true;
export const debug = (...msg) => _VERBOSE ? console.debug('[QR2]', ...msg) : null;
export const log = (...msg) => _VERBOSE ? console.log('[QR2]', ...msg) : null;
@@ -54,8 +52,6 @@ let autoExec;
export let quickReplyApi;
const loadSets = async () => {
const response = await fetch('/api/settings/get', {
method: 'POST',
@@ -8,8 +8,6 @@ export class AutoExecuteHandler {
/** @type {Boolean[]}*/ preventAutoExecuteStack = [];
constructor(/** @type {QuickReplySettings} */settings) {
this.settings = settings;
}
@@ -20,8 +18,6 @@ export class AutoExecuteHandler {
}
async performAutoExecute(/** @type {QuickReply[]} */qrList) {
for (const qr of qrList) {
this.preventAutoExecuteStack.push(qr.preventAutoExecute);
@@ -27,8 +27,6 @@ export class QuickReply {
}
/**@type {number}*/ id;
/**@type {string}*/ icon;
/**@type {string}*/ label = '';
@@ -89,8 +87,6 @@ export class QuickReply {
}
unrender() {
this.dom?.remove();
this.dom = null;
@@ -169,8 +165,6 @@ export class QuickReply {
}
renderSettings(idx) {
if (!this.settingsDom) {
const item = document.createElement('div'); {
@@ -1769,8 +1763,6 @@ export class QuickReply {
}
delete() {
if (this.onDelete) {
this.unrender();
@@ -1908,8 +1900,6 @@ export class QuickReply {
}
toJSON() {
return {
id: this.id,
@@ -13,8 +13,6 @@ export class QuickReplyConfig {
/**@type {HTMLElement}*/ setListDom;
static from(props) {
props.setList = props.setList?.map(it => QuickReplySetLink.from(it))?.filter(it => it.set) ?? [];
const instance = Object.assign(new this(), props);
@@ -23,8 +21,6 @@ export class QuickReplyConfig {
}
init() {
this.setList.forEach(it => this.hookQuickReplyLink(it));
}
@@ -54,8 +50,6 @@ export class QuickReplyConfig {
}
renderSettingsInto(/**@type {HTMLElement}*/root) {
/**@type {HTMLElement}*/
this.setListDom = root.querySelector('.qr--setList');
@@ -91,8 +85,6 @@ export class QuickReplyConfig {
}
/**
* @param {QuickReplySetLink} qrl
*/
@@ -8,8 +8,6 @@ export class QuickReplyContextLink {
}
/**@type {QuickReplySet}*/ set;
/**@type {Boolean}*/ isChained = false;
@@ -209,8 +209,7 @@ export class QuickReplySet {
addQuickReply(data = {}) {
const id = Math.max(this.idIndex, this.qrList.reduce((max, qr) => Math.max(max, qr.id), 0)) + 1;
data.id =
this.idIndex = id + 1;
data.id = this.idIndex = id + 1;
const qr = QuickReply.from(data);
this.qrList.push(qr);
this.hookQuickReply(qr);
@@ -9,8 +9,6 @@ export class QuickReplySetLink {
}
/**@type {QuickReplySet}*/ set;
/**@type {Boolean}*/ isVisible = true;
@@ -23,8 +21,6 @@ export class QuickReplySetLink {
/**@type {HTMLElement}*/ settingsDom;
renderSettings(idx) {
this.index = idx;
const item = document.createElement('div'); {
@@ -98,8 +94,6 @@ export class QuickReplySetLink {
}
update() {
if (this.onUpdate) {
this.onUpdate(this);
@@ -118,8 +112,6 @@ export class QuickReplySetLink {
}
toJSON() {
return {
set: this.set.name,
@@ -15,8 +15,6 @@ export class QuickReplySettings {
}
/**@type {Boolean}*/ isEnabled = false;
/**@type {Boolean}*/ isCombined = false;
/**@type {Boolean}*/ isPopout = false;
@@ -50,8 +48,6 @@ export class QuickReplySettings {
/**@type {Function}*/ onRequestEditSet;
init() {
this.hookConfig(this.config);
this.hookConfig(this.chatConfig);
@@ -72,8 +68,6 @@ export class QuickReplySettings {
}
save() {
extension_settings.quickReplyV2 = this.toJSON();
saveSettingsDebounced();
@@ -16,15 +16,11 @@ export class SlashCommandHandler {
/** @type {QuickReplyApi} */ api;
constructor(/** @type {QuickReplyApi} */api) {
this.api = api;
}
init() {
function getExecutionIcons(/** @type {QuickReply} */ qr) {
let icons = '';
@@ -783,8 +779,6 @@ export class SlashCommandHandler {
}
getSetByName(name) {
const set = this.api.getSetByName(name);
if (!set) {
@@ -802,8 +796,6 @@ export class SlashCommandHandler {
}
async executeQuickReplyByIndex(idx) {
try {
return await this.api.executeQuickReplyByIndex(idx);
@@ -10,15 +10,11 @@ export class ButtonUi {
/**@type {HTMLElement}*/ popoutDom;
constructor(/**@type {QuickReplySettings}*/settings) {
this.settings = settings;
}
render() {
if (this.settings.isPopout) {
return this.renderPopout();
@@ -57,8 +53,6 @@ export class ButtonUi {
}
renderBar() {
if (!this.dom) {
let buttonHolder;
@@ -100,8 +94,6 @@ export class ButtonUi {
}
renderPopout() {
if (!this.popoutDom) {
let buttonHolder;
@@ -29,18 +29,12 @@ export class SettingsUi {
/**@type {HTMLSelectElement}*/ currentSet;
constructor(/**@type {QuickReplySettings}*/settings) {
this.settings = settings;
settings.onRequestEditSet = (qrs) => this.selectQrSet(qrs);
}
rerender() {
if (!this.dom) return;
const content = this.dom.querySelector('.inline-drawer-content');
@@ -256,8 +250,6 @@ export class SettingsUi {
}
async onIsEnabled() {
this.settings.isEnabled = this.isEnabled.checked;
this.settings.save();
@@ -11,8 +11,6 @@ export class ContextMenu {
/**@type {HTMLElement}*/ menu;
constructor(/**@type {QuickReply}*/qr) {
// this.itemList = items;
this.itemList = this.build(qr).children;
@@ -104,8 +102,6 @@ export class ContextMenu {
}
show({ clientX, clientY }) {
if (this.isActive) return;
this.isActive = true;
@@ -15,8 +15,6 @@ export class MenuItem {
/**@type {function}*/ onExpand;
/**
*
* @param {?string} icon
@@ -80,7 +78,6 @@ export class MenuItem {
}
item.addEventListener('mouseover', () => sub.show(item));
item.addEventListener('mouseleave', () => sub.hide());
}
}
}
@@ -9,8 +9,6 @@ export class SubMenu {
/**@type {HTMLElement}*/ root;
constructor(/**@type {MenuItem[]}*/items) {
this.itemList = items;
}
@@ -29,8 +27,6 @@ export class SubMenu {
}
show(/**@type {HTMLElement}*/parent) {
if (this.isActive) return;
this.isActive = true;
-1
View File
@@ -1031,7 +1031,6 @@ function executeRegexScriptForDebugging(script, text) {
const trailingText = text.substring(lastIndex);
outputText += trailingText;
highlightedOutput += escapeHtml(trailingText);
} catch (e) {
err = (err ? err + '; ' : '') + `Replace error: ${e.message}`;
outputText = text; // Fallback
@@ -115,5 +115,4 @@ jQuery(() => {
returns: 'number of tokens',
helpString: 'Counts the number of tokens in the current chat.',
}));
});
-1
View File
@@ -1043,7 +1043,6 @@ class AllTalkTtsProvider {
// V2: Combine the endpoint with the relative path
return `${this.settings.provider_endpoint}${data.output_file_url}`;
}
} catch (error) {
console.error('[fetchTtsGeneration] Exception caught:', error);
throw error;
@@ -239,7 +239,6 @@ class ChatterboxTtsProvider {
}
this.setupEventListeners();
} catch (error) {
console.error('Error loading Chatterbox settings:', error);
this.updateStatus('Offline');
@@ -518,7 +517,6 @@ class ChatterboxTtsProvider {
});
await audio.play();
} catch (error) {
console.error('Error previewing voice:', error);
this.updateStatus('Ready');
@@ -627,7 +625,6 @@ class ChatterboxTtsProvider {
// Return the response directly - SillyTavern expects a Response object
return response;
} catch (error) {
console.error('Error in generateTts:', error);
this.updateStatus('Ready');
-1
View File
@@ -583,7 +583,6 @@ class CoquiTtsProvider {
$('#coqui_api_model_install_button').show();
return;
}
}
@@ -110,15 +110,11 @@ class CosyVoiceProvider {
//#################//
async getVoice(voiceName) {
if (this.voices.length == 0) {
this.voices = await this.fetchTtsVoiceObjects();
}
const match = this.voices.filter(
v => v.name == voiceName,
)[0];
@@ -130,7 +126,6 @@ class CosyVoiceProvider {
}
async generateTts(text, voiceId) {
const response = await this.fetchTtsGeneration(text, voiceId);
return response;
@@ -198,7 +193,6 @@ class CosyVoiceProvider {
}
// Interface not used
async fetchTtsFromHistory(history_item_id) {
return Promise.resolve(history_item_id);
@@ -124,7 +124,6 @@ export class GoogleNativeTtsProvider {
console.info(`Google TTS: Loaded ${this.voices.length} voices`);
return this.voices;
} catch (error) {
console.error('Failed to fetch Google TTS voices:', error);
throw error;
@@ -151,7 +150,6 @@ export class GoogleNativeTtsProvider {
this.audioElement.src = url;
this.audioElement.play();
this.audioElement.onended = () => URL.revokeObjectURL(url);
} catch (error) {
console.error('TTS Preview Error:', error);
toastr.error(`Could not generate preview: ${error.message}`);
@@ -115,15 +115,11 @@ class GptSovitsV2Provider {
//#################//
async getVoice(voiceName) {
if (this.voices.length == 0) {
this.voices = await this.fetchTtsVoiceObjects();
}
const match = this.voices.filter(
v => v.name == voiceName,
)[0];
@@ -135,7 +131,6 @@ class GptSovitsV2Provider {
}
async generateTts(text, voiceId) {
const response = await this.fetchTtsGeneration(text, voiceId);
return response;
@@ -171,8 +166,6 @@ class GptSovitsV2Provider {
*/
async fetchTtsGeneration(inputText, voiceId, lang = null, forceNoStreaming = false) {
console.info(`Generating new TTS for voice_id ${voiceId}`);
@@ -215,7 +208,6 @@ class GptSovitsV2Provider {
}
// Interface not used
async fetchTtsFromHistory(history_item_id) {
return Promise.resolve(history_item_id);
-9
View File
@@ -1,4 +1,3 @@
import { saveTtsProviderSettings } from './index.js';
export { GSVITtsProvider };
@@ -60,11 +59,9 @@ class GSVITtsProvider {
const characterList = await response.json();
this.characterList = characterList;
this.voices = Object.keys(characterList);
}
get settingsHtml() {
let html = `
<label for="gsvi_api_language">Text Language</label>
@@ -142,11 +139,8 @@ class GSVITtsProvider {
$('#gsvi_batch_size_output').text(this.settings.batch_size);
// Persist settings changes
saveTtsProviderSettings();
}
async loadSettings(settings) {
@@ -197,7 +191,6 @@ class GSVITtsProvider {
}
// Perform a simple readiness check by trying to fetch voiceIds
async checkReady() {
await Promise.allSettled([this.fetchCharacterList()]);
@@ -256,12 +249,10 @@ class GSVITtsProvider {
return `${this.settings.provider_endpoint}/tts?${params.toString()}`;
}
// Interface not used by GSVI TTS
async fetchTtsFromHistory(history_item_id) {
return Promise.resolve(history_item_id);
}
}
-4
View File
@@ -611,7 +611,6 @@ async function processTtsQueue() {
// Pass the full voiceMapKey (e.g., "User ("Quotes")") as well with character name
await tts(segmentText, voiceId, char, voiceMapKey);
} catch (error) {
toastr.error(error.toString());
console.error(error);
@@ -707,7 +706,6 @@ async function processTtsQueue() {
// Clear current job so the segmented jobs can be processed
currentTtsJob = null;
} catch (error) {
toastr.error(error.toString());
console.error(error);
@@ -1286,7 +1284,6 @@ export function getCharacters(unrestricted) {
}
return characters;
}
export function sanitizeId(input) {
@@ -1314,7 +1311,6 @@ function parseVoiceMap(voiceMapString) {
}
/**
* Apply voiceMap based on current voiceMapEntries
*/
-2
View File
@@ -837,7 +837,6 @@ class MiniMaxTtsProvider {
// Backend handles all the complex processing and returns audio data directly
console.debug('MiniMax TTS: Audio response received from backend');
return response;
} catch (error) {
console.error('Error in MiniMax TTS generation:', error);
throw error;
@@ -954,7 +953,6 @@ class MiniMaxTtsProvider {
this.audioElement.onended = null;
this.audioElement.onerror = null;
};
} catch (error) {
console.error('MiniMax TTS Preview Error:', error);
toastr.error(`Could not generate preview: ${error.message}`);
-1
View File
@@ -146,7 +146,6 @@ class OpenAITtsProvider {
}
populateCharacterInstructions() {
const currentCharacters = $('.tts_voicemap_block_char span').map((i, el) => $(el).text()).get();
$('#openai-character-instructions').empty();
@@ -172,5 +172,4 @@ class SileroTtsProvider {
async fetchTtsFromHistory(history_item_id) {
return Promise.resolve(history_item_id);
}
}
-1
View File
@@ -323,5 +323,4 @@ class XTTSTtsProvider {
async fetchTtsFromHistory(history_item_id) {
return Promise.resolve(history_item_id);
}
}
@@ -1456,7 +1456,6 @@ async function onViewStatsClick() {
messageElement.addClass('vectorized');
}
}
}
async function onVectorizeAllFilesClick() {
-1
View File
@@ -13,7 +13,6 @@ export function SaveLocal(target, val) {
export function LoadLocal(target) {
console.debug('LoadLocal -- ' + target);
return localStorage.getItem(target);
}
/**
* @deprecated THIS FUNCTION IS OBSOLETE. DO NOT USE
-1
View File
@@ -76,7 +76,6 @@ export const fuzzySearchCategories = Object.freeze({
* data = filterHelper.applyFilters(data);
*/
export class FilterHelper {
/**
* Cache fuzzy search weighting scores for re-usability, sorting and stuff
*
-1
View File
@@ -2477,7 +2477,6 @@ jQuery(() => {
const value = $(this).prop('checked');
hideMutedSprites = value;
onHideMutedSpritesClick(value);
});
$('#send_textarea').on('keyup', onSendTextareaInput);
$('#groupCurrentMemberPopoutButton').on('click', doCurMemberListPopout);
+4 -5
View File
@@ -59,7 +59,8 @@ export function initInputMarkdown() {
let cursorShift = charsToAdd.length;
let selectedTextandPossibleFormatting = textarea.value.substring(start - possiblePreviousFormattingMargin, end + possiblePreviousFormattingMargin).trim();
if (isTextSelected) { //if text is selected
if (isTextSelected) {
//if text is selected
selectedText = textarea.value.substring(start, end);
if (selectedTextandPossibleFormatting === charsToAdd + selectedText + charsToAdd) {
// If the selected text is already formatted, remove the formatting
@@ -90,7 +91,8 @@ export function initInputMarkdown() {
textarea.focus();
document.execCommand('insertText', false, charsToAdd + selectedText + charsToAdd + possibleAddedSpace);
}
} else {// No text is selected
} else {
// No text is selected
//check 1 character before and after the cursor for non-space characters
if (beforeCaret !== ' ' && afterCaret !== ' ' && afterCaret !== '' && beforeCaret !== '') { //look for caret in the middle of a word
@@ -116,7 +118,6 @@ export function initInputMarkdown() {
}
if (charsToAdd + discoveredWord + charsToAdd === discoveredWordWithPossibleFormatting) {
// Replace the expanded selection with the original discovered word
textarea.focus();
document.execCommand('insertText', false, discoveredWord);
@@ -126,8 +127,6 @@ export function initInputMarkdown() {
textarea.focus();
document.execCommand('insertText', false, charsToAdd + discoveredWord + charsToAdd);
}
} else { //caret is not inside a word, so just add the formatting
textarea.focus();
textarea.setSelectionRange(start, end);
-1
View File
@@ -798,7 +798,6 @@ jQuery(() => {
$('#instruct_system_sequence').prop('readOnly', false);
$('#instruct_system_suffix').prop('readOnly', false);
}
});
$('#instruct_enabled').on('change', function () {
-4
View File
@@ -2279,7 +2279,6 @@ function appendElectronHubOptions(model_list, groupModels = false) {
appendOption(model);
});
}
}
function electronHubSortBy(data, property = 'alphabetically') {
@@ -3985,7 +3984,6 @@ function loadOpenAISettings(data, settings) {
option.value = i;
option.text = item;
$('#settings_preset_openai').append(option);
});
openai_setting_names = settingNames;
@@ -4896,7 +4894,6 @@ function getSiliconflowMaxContext(model, isUnlocked) {
// Return context size if model found, otherwise default to 32k
return Object.entries(contextMap).find(([key]) => model.includes(key))?.[1] || max_32k;
}
/**
@@ -5041,7 +5038,6 @@ async function onModelChange() {
console.log('Claude model changed to', value);
oai_settings.claude_model = value;
$('#model_claude_select').val(oai_settings.claude_model);
}
if ($(this).is('#model_openai_select')) {
-2
View File
@@ -1593,7 +1593,6 @@ export async function showCharConnections() {
highlightPersonas: true,
targetedChar: getCurrentConnectionObj(),
shiftClickHandler: (element, ev) => {
const personaId = $(element).attr('data-pid');
/** @type {PersonaConnection[]} */
@@ -1845,7 +1844,6 @@ async function lockPersonaCallback(_args, value) {
if (isFalseBoolean(value)) {
await setPersonaLockState(false, type);
return 'false';
}
return '';
-1
View File
@@ -478,7 +478,6 @@ export class Popup {
break;
}
}
};
this.dlg.addEventListener('keydown', keyListener.bind(this));
}
-7
View File
@@ -536,7 +536,6 @@ function switchSwipeNumAllMessages() {
var originalSliderValues = [];
async function switchLabMode({ noReset = false } = {}) {
/* if (power_user.enableZenSliders && power_user.enableLabMode) {
toastr.warning("Can't start Lab Mode while Zen Sliders are active")
return
@@ -571,8 +570,6 @@ async function switchLabMode({ noReset = false } = {}) {
$('#amount_gen').attr('min', '1')
.attr('max', '99999')
.attr('step', '1');
} else if (!noReset) {
//re apply the original sliders values to each input
originalSliderValues.forEach(function (slider) {
@@ -628,7 +625,6 @@ async function switchZenSliders() {
});
$('div[id$="_zenslider"]').remove();
}
}
async function CreateZenSliders(elmnt) {
var originalSlider = elmnt;
@@ -1178,7 +1174,6 @@ function applyShadowWidth() {
document.documentElement.style.setProperty('--shadowWidth', String(power_user.shadow_width));
$('#shadow_width_counter').val(power_user.shadow_width);
$('#shadow_width').val(power_user.shadow_width);
}
function applyFontScale(type) {
@@ -2954,7 +2949,6 @@ function setAvgBG() {
} */
function getAverageRGB(imgEl) {
var blockSize = 5, // only visit every 5 pixels
defaultRGB = { r: 0, g: 0, b: 0 }, // for non-supporting envs
canvas = document.createElement('canvas'),
@@ -2994,7 +2988,6 @@ function setAvgBG() {
rgb.b = ~~(rgb.b / count);
return rgb;
}
/**
-1
View File
@@ -514,7 +514,6 @@ class PresetManager {
console.error('Preset could not be renamed', error);
throw new Error('Preset could not be renamed');
}
}
/**
-1
View File
@@ -865,7 +865,6 @@ function selectReasoningTemplateCallback(args, name) {
UI.$select.val(foundName).trigger('change');
!quiet && toastr.success(`Reasoning template "${foundName}" selected`);
return foundName;
}
function registerReasoningSlashCommands() {
-1
View File
@@ -203,7 +203,6 @@ function setSamplerListListeners() {
console.log(samplerName, relatedDOMElement.data(SELECT_SAMPLER.DATA), shouldDisplay);
});
}
function isElementVisibleInDOM(element) {
-2
View File
@@ -4916,7 +4916,6 @@ export async function sendNarratorMessage(args, text) {
}
export async function promptQuietForLoudResponse(who, text) {
let character_id = getContext().characterId;
if (who === 'sys') {
text = 'System: ' + text;
@@ -4955,7 +4954,6 @@ export async function promptQuietForLoudResponse(who, text) {
addOneMessage(message);
await eventSource.emit(event_types.USER_MESSAGE_RENDERED, (chat.length - 1));
await saveChatConditional();
}
async function sendCommentMessage(args, text) {
@@ -26,7 +26,6 @@ import { SlashCommandScope } from './SlashCommandScope.js';
*/
export class SlashCommand {
/**
* Creates a SlashCommand from a properties object.
@@ -48,8 +47,6 @@ export class SlashCommand {
}
/**@type {string}*/ name;
/**@type {(namedArguments:NamedArguments, unnamedArguments:UnnamedArguments)=>string|SlashCommandClosure|Promise<string|SlashCommandClosure>}*/ callback;
/**@type {string}*/ helpString;
@@ -5,7 +5,6 @@ import { SlashCommandExecutor } from './SlashCommandExecutor.js';
import { SlashCommandScope } from './SlashCommandScope.js';
/**@readonly*/
/**@enum {string}*/
export const ARGUMENT_TYPE = {
@@ -10,8 +10,6 @@ export class SlashCommandCommandAutoCompleteOption extends AutoCompleteOption {
}
/**
* @param {SlashCommand} command
* @param {string} name
@@ -18,15 +18,11 @@ export class SlashCommandDebugController {
/** @type {(closure:SlashCommandClosure, executor:SlashCommandExecutor)=>Promise<boolean>} */ onBreakPoint;
testStepping(closure) {
return this.stepStack[this.stack.indexOf(closure)];
}
down(closure) {
this.stack.push(closure);
if (this.stepStack.length < this.stack.length) {
@@ -44,7 +40,6 @@ export class SlashCommandDebugController {
}
resume() {
this.continueResolver?.(false);
this.continuePromise = null;
@@ -18,7 +18,6 @@ export class SlashCommandEnumAutoCompleteOption extends AutoCompleteOption {
/**@type {SlashCommandEnumValue}*/ enumValue;
/**
* @param {SlashCommand} cmd
* @param {SlashCommandEnumValue} enumValue
@@ -48,7 +48,6 @@ export class SlashCommandExecutionError extends Error {
}
constructor(cause, message, commandName, start, end, commandText, fullText) {
super(message, { cause });
this.commandName = commandName;
@@ -109,8 +109,6 @@ export class SlashCommandScope {
}
export class SlashCommandScopeVariableExistsError extends Error {}
-1
View File
@@ -2091,7 +2091,6 @@ function onTagAsFolderClick() {
// If folder display has changed, we have to redraw the character list, otherwise this folders state would not change
printCharactersDebounced();
saveSettingsDebounced();
}
function updateDrawTagFolder(element, tag) {
-1
View File
@@ -802,7 +802,6 @@ async function getStatusTextgen() {
console.info('Status check aborted.', err.reason);
} else {
console.error('Error getting status', err);
}
setOnlineStatus('no_connection');
}
-4
View File
@@ -455,7 +455,6 @@ async function changeName(handle, name, callback) {
toastr.success('Name changed successfully', 'Name Changed');
callback();
} catch (error) {
console.error('Error changing name:', error);
}
@@ -495,7 +494,6 @@ async function restoreSnapshot(name, callback) {
} catch (error) {
console.error('Error restoring snapshot:', error);
}
}
/**
@@ -601,7 +599,6 @@ async function viewSettingsSnapshots() {
const content = await loadSnapshotContent(snapshot.name);
contentBlock.val(content);
}
});
template.find('.snapshotList').append(snapshotBlock);
}
@@ -667,7 +664,6 @@ async function resetEverything(callback) {
} catch (error) {
console.error('Error resetting everything:', error);
}
}
async function openUserProfile() {
-1
View File
@@ -2310,7 +2310,6 @@ export function highlightRegex(regexStr) {
flags: new RegExp('(?<=\\/)([gimsuy]*)$', 'g'), // Match trailing flags
delimiters: new RegExp('^\\/|(?<![\\\\<])\\/', 'g'), // Match leading or trailing delimiters
};
} catch (error) {
return {
brackets: new RegExp('(\\\\)?\\[.*?\\]', 'g'), // Non-escaped square brackets
-2
View File
@@ -675,7 +675,6 @@ class WorldInfoTimedEffects {
console.log('[WI] Timed effect "delay" applied to entry', entry);
}
}
}
/**
@@ -4495,7 +4494,6 @@ function parseDecorators(content) {
}
return [[], content];
}
/**
-2
View File
@@ -111,7 +111,6 @@ router.post('/get', async (request, response) => {
try {
if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) {
ensureFoldersExist(request.user.directories);
const folders = fs.readdirSync(folderPath, { withFileTypes: true })
@@ -346,7 +345,6 @@ router.post('/character', async (request, response) => {
let output = [];
try {
if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) {
// Live2d assets
if (category == 'live2d') {
const folders = fs.readdirSync(folderPath, { withFileTypes: true });
@@ -541,7 +541,6 @@ llamacpp.post('/props', async function (request, response) {
console.debug('LlamaCpp props response:', data);
return response.send(data);
} catch (error) {
console.error(error);
return response.sendStatus(500);
@@ -591,7 +590,6 @@ llamacpp.post('/slots', async function (request, response) {
console.debug('LlamaCpp slots response:', data);
return response.send(data);
} catch (error) {
console.error(error);
return response.sendStatus(500);
+2 -2
View File
@@ -639,7 +639,6 @@ function charaFormatData(data, directories) {
if (file && file.entries) {
_.set(char, 'data.character_book', convertWorldInfoToCharacterBook(data.world, file.entries));
}
} catch {
console.warn(`Failed to read world info file: ${data.world}. Character book will not be available.`);
}
@@ -921,7 +920,8 @@ async function importFromJson(uploadPath, { request }, preservedFileName) {
let charJSON = JSON.stringify(char);
const result = await writeCharacterData(DEFAULT_AVATAR_PATH, charJSON, pngName, request);
return result ? pngName : '';
} else if (jsonData.char_name !== undefined) {//json Pygmalion notepad
} else if (jsonData.char_name !== undefined) {
//json Pygmalion notepad
console.info('Importing from gradio json');
jsonData.char_name = sanitize(jsonData.char_name);
if (jsonData.creator_notes) {
-2
View File
@@ -367,7 +367,6 @@ router.post('/version', async (request, response) => {
const { isUpToDate, remoteUrl } = await checkIfRepoIsUpToDate(extensionPath);
return response.send({ currentBranchName, currentCommitHash, isUpToDate, remoteUrl });
} catch (error) {
console.error('Getting extension version failed', error);
return response.status(500).send(`Server Error: ${error.message}`);
@@ -406,7 +405,6 @@ router.post('/delete', async (request, response) => {
console.info(`Extension has been deleted at ${extensionPath}`);
return response.send(`Extension has been deleted at ${extensionPath}`);
} catch (error) {
console.error('Deleting custom content failed', error);
return response.status(500).send(`Server Error: ${error.message}`);
-2
View File
@@ -256,7 +256,6 @@ router.post('/caption-image', async (request, response) => {
console.info(status);
if (status.state === HordeAsyncRequestStates.done) {
if (status.forms === undefined) {
console.error('Image interrogation request failed: no forms found.');
return response.sendStatus(500);
@@ -278,7 +277,6 @@ router.post('/caption-image', async (request, response) => {
return response.sendStatus(503);
}
}
} catch (error) {
console.error(error);
response.sendStatus(500);
-1
View File
@@ -442,7 +442,6 @@ router.post('/', async function (request, response) {
}
return response.status(400).json({ error: 'Invalid request format.' });
} catch (error) {
console.error('[ImageMetadata] API error:', error);
return response.status(500).json({ error: 'Internal server error.' });
-2
View File
@@ -189,7 +189,6 @@ router.post('/generate-voice', async (request, response) => {
response.setHeader('Content-Length', audioBytes.length);
return response.send(Buffer.from(audioBytes));
} catch (conversionError) {
console.error('MiniMax TTS: Audio conversion error:', conversionError);
return response.status(500).json({ error: `Audio data conversion failed: ${conversionError.message}` });
@@ -222,7 +221,6 @@ router.post('/generate-voice', async (request, response) => {
console.error('MiniMax TTS: No valid audio data in response:', responseData);
return response.status(500).json({ error: `API Error: ${errorMessage}` });
}
} catch (error) {
console.error('MiniMax TTS generation failed:', error);
return response.status(500).json({ error: 'Internal server error' });
-1
View File
@@ -158,7 +158,6 @@ router.post('/samplers', async (request, response) => {
const data = await result.json();
const names = data.map(x => x.name);
return response.send(names);
} catch (error) {
console.error(error);
return response.sendStatus(500);
-1
View File
@@ -301,7 +301,6 @@ publicRouter.get('/', async function (request, response) {
// Send a 404 so the frontend can display a placeholder
return response.sendStatus(404);
} catch (error) {
console.error('Failed getting thumbnail', error);
return response.sendStatus(500);
-1
View File
@@ -118,7 +118,6 @@ export function postProcessPrompt(messages, type, names) {
* @copyright Prompt Conversion script taken from RisuAI by kwaroran (GPLv3).
*/
export function convertClaudePrompt(messages, addAssistantPostfix, addAssistantPrefill, withSysPromptSupport, useSystemPrompt, addSysHumanMsg, excludePrefixes) {
//Prepare messages for claude.
//When 'Exclude Human/Assistant prefixes' checked, setting messages role to the 'system'(last message is exception).
if (messages.length > 0) {
-1
View File
@@ -1012,7 +1012,6 @@ export async function canResolve(name, useIPv6 = true, useIPv4 = true) {
}
return v6Resolved || v4Resolved;
} catch (error) {
return false;
}