Files
SillyTavern/public/scripts/server-history.js
T
GregW6andCohee 1547a53d7c Refactor: Replace Deprecated Code (#4221)
* refactor: ♻️ Replace deprecated code defined within this repository

- Replace ““/public/scripts.js” > `callPopup`” with ““/public/scripts/popup.js” > `callGenericPopup`”.
- Replace ““/public/scripts/tokenizers.js” > `getTokenCount`” with ““/public/scripts/tokenizers.js” > `getTokenCountAsync`”.
- Replace ““/public/scripts/extensions/assets/index.js” > `executeSlashCommands`” with ““/public/scripts/extensions/assets/index.js” > `executeSlashCommandsWithOptions`”.

* refactor: ♻️ Replace deprecated code from standard library

1. Replace set of deprecated `escape` and deprecated `unescape` functions with `encodeURIComponent` and `decodeURIComponent` functions.
2. Replace set of `encodeURIComponent` and deprecated `unescape` functions with a custom `convertTextToBinaryString` function.

* refactor: ♻️ Replace deprecated code imported from external library

All of them is from jQuery.
1. Replace `$(document).ready(() => { ... })` → `jQuery(() => { ... })`.
2. Replace event type direct calls.
    1) Change
        - `$('...').change(function () { ... })` → `$('...').on('change', function () { ... })`.
    2) Click
        - `$('...').click(function () { ... })` → `$('...').on('click', function () { ... })`.
        - `$('...').click()` → `$('...').trigger('click')`.
    3) Focus
        - `$('...').focus(function () { ... })` → `$('...').on('focus', function () { ... })`.
        - `$('...').focus()` → `$('...').trigger('focus')`.
    4) Blur
        - `$('...').blur(function () { ... })` → `$('...').on('blur', function () { ... })`.
    5) Keyup
        - `$('...').keyup(function () { ... })` → `$('...').on('keyup', function () { ... })`.

* refactor(Attachment): ♻️ Merge `convertTextToBinaryString` and `convertTextToBase64`

`convertTextToBase64` function use `Uint8Array.prototype.toBase64` if supported by the Browser and use a combination of `Window.btoa` and `String.fromCharCode` as fallback.

* fix: 🐛 Fix Bind World Info to Character Card

Using the new `Popup` class.

* fix: 🐛 Fix Bind World Info to Character Card

Using the new `Popup` class.

* refactor: 🐛 Refactor and fix Character World Info popup

Add singleton back and some optimization.

-   **🛡️ Singleton Pattern:** Implemented a singleton pattern using the `characterWorldPopup` variable. This prevents multiple instances of the popup from being created, ensuring a clean and predictable UI. If the popup is already open, it will be brought into focus instead of creating a duplicate.
-   **♻️ Improved Readability:** The event handling logic has been extracted into clearly named functions (`handlePrimaryWorldSelect`, `handleExtrasWorldSelect`), making the `Popup` constructor cleaner and the overall code more readable and maintainable.
-   **⚙️ Optimized Performance:** The new implementation caches frequently accessed values and jQuery selectors, reducing redundant DOM lookups and improving performance.

---

* refactor(Chat): ♻️ Modernize chat deletion confirmation

Replaces the deprecated `callPopup` with the modern `callGenericPopup` for the chat deletion confirmation dialog.

* Fix /delchat command

* Remove unused code

* Fix type. Change value to debug log

* Remove value logs

* Remove singleton pattern for openCharacterWorldPopup

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-04 19:42:51 +03:00

87 lines
2.6 KiB
JavaScript

import { saveSettingsDebounced } from '../script.js';
import { power_user } from './power-user.js';
import { isValidUrl } from './utils.js';
/**
* @param {{ term: string; }} request
* @param {function} resolve
* @param {string} serverLabel
*/
function findServers(request, resolve, serverLabel) {
if (!power_user.servers) {
power_user.servers = [];
}
const needle = request.term.toLowerCase();
const result = power_user.servers.filter(x => x.label == serverLabel).sort((a, b) => b.lastConnection - a.lastConnection).map(x => x.url).slice(0, 5);
const hasExactMatch = result.findIndex(x => x.toLowerCase() == needle) !== -1;
if (request.term && !hasExactMatch) {
result.unshift(request.term);
}
resolve(result);
}
function selectServer(event, ui, serverLabel) {
// unfocus the input
$(event.target).val(ui.item.value).trigger('input').trigger('blur');
$('[data-server-connect]').each(function () {
const serverLabels = String($(this).data('server-connect')).split(',');
if (serverLabels.includes(serverLabel)) {
$(this).trigger('click');
}
});
}
function createServerAutocomplete() {
const inputElement = $(this);
const serverLabel = inputElement.data('server-history');
inputElement
.autocomplete({
source: (i, o) => findServers(i, o, serverLabel),
select: (e, u) => selectServer(e, u, serverLabel),
minLength: 0,
})
.on('focus', onInputFocus); // <== show tag list on click
}
function onInputFocus() {
$(this).autocomplete('search', $(this).val());
}
function onServerConnectClick() {
const serverLabels = String($(this).data('server-connect')).split(',');
serverLabels.forEach(serverLabel => {
if (!power_user.servers) {
power_user.servers = [];
}
const value = String($(`[data-server-history="${serverLabel}"]`).val()).toLowerCase().trim();
// Don't save empty values or invalid URLs
if (!value || !isValidUrl(value)) {
return;
}
const server = power_user.servers.find(x => x.url === value && x.label === serverLabel);
if (!server) {
power_user.servers.push({ label: serverLabel, url: value, lastConnection: Date.now() });
} else {
server.lastConnection = Date.now();
}
saveSettingsDebounced();
});
}
export function initServerHistory() {
$('[data-server-history]').each(createServerAutocomplete);
$(document).on('click', '[data-server-connect]', onServerConnectClick);
}