SillyTavern/public/scripts/BulkEditOverlay.js

563 lines
19 KiB
JavaScript
Raw Normal View History

2023-10-21 15:12:09 +02:00
"use strict";
import {
callPopup,
2023-11-04 19:33:15 +01:00
characters,
deleteCharacter,
2023-10-21 15:12:09 +02:00
event_types,
eventSource,
getCharacters,
2023-11-04 19:33:15 +01:00
getRequestHeaders,
this_chid
2023-10-21 15:12:09 +02:00
} from "../script.js";
2023-11-05 18:23:14 +01:00
2023-10-21 15:12:09 +02:00
import {favsToHotswap} from "./RossAscends-mods.js";
import {convertCharacterToPersona} from "./personas.js";
2023-11-04 19:33:15 +01:00
import {createTagInput, getTagKeyForCharacter, tag_map} from "./tags.js";
2023-10-21 15:12:09 +02:00
2023-11-05 18:23:14 +01:00
// Utility object for popup messages.
2023-10-21 15:12:09 +02:00
const popupMessage = {
deleteChat(characterCount) {
return `<h3>Delete ${characterCount} characters?</h3>
<b>THIS IS PERMANENT!<br><br>
<label for="del_char_checkbox" class="checkbox_label justifyCenter">
<input type="checkbox" id="del_char_checkbox" />
<span>Also delete the chat files</span>
</label><br></b>`;
},
}
2023-11-05 18:23:14 +01:00
/**
* Static object representing the actions of the
* character context menu override.
*/
2023-10-21 15:12:09 +02:00
class CharacterContextMenu {
2023-11-05 18:23:14 +01:00
/**
* Tag one or more characters,
* opens a popup.
*
* @param selectedCharacters
*/
2023-11-04 19:33:15 +01:00
static tag = (selectedCharacters) => {
BulkTagPopupHandler.show(selectedCharacters);
}
2023-10-21 15:12:09 +02:00
/**
2023-11-05 18:23:14 +01:00
* Duplicate one or more characters
2023-10-21 15:12:09 +02:00
*
* @param characterId
* @returns {Promise<Response>}
*/
static duplicate = async (characterId) => {
2023-11-05 18:23:14 +01:00
const character = CharacterContextMenu.#getCharacter(characterId);
2023-10-21 15:12:09 +02:00
return fetch('/dupecharacter', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ avatar_url: character.avatar }),
});
}
/**
* Favorite a character
2023-11-05 18:23:14 +01:00
* and highlight it.
2023-10-21 15:12:09 +02:00
*
* @param characterId
* @returns {Promise<void>}
*/
static favorite = async (characterId) => {
2023-11-05 18:23:14 +01:00
const character = CharacterContextMenu.#getCharacter(characterId);
// Only set fav for V2 spec
2023-10-21 15:12:09 +02:00
const data = {
name: character.name,
avatar: character.avatar,
data: {
extensions: {
fav: !character.data.extensions.fav
}
}
};
return fetch('/v2/editcharacterattribute', {
method: "POST",
headers: getRequestHeaders(),
body: JSON.stringify(data),
}).then((response) => {
2023-11-05 18:23:14 +01:00
if (response.ok) {
const element = document.getElementById(`CharID${characterId}`);
element.classList.toggle('is_fav');
} else {
response.json().then(json => toastr.error('Character not saved. Error: ' + json.message + '. Field: ' + json.error));
}
2023-10-21 15:12:09 +02:00
});
}
/**
2023-11-05 18:23:14 +01:00
* Convert one or more characters to persona,
* may open a popup for one or more characters.
*
* @param characterId
* @returns {Promise<void>}
*/
static persona = async (characterId) => await convertCharacterToPersona(characterId);
2023-10-21 15:12:09 +02:00
2023-11-05 18:23:14 +01:00
/**
* Delete one or more characters,
* opens a popup.
*
* @param characterId
* @param deleteChats
* @returns {Promise<void>}
*/
2023-10-21 15:12:09 +02:00
static delete = async (characterId, deleteChats = false) => {
2023-11-05 18:23:14 +01:00
const character = CharacterContextMenu.#getCharacter(characterId);
2023-10-21 15:12:09 +02:00
return fetch('/deletecharacter', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ avatar_url: character.avatar , delete_chats: deleteChats }),
cache: 'no-cache',
}).then(response => {
if (response.ok) {
deleteCharacter(character.name, character.avatar).then(() => {
if (deleteChats) {
fetch("/getallchatsofcharacter", {
method: 'POST',
body: JSON.stringify({ avatar_url: character.avatar }),
headers: getRequestHeaders(),
}).then( (response) => {
let data = response.json();
data = Object.values(data);
const pastChats = data.sort((a, b) => a["file_name"].localeCompare(b["file_name"])).reverse();
for (const chat of pastChats) {
const name = chat.file_name.replace('.jsonl', '');
eventSource.emit(event_types.CHAT_DELETED, name);
}
});
}
})
}
2023-11-05 18:23:14 +01:00
eventSource.emit('characterDeleted', { id: this_chid, character: characters[this_chid] });
2023-10-21 15:12:09 +02:00
});
}
2023-11-05 18:23:14 +01:00
static #getCharacter = (characterId) => characters[characterId] ?? null;
2023-10-21 15:12:09 +02:00
2023-11-05 18:23:14 +01:00
/**
* Show the context menu at the given position
*
* @param positionX
* @param positionY
*/
2023-10-21 15:12:09 +02:00
static show = (positionX, positionY) => {
let contextMenu = document.getElementById(BulkEditOverlay.contextMenuId);
2023-10-21 15:12:09 +02:00
contextMenu.style.left = `${positionX}px`;
contextMenu.style.top = `${positionY}px`;
document.getElementById(BulkEditOverlay.contextMenuId).classList.remove('hidden');
2023-10-21 15:12:09 +02:00
}
2023-11-05 18:23:14 +01:00
/**
* Hide the context menu
*/
static hide = () => document.getElementById(BulkEditOverlay.contextMenuId).classList.add('hidden');
2023-10-21 15:12:09 +02:00
2023-11-05 18:23:14 +01:00
/**
* Sets up the context menu for the given overlay
*
* @param characterGroupOverlay
*/
2023-10-21 15:12:09 +02:00
constructor(characterGroupOverlay) {
const contextMenuItems = [
{id: 'character_context_menu_favorite', callback: characterGroupOverlay.handleContextMenuFavorite},
{id: 'character_context_menu_duplicate', callback: characterGroupOverlay.handleContextMenuDuplicate},
{id: 'character_context_menu_delete', callback: characterGroupOverlay.handleContextMenuDelete},
2023-11-04 19:33:15 +01:00
{id: 'character_context_menu_persona', callback: characterGroupOverlay.handleContextMenuPersona},
{id: 'character_context_menu_tag', callback: characterGroupOverlay.handleContextMenuTag}
2023-10-21 15:12:09 +02:00
];
contextMenuItems.forEach(contextMenuItem => document.getElementById(contextMenuItem.id).addEventListener('click', contextMenuItem.callback))
}
}
2023-11-04 19:33:15 +01:00
/**
2023-11-05 18:23:14 +01:00
* Represents a tag control not bound to a single character
2023-11-04 19:33:15 +01:00
*/
class BulkTagPopupHandler {
static #getHtml = (characterIds) => {
const characterData = JSON.stringify({characterIds: characterIds});
return `<div id="bulk_tag_shadow_popup">
<div id="bulk_tag_popup">
<div id="bulk_tag_popup_holder">
<h3 class="m-b-1">Add tags to ${characterIds.length} characters</h3>
<br>
<div id="bulk_tags_div" class="marginBot5" data-characters='${characterData}'>
<div class="tag_controls">
<input id="bulkTagInput" class="text_pole tag_input wide100p margin0" data-i18n="[placeholder]Search / Create Tags" placeholder="Search / Create tags" maxlength="25" />
<div class="tags_view menu_button fa-solid fa-tags" title="View all tags" data-i18n="[title]View all tags"></div>
</div>
<div id="bulkTagList" class="m-t-1 tags"></div>
</div>
<div id="dialogue_popup_controls" class="m-t-1">
<div id="bulk_tag_popup_cancel" class="menu_button" data-i18n="Cancel">Close</div>
<div id="bulk_tag_popup_reset" class="menu_button" data-i18n="Cancel">Remove all</div>
</div>
</div>
</div>
</div>
`
};
2023-11-05 18:23:14 +01:00
/**
* Append and show the tag control
*
* @param characters - The characters assigned to this control
*/
2023-11-04 19:33:15 +01:00
static show(characters) {
document.body.insertAdjacentHTML('beforeend', this.#getHtml(characters));
createTagInput('#bulkTagInput', '#bulkTagList');
document.querySelector('#bulk_tag_popup_cancel').addEventListener('click', this.hide.bind(this));
document.querySelector('#bulk_tag_popup_reset').addEventListener('click', this.resetTags.bind(this, characters));
}
2023-11-05 18:23:14 +01:00
/**
* Hide and remove the tag control
*/
2023-11-04 19:33:15 +01:00
static hide() {
let popupElement = document.querySelector('#bulk_tag_shadow_popup');
if (popupElement) {
document.body.removeChild(popupElement);
}
}
2023-11-05 18:23:14 +01:00
/**
* Empty the tag map for the given characters
*
* @param characterIds
*/
2023-11-04 19:33:15 +01:00
static resetTags(characterIds) {
characterIds.forEach((characterId) => {
const key = getTagKeyForCharacter(characterId);
if (key) tag_map[key] = [];
});
}
}
2023-11-05 18:23:14 +01:00
class CharacterGroupOverlayState {
/**
*
* @type {number}
*/
static browse = 0;
/**
*
* @type {number}
*/
static select = 1;
}
2023-11-04 19:33:15 +01:00
/**
* Implement a SingletonPattern, allowing access to the group overlay instance
* from everywhere via (new CharacterGroupOverlay())
*
* @type BulkEditOverlay
*/
let bulkEditOverlayInstance = null;
class BulkEditOverlay {
2023-10-21 15:12:09 +02:00
static containerId = 'rm_print_characters_block';
static contextMenuId = 'character_context_menu';
static characterClass = 'character_select';
static selectModeClass = 'group_overlay_mode_select';
static selectedClass = 'character_selected';
static legacySelectedClass = 'bulk_select_checkbox';
2023-10-21 15:12:09 +02:00
2023-11-06 15:31:27 +01:00
static longPressDelay = 2800;
2023-10-21 15:12:09 +02:00
#state = CharacterGroupOverlayState.browse;
#longPress = false;
#stateChangeCallbacks = [];
#selectedCharacters = [];
/**
* @type HTMLElement
*/
container = null;
get state() {
return this.#state;
}
set state(newState) {
if (this.#state === newState) return;
eventSource.emit(event_types.CHARACTER_GROUP_OVERLAY_STATE_CHANGE_BEFORE, newState)
.then(() => {
this.#state = newState;
eventSource.emit(event_types.CHARACTER_GROUP_OVERLAY_STATE_CHANGE_AFTER, this.state)
});
}
get isLongPress() {
return this.#longPress;
}
set isLongPress(longPress) {
this.#longPress = longPress;
}
get stateChangeCallbacks() {
return this.#stateChangeCallbacks;
}
2023-11-04 19:33:15 +01:00
/**
*
* @returns {*[]}
*/
2023-10-21 15:12:09 +02:00
get selectedCharacters() {
return this.#selectedCharacters;
}
constructor() {
2023-11-04 19:33:15 +01:00
if (bulkEditOverlayInstance instanceof BulkEditOverlay)
return bulkEditOverlayInstance
2023-10-21 15:12:09 +02:00
this.container = document.getElementById(BulkEditOverlay.containerId);
2023-10-21 15:12:09 +02:00
this.container.addEventListener('click', this.handleCancelClick);
eventSource.on(event_types.CHARACTER_GROUP_OVERLAY_STATE_CHANGE_AFTER, this.handleStateChange);
2023-11-04 19:33:15 +01:00
bulkEditOverlayInstance = Object.freeze(this);
2023-10-21 15:12:09 +02:00
}
2023-11-05 18:23:14 +01:00
/**
* Set the overlay to browse mode
*/
2023-10-21 15:12:09 +02:00
browseState = () => this.state = CharacterGroupOverlayState.browse;
2023-11-05 18:23:14 +01:00
/**
* Set the overlay to select mode
*/
2023-10-21 15:12:09 +02:00
selectState = () => this.state = CharacterGroupOverlayState.select;
/**
* Set up a Sortable grid for the loaded page
*/
onPageLoad = () => {
this.browseState();
2023-10-21 15:12:09 +02:00
2023-11-06 15:31:27 +01:00
const elements = this.#getEnabledElements();
2023-10-21 15:12:09 +02:00
elements.forEach(element => element.addEventListener('touchstart', this.handleHold));
elements.forEach(element => element.addEventListener('mousedown', this.handleHold));
2023-10-21 15:12:09 +02:00
elements.forEach(element => element.addEventListener('touchend', this.handleLongPressEnd));
elements.forEach(element => element.addEventListener('mouseup', this.handleLongPressEnd));
elements.forEach(element => element.addEventListener('dragend', this.handleLongPressEnd));
const grid = document.getElementById(BulkEditOverlay.containerId);
2023-10-21 15:12:09 +02:00
grid.addEventListener('click', this.handleCancelClick);
}
2023-11-05 18:23:14 +01:00
/**
* Handle state changes
*
*
*/
handleStateChange = () => {
switch (this.state) {
case CharacterGroupOverlayState.browse:
this.container.classList.remove(BulkEditOverlay.selectModeClass);
this.#enableClickEventsForCharacters();
this.clearSelectedCharacters();
this.disableContextMenu();
this.#disableBulkEditButtonHighlight();
CharacterContextMenu.hide();
break;
case CharacterGroupOverlayState.select:
this.container.classList.add(BulkEditOverlay.selectModeClass);
this.#disableClickEventsForCharacters();
this.enableContextMenu();
this.#enableBulkEditButtonHighlight();
break;
}
this.stateChangeCallbacks.forEach(callback => callback(this.state));
}
2023-10-21 15:12:09 +02:00
/**
* Block the browsers native context menu and
* set a click event to hide the custom context menu.
*/
enableContextMenu = () => {
document.addEventListener('contextmenu', this.handleContextMenuShow);
document.addEventListener('click', this.handleContextMenuHide);
}
/**
* Remove event listeners, allowing the native browser context
* menu to be opened.
*/
disableContextMenu = () => {
document.removeEventListener('contextmenu', this.handleContextMenuShow);
document.removeEventListener('click', this.handleContextMenuHide);
}
handleHold = (event) => {
2023-11-06 15:31:27 +01:00
if (0 !== event.button && event.type !== 'touchstart') return;
// Prevent call for mobile browser context menu on long-press.
event.preventDefault();
event.stopPropagation();
2023-10-21 15:12:09 +02:00
this.isLongPress = true;
setTimeout(() => {
if (this.isLongPress) {
2023-11-06 15:31:27 +01:00
if (this.state === CharacterGroupOverlayState.browse)
this.selectState();
else if (this.state === CharacterGroupOverlayState.select)
CharacterContextMenu.show(...this.#getContextMenuPosition(event));
2023-10-21 15:12:09 +02:00
}
2023-11-06 15:31:27 +01:00
}, BulkEditOverlay.longPressDelay);
2023-10-21 15:12:09 +02:00
}
handleLongPressEnd = () => {
this.isLongPress = false;
}
handleCancelClick = () => {
this.state = CharacterGroupOverlayState.browse;
}
2023-11-06 15:31:27 +01:00
/**
* Returns the position of the mouse/touch location
*
* @param event
* @returns {(boolean|number|*)[]}
*/
#getContextMenuPosition = (event) => [
event.clientX || event.touches[0].clientX,
event.clientY || event.touches[0].clientY,
];
#enableClickEventsForCharacters = () => this.#getEnabledElements().forEach(element => element.removeEventListener('click', this.toggleCharacterSelected));
2023-11-06 15:31:27 +01:00
#disableClickEventsForCharacters = () => this.#getEnabledElements().forEach(element => element.addEventListener('click', this.toggleCharacterSelected));
#enableBulkEditButtonHighlight = () => document.getElementById('bulkEditButton').classList.add('bulk_edit_overlay_active');
#disableBulkEditButtonHighlight = () => document.getElementById('bulkEditButton').classList.remove('bulk_edit_overlay_active');
2023-11-06 15:31:27 +01:00
#getEnabledElements = () => [...this.container.getElementsByClassName(BulkEditOverlay.characterClass)];
2023-10-21 15:12:09 +02:00
toggleCharacterSelected = event => {
event.stopPropagation();
const character = event.currentTarget;
const characterId = character.getAttribute('chid');
const alreadySelected = this.selectedCharacters.includes(characterId)
2023-11-06 15:31:27 +01:00
const legacyBulkEditCheckbox = character.querySelector('.' + BulkEditOverlay.legacySelectedClass);
2023-10-21 15:12:09 +02:00
if (alreadySelected) {
character.classList.remove(BulkEditOverlay.selectedClass);
2023-11-06 15:31:27 +01:00
if (legacyBulkEditCheckbox) legacyBulkEditCheckbox.checked = false;
2023-10-21 15:12:09 +02:00
this.dismissCharacter(characterId);
} else {
character.classList.add(BulkEditOverlay.selectedClass)
2023-11-06 15:31:27 +01:00
if (legacyBulkEditCheckbox) legacyBulkEditCheckbox.checked = true;
2023-10-21 15:12:09 +02:00
this.selectCharacter(characterId);
}
}
handleContextMenuShow = (event) => {
event.preventDefault();
document.getElementById(BulkEditOverlay.containerId).style.pointerEvents = 'none';
2023-11-06 15:31:27 +01:00
CharacterContextMenu.show(...this.#getContextMenuPosition(event));
2023-10-21 15:12:09 +02:00
}
handleContextMenuHide = (event) => {
document.getElementById(BulkEditOverlay.containerId).style.pointerEvents = '';
let contextMenu = document.getElementById(BulkEditOverlay.contextMenuId);
2023-10-21 15:12:09 +02:00
if (false === contextMenu.contains(event.target)) {
CharacterContextMenu.hide();
}
}
2023-11-06 15:31:27 +01:00
/**
* Concurrently handle character favorite requests.
*
* @returns {Promise<number>}
*/
2023-10-21 15:12:09 +02:00
handleContextMenuFavorite = () => Promise.all(this.selectedCharacters.map(async characterId => CharacterContextMenu.favorite(characterId)))
.then(() => getCharacters())
.then(() => favsToHotswap())
.then(() => this.browseState())
2023-11-06 15:31:27 +01:00
/**
* Concurrently handle character duplicate requests.
*
* @returns {Promise<number>}
*/
2023-10-21 15:12:09 +02:00
handleContextMenuDuplicate = () => Promise.all(this.selectedCharacters.map(async characterId => CharacterContextMenu.duplicate(characterId)))
.then(() => getCharacters())
.then(() => this.browseState())
/**
* Sequentially handle all character-to-persona conversions.
*
* @returns {Promise<void>}
*/
handleContextMenuPersona = async () => {
for (const characterId of this.selectedCharacters) {
await CharacterContextMenu.persona(characterId)
}
this.browseState();
}
2023-10-21 15:12:09 +02:00
2023-11-06 15:31:27 +01:00
/**
* Request user input before concurrently handle deletion
* requests.
*
* @returns {Promise<number>}
*/
2023-10-21 15:12:09 +02:00
handleContextMenuDelete = () => {
callPopup(
popupMessage.deleteChat(this.selectedCharacters.length), null)
.then(deleteChats =>
Promise.all(this.selectedCharacters.map(async characterId => CharacterContextMenu.delete(characterId, deleteChats)))
.then(() => getCharacters())
.then(() => this.browseState())
);
}
2023-11-06 15:31:27 +01:00
/**
* Attaches and opens the tag menu
*/
2023-11-04 19:33:15 +01:00
handleContextMenuTag = () => {
CharacterContextMenu.tag(this.selectedCharacters);
}
2023-10-21 15:12:09 +02:00
addStateChangeCallback = callback => this.stateChangeCallbacks.push(callback);
selectCharacter = characterId => this.selectedCharacters.push(String(characterId));
dismissCharacter = characterId => this.#selectedCharacters = this.selectedCharacters.filter(item => String(characterId) !== item);
2023-11-05 16:57:14 +01:00
/**
* Clears internal character storage and
* removes visual highlight.
*/
2023-10-21 15:12:09 +02:00
clearSelectedCharacters = () => {
2023-11-05 16:57:14 +01:00
document.querySelectorAll('#' + BulkEditOverlay.containerId + ' .' + BulkEditOverlay.selectedClass)
.forEach( element => element.classList.remove(BulkEditOverlay.selectedClass));
2023-10-21 15:12:09 +02:00
this.selectedCharacters.length = 0;
}
}
export {CharacterGroupOverlayState, CharacterContextMenu, BulkEditOverlay};