Preset Regex: refactor regex scope detection (#4618)

* refactor: explicit type for regex scope + feat: bulk move regex

* fix: eslint

* i18n: polish

* refactor: jsdoc + use object type for option

* fix: default return type for `getScriptsByType`

* refactor: simplify

* refactor: share default options

* refactor: remove unrequired css

* fix: move regexes to global + refactor: make regex operation interfaces more consistant

---------

Co-authored-by: ZoinkCN <zoinkcn@outlook.com>
This commit is contained in:
StageDog
2025-10-07 22:30:11 +03:00
committed by GitHub
co-authored by ZoinkCN
parent 7296d89b58
commit f15c91fa8e
6 changed files with 283 additions and 130 deletions
+3 -3
View File
@@ -1677,9 +1677,9 @@
"ext_regex_global_scripts_desc": "影响所有角色,保存在本地设定中",
"No scripts found": "没有找到脚本",
"ext_regex_scoped_scripts": "局部正则脚本",
"ext_regex_scoped_scripts_desc": "只影响当前角色,保存在角色卡片中",
"ext_regex_disallow_scoped": "不允许使用局部正则",
"ext_regex_allow_scoped": "允许使用局部正则",
"ext_regex_scoped_scripts_desc": "只影响当前角色,保存在角色卡片中",
"Regex Editor": "正则表达式编辑器",
"Test Mode": "测试模式",
"ext_regex_desc": "“正则”是一个使用“正则表达式”来查找/替换字符串的工具。如果您想了解更多信息,请点击标题旁边的“?”。",
@@ -1728,8 +1728,8 @@
"ext_regex_disable_script": "禁用脚本",
"ext_regex_enable_script": "启用脚本",
"ext_regex_edit_script": "编辑脚本",
"ext_regex_move_to_global": "移至全局脚本",
"ext_regex_move_to_scoped": "移至作用域脚本",
"ext_regex_move_to_global": "移至全局",
"ext_regex_move_to_scoped": "移至局部",
"ext_regex_export_script": "导出脚本",
"ext_regex_delete_script": "删除脚本",
"Trigger Stable Diffusion": "触发Stable Diffusion",
+10 -1
View File
@@ -31,7 +31,8 @@
<small data-i18n="ext_regex_debugger">Debugger</small>
</div>
</div>
<div class="regex_bulk_operations flex-container justifyCenter">
<hr class="regex_bulk_operations_hr" />
<div class="regex_bulk_operations flex-container">
<div id="bulk_select_all_toggle" class="menu_button menu_button_icon" title="Toggle Select All">
<i class="fa-solid fa-check-double"></i>
</div>
@@ -43,6 +44,14 @@
<i class="fa-solid fa-toggle-off"></i>
<small data-i18n="Disable">Disable</small>
</div>
<div id="bulk_regex_move_to_global" class="menu_button menu_button_icon" hidden>
<i class="fa-solid fa-globe"></i>
<small data-i18n="ext_regex_move_to_global">Move to global scripts</small>
</div>
<div id="bulk_regex_move_to_scoped" class="menu_button menu_button_icon" hidden>
<i class="fa-solid fa-address-card"></i>
<small data-i18n="ext_regex_move_to_scoped">Move to scoped scripts</small>
</div>
<div id="bulk_export_regex" class="menu_button menu_button_icon">
<i class="fa-solid fa-file-export"></i>
<small data-i18n="Export">Export</small>
+52 -18
View File
@@ -7,6 +7,56 @@ export {
runRegexScript,
};
/**
* @enum {number} Regex scripts types
*/
export const SCRIPT_TYPES = {
GLOBAL: 0,
SCOPED: 1,
};
/**
* @typedef {import('../../char-data.js').RegexScriptData} RegexScript
*/
/**
* @typedef {object} GetRegexScriptsOptions
* @property {boolean} allowedOnly only return allowed scripts
*/
const DEFAULT_GET_REGEX_SCRIPTS_OPTIONS = { allowedOnly: false };
/**
* Retrieves the list of regex scripts by combining the scripts from the extension settings and the character data
*
* @param {GetRegexScriptsOptions} option
* @returns {RegexScript[]} An array of regex scripts, where each script is an object containing the necessary information.
*/
export function getRegexScripts(option = DEFAULT_GET_REGEX_SCRIPTS_OPTIONS) {
return [...Object.values(SCRIPT_TYPES).flatMap(type => getScriptsByType(type, option))];
}
/**
* Retrieves the regex scripts for a specific type.
* @param {SCRIPT_TYPES} scriptType
* @param {GetRegexScriptsOptions} option
* @returns {RegexScript[]} An array of regex scripts for the specified type.
*/
export function getScriptsByType(scriptType, { allowedOnly } = DEFAULT_GET_REGEX_SCRIPTS_OPTIONS) {
switch (scriptType) {
case SCRIPT_TYPES.GLOBAL:
return extension_settings.regex ?? [];
case SCRIPT_TYPES.SCOPED: {
if (allowedOnly && !extension_settings?.character_allowed_regex?.includes(characters?.[this_chid]?.avatar)) {
return [];
}
const scopedScripts = characters[this_chid]?.data?.extensions?.regex_scripts;
return Array.isArray(scopedScripts) ? scopedScripts : [];
}
default:
return [];
}
}
/**
* @enum {number} Where the regex script should be applied
*/
@@ -51,22 +101,6 @@ function sanitizeRegexMacro(x) {
}) : x;
}
function getScopedRegex() {
const isAllowed = extension_settings?.character_allowed_regex?.includes(characters?.[this_chid]?.avatar);
if (!isAllowed) {
return [];
}
const scripts = characters[this_chid]?.data?.extensions?.regex_scripts;
if (!Array.isArray(scripts)) {
return [];
}
return scripts;
}
/**
* Parent function to fetch a regexed version of a raw string
* @param {string} rawString The raw string to be regexed
@@ -87,7 +121,7 @@ function getRegexedString(rawString, placement, { characterOverride, isMarkdown,
return finalString;
}
const allRegex = [...(extension_settings.regex ?? []), ...(getScopedRegex() ?? [])];
const allRegex = getRegexScripts({ allowedOnly: true });
allRegex.forEach((script) => {
if (
// Script applies to Markdown and input is Markdown
@@ -126,7 +160,7 @@ function getRegexedString(rawString, placement, { characterOverride, isMarkdown,
/**
* Runs the provided regex script on the given string
* @param {import('./index.js').RegexScript} regexScript The regex script to run
* @param {RegexScript} regexScript The regex script to run
* @param {string} rawString The string to run the regex script on
* @param {RegexScriptParams} params The parameters to use for the regex script
* @returns {string} The new string
+210 -105
View File
@@ -7,8 +7,8 @@ import { ARGUMENT_TYPE, SlashCommandArgument, SlashCommandNamedArgument } from '
import { commonEnumProviders, enumIcons } from '../../slash-commands/SlashCommandCommonEnumsProvider.js';
import { SlashCommandEnumValue, enumTypes } from '../../slash-commands/SlashCommandEnumValue.js';
import { SlashCommandParser } from '../../slash-commands/SlashCommandParser.js';
import { download, equalsIgnoreCaseAndAccents, getFileText, getSortableDelay, isFalseBoolean, isTrueBoolean, regexFromString, setInfoBlock, uuidv4, escapeHtml } from '../../utils.js';
import { regex_placement, runRegexScript, substitute_find_regex } from './engine.js';
import { download, equalsIgnoreCaseAndAccents, escapeHtml, getFileText, getSortableDelay, isFalseBoolean, isTrueBoolean, regexFromString, setInfoBlock, uuidv4 } from '../../utils.js';
import { getRegexScripts, getScriptsByType, regex_placement, runRegexScript, SCRIPT_TYPES, substitute_find_regex } from './engine.js';
import { t } from '../../i18n.js';
import { accountStorage } from '../../util/AccountStorage.js';
@@ -65,8 +65,8 @@ class RegexPresetManager {
* @returns {RegexPresetState} The current state object
*/
captureCurrentState() {
const globalScripts = this.regexListToPresetItems(extension_settings.regex) || [];
const scopedScripts = this.regexListToPresetItems(characters[this_chid]?.data?.extensions?.regex_scripts) || [];
const globalScripts = this.regexListToPresetItems(getScriptsByType(SCRIPT_TYPES.GLOBAL));
const scopedScripts = this.regexListToPresetItems(getScriptsByType(SCRIPT_TYPES.SCOPED));
return {
global: globalScripts.map(item => item.id).sort(),
@@ -418,8 +418,8 @@ class RegexPresetManager {
id: id,
name: name,
isSelected: false,
global: this.regexListToPresetItems(extension_settings.regex),
scoped: this.regexListToPresetItems(characters[this_chid]?.data?.extensions?.regex_scripts),
global: this.regexListToPresetItems(getScriptsByType(SCRIPT_TYPES.GLOBAL)),
scoped: this.regexListToPresetItems(getScriptsByType(SCRIPT_TYPES.SCOPED)),
};
if (isUpdate) {
@@ -464,15 +464,6 @@ class RegexPresetManager {
const presetManager = new RegexPresetManager();
/**
* Retrieves the list of regex scripts by combining the scripts from the extension settings and the character data
*
* @return {RegexScript[]} An array of regex scripts, where each script is an object containing the necessary information.
*/
export function getRegexScripts() {
return [...(extension_settings.regex ?? []), ...(characters[this_chid]?.data?.extensions?.regex_scripts ?? [])];
}
/**
* Toggle the icon for the "select all" checkbox in the regex settings.
* - Use `fa-check-double` when the checkbox is unchecked (indicating all scripts are not selected).
@@ -485,16 +476,25 @@ function setToggleAllIcon(allAreChecked) {
selectAllIcon.toggleClass('fa-minus', allAreChecked);
}
function setMoveButtonsVisibility() {
const hasGlobalScripts = $('#saved_regex_scripts .regex-script-label:has(.regex_bulk_checkbox:checked)').length > 0;
const hasScopedScripts =
$('#saved_scoped_scripts .regex-script-label:has(.regex_bulk_checkbox:checked)').length > 0;
$('#bulk_regex_move_to_global').toggle(hasScopedScripts);
$('#bulk_regex_move_to_scoped').toggle(hasGlobalScripts);
}
/**
* Saves a regex script to the extension settings or character data.
* @param {import('../../char-data.js').RegexScriptData} regexScript
* @param {number} existingScriptIndex Index of the existing script
* @param {boolean} isScoped Is the script scoped to a character?
* @param {SCRIPT_TYPES} scriptType global? scoped?
* @param {boolean} [saveSettings=true] Whether to save the settings immediately
* @returns {Promise<void>}
*/
async function saveRegexScript(regexScript, existingScriptIndex, isScoped) {
async function saveRegexScript(regexScript, existingScriptIndex, scriptType, saveSettings = true) {
// If not editing
const array = (isScoped ? characters[this_chid]?.data?.extensions?.regex_scripts : extension_settings.regex) ?? [];
const array = getScriptsByType(scriptType);
// Assign a UUID if it doesn't exist
if (!regexScript.id) {
@@ -523,7 +523,7 @@ async function saveRegexScript(regexScript, existingScriptIndex, isScoped) {
array.push(regexScript);
}
if (isScoped) {
if (scriptType === SCRIPT_TYPES.SCOPED) {
await writeExtensionField(this_chid, 'regex_scripts', array);
// Add the character to the allowed list
@@ -532,13 +532,15 @@ async function saveRegexScript(regexScript, existingScriptIndex, isScoped) {
}
}
saveSettingsDebounced();
await loadRegexScripts();
if (saveSettings) {
saveSettingsDebounced();
await loadRegexScripts();
// Reload the current chat to undo previous markdown
const currentChatId = getCurrentChatId();
if (currentChatId !== undefined && currentChatId !== null) {
await reloadCurrentChat();
// Reload the current chat to undo previous markdown
const currentChatId = getCurrentChatId();
if (currentChatId !== undefined && currentChatId !== null) {
await reloadCurrentChat();
}
}
const debuggerPopup = $('#regex_debugger_popup');
@@ -547,22 +549,49 @@ async function saveRegexScript(regexScript, existingScriptIndex, isScoped) {
}
}
async function deleteRegexScript({ id, isScoped }) {
const array = (isScoped ? characters[this_chid]?.data?.extensions?.regex_scripts : extension_settings.regex) ?? [];
/**
* Delete a regex script
* @param {string} id
* @param {SCRIPT_TYPES} scriptType
* @param {boolean} saveSettings
* @returns {Promise<void>}
*/
async function deleteRegexScript(id, scriptType, saveSettings = true) {
const array = getScriptsByType(scriptType);
const existingScriptIndex = array.findIndex((script) => script.id === id);
const existingScriptIndex = array.findIndex(script => script.id === id);
if (existingScriptIndex !== -1) {
array.splice(existingScriptIndex, 1);
if (isScoped) {
if (scriptType === SCRIPT_TYPES.SCOPED) {
await writeExtensionField(this_chid, 'regex_scripts', array);
}
saveSettingsDebounced();
await loadRegexScripts();
if (saveSettings) {
saveSettingsDebounced();
await loadRegexScripts();
}
}
}
/**
* Move a regex script from one type to another
* @param {import('../../char-data.js').RegexScriptData} script
* @param {SCRIPT_TYPES} toType
* @param {SCRIPT_TYPES|null} fromType
* @param {boolean} saveSettings
* @returns {Promise<void>}
*/
async function moveRegexScript(script, toType, fromType = null, saveSettings = true) {
if (!fromType) {
fromType = getScriptType(script);
}
if (fromType === toType || fromType === -1) {
return;
}
await deleteRegexScript(script.id, fromType, false);
await saveRegexScript(script, -1, toType, saveSettings);
}
async function loadRegexScripts() {
$('#saved_regex_scripts').empty();
$('#saved_scoped_scripts').empty();
@@ -574,13 +603,13 @@ async function loadRegexScripts() {
* Renders a script to the UI.
* @param {string} container Container to render the script to
* @param {import('../../char-data.js').RegexScriptData} script Script data
* @param {boolean} isScoped Script is scoped to a character
* @param {SCRIPT_TYPES} scriptType global? scoped?
* @param {number} index Index of the script in the array
*/
function renderScript(container, script, isScoped, index) {
function renderScript(container, script, scriptType, index) {
// Have to clone here
const scriptHtml = scriptTemplate.clone();
const save = () => saveRegexScript(script, index, isScoped);
const save = () => saveRegexScript(script, index, scriptType);
if (!script.id) {
script.id = uuidv4();
@@ -600,7 +629,7 @@ async function loadRegexScripts() {
scriptHtml.find('.disable_regex').prop('checked', false).trigger('input');
});
scriptHtml.find('.edit_existing_regex').on('click', async function () {
await onRegexEditorOpenClick(scriptHtml.attr('id'), isScoped);
await onRegexEditorOpenClick(scriptHtml.attr('id'), scriptType);
});
scriptHtml.find('.move_to_global').on('click', async function () {
const confirm = await callGenericPopup(t`Are you sure you want to move this regex script to global?`, POPUP_TYPE.CONFIRM);
@@ -608,29 +637,22 @@ async function loadRegexScripts() {
if (!confirm) {
return;
}
await deleteRegexScript({ id: script.id, isScoped: true });
await saveRegexScript(script, -1, false);
await moveRegexScript(script, SCRIPT_TYPES.GLOBAL, scriptType);
});
scriptHtml.find('.move_to_scoped').on('click', async function () {
if (this_chid === undefined) {
toastr.error(t`No character selected.`);
return;
}
if (selected_group) {
toastr.error(t`Cannot edit scoped scripts in group chats.`);
return;
}
const confirm = await callGenericPopup(t`Are you sure you want to move this regex script to scoped?`, POPUP_TYPE.CONFIRM);
if (!confirm) {
return;
}
await deleteRegexScript({ id: script.id, isScoped: false });
await saveRegexScript(script, -1, true);
await moveRegexScript(script, SCRIPT_TYPES.SCOPED, scriptType);
});
scriptHtml.find('.export_regex').on('click', async function () {
const fileName = `regex-${sanitizeFileName(script.scriptName)}.json`;
@@ -639,15 +661,14 @@ async function loadRegexScripts() {
});
scriptHtml.find('.delete_regex').on('click', async function () {
const confirm = await callGenericPopup(t`Are you sure you want to delete this regex script?`, POPUP_TYPE.CONFIRM);
if (!confirm) {
return;
}
await deleteRegexScript({ id: script.id, isScoped });
await deleteRegexScript(script.id, scriptType);
await reloadCurrentChat();
});
scriptHtml.find('.regex_bulk_checkbox').on('change', function () {
setMoveButtonsVisibility();
const checkboxes = $('#regex_container .regex_bulk_checkbox');
const allAreChecked = checkboxes.length === checkboxes.filter(':checked').length;
setToggleAllIcon(allAreChecked);
@@ -656,22 +677,24 @@ async function loadRegexScripts() {
$(container).append(scriptHtml);
}
extension_settings?.regex?.forEach((script, index) => renderScript('#saved_regex_scripts', script, false, index));
characters[this_chid]?.data?.extensions?.regex_scripts?.forEach((script, index) => renderScript('#saved_scoped_scripts', script, true, index));
getScriptsByType(SCRIPT_TYPES.GLOBAL).forEach((script, index) => renderScript('#saved_regex_scripts', script, SCRIPT_TYPES.GLOBAL, index));
getScriptsByType(SCRIPT_TYPES.SCOPED).forEach((script, index) => renderScript('#saved_scoped_scripts', script, SCRIPT_TYPES.SCOPED, index));
const isAllowed = extension_settings?.character_allowed_regex?.includes(characters?.[this_chid]?.avatar);
$('#regex_scoped_toggle').prop('checked', isAllowed);
const isScopedAllowed = extension_settings?.character_allowed_regex?.includes(characters?.[this_chid]?.avatar);
$('#regex_scoped_toggle').prop('checked', isScopedAllowed);
setMoveButtonsVisibility();
}
/**
* Opens the regex editor.
* @param {string|boolean} existingId Existing ID
* @param {boolean} isScoped Is the script scoped to a character?
* @param {SCRIPT_TYPES} scriptType global? scoped?
* @returns {Promise<void>}
*/
async function onRegexEditorOpenClick(existingId, isScoped) {
async function onRegexEditorOpenClick(existingId, scriptType) {
const editorHtml = $(await renderExtensionTemplateAsync('regex', 'editor'));
const array = (isScoped ? characters[this_chid]?.data?.extensions?.regex_scripts : extension_settings.regex) ?? [];
const array = getScriptsByType(scriptType);
// If an ID exists, fill in all the values
let existingScriptIndex = -1;
@@ -776,7 +799,7 @@ async function onRegexEditorOpenClick(existingId, isScoped) {
maxDepth: parseInt(String(editorHtml.find('input[name="max_depth"]').val())),
};
saveRegexScript(newRegexScript, existingScriptIndex, isScoped);
saveRegexScript(newRegexScript, existingScriptIndex, scriptType);
}
}
@@ -973,7 +996,7 @@ function populateDebuggerRuleList(container) {
return;
}
const globalScriptIds = new Set((extension_settings.regex ?? []).map(s => s.id));
const globalScriptIds = new Set(getScriptsByType(SCRIPT_TYPES.GLOBAL).map(s => s.id));
const globalScripts = [];
const scopedScripts = [];
@@ -981,11 +1004,11 @@ function populateDebuggerRuleList(container) {
const scriptCopy = structuredClone(script); // Use structuredClone for deep copy
if (globalScriptIds.has(script.id)) {
// @ts-ignore
scriptCopy.isScoped = false;
scriptCopy.type = SCRIPT_TYPES.SCOPED;
globalScripts.push(scriptCopy);
} else {
// @ts-ignore
scriptCopy.isScoped = true;
scriptCopy.type = SCRIPT_TYPES.SCOPED;
scopedScripts.push(scriptCopy);
}
});
@@ -1002,10 +1025,17 @@ function populateDebuggerRuleList(container) {
ruleElement.find('.rule-name').text(script.scriptName);
ruleElement.find('.rule-regex').text(script.findRegex);
// @ts-ignore
ruleElement.find('.rule-scope').text(script.isScoped ? t`Scoped` : t`Global`);
ruleElement
.find('.rule-scope')
.text(
{
[SCRIPT_TYPES.SCOPED]: t`Scoped`,
[SCRIPT_TYPES.GLOBAL]: t`Global`,
}[script.type],
);
ruleElement.find('.rule-enabled').prop('checked', !script.disabled);
// @ts-ignore
ruleElement.find('.edit_rule').on('click', () => onRegexEditorOpenClick(script.id, script.isScoped));
ruleElement.find('.edit_rule').on('click', () => onRegexEditorOpenClick(script.id, script.type));
ruleElement.on('click', function (event) {
if ($(event.target).is('input, .menu_button, .menu_button i')) {
@@ -1364,10 +1394,10 @@ async function toggleRegexCallback(args, scriptName) {
break;
}
const isScoped = characters[this_chid]?.data?.extensions?.regex_scripts?.some(s => s.id === script.id);
const index = isScoped ? characters[this_chid]?.data?.extensions?.regex_scripts?.indexOf(script) : scripts.indexOf(script);
const scriptType = getScriptType(script);
const index = getScriptsByType(scriptType).indexOf(script);
await saveRegexScript(script, index, isScoped);
await saveRegexScript(script, index, scriptType);
if (script.disabled) {
!quiet && toastr.success(t`Regex script '${scriptName}' has been disabled.`);
} else {
@@ -1380,9 +1410,9 @@ async function toggleRegexCallback(args, scriptName) {
/**
* Performs the import of the regex object.
* @param {Object} regexScript Input object
* @param {boolean} isScoped Is the script scoped to a character?
* @param {SCRIPT_TYPES} scriptType global? scoped?
*/
async function onRegexImportObjectChange(regexScript, isScoped) {
async function onRegexImportObjectChange(regexScript, scriptType) {
try {
if (!regexScript.scriptName) {
throw new Error('No script name provided.');
@@ -1391,10 +1421,10 @@ async function onRegexImportObjectChange(regexScript, isScoped) {
// Assign a new UUID
regexScript.id = uuidv4();
const array = (isScoped ? characters[this_chid]?.data?.extensions?.regex_scripts : extension_settings.regex) ?? [];
const array = getScriptsByType(scriptType);
array.push(regexScript);
if (isScoped) {
if (scriptType === SCRIPT_TYPES.SCOPED) {
await writeExtensionField(this_chid, 'regex_scripts', array);
}
@@ -1411,9 +1441,9 @@ async function onRegexImportObjectChange(regexScript, isScoped) {
/**
* Performs the import of the regex file.
* @param {File} file Input file
* @param {boolean} isScoped Is the script scoped to a character?
* @param {SCRIPT_TYPES} scriptType global? scoped?
*/
async function onRegexImportFileChange(file, isScoped) {
async function onRegexImportFileChange(file, scriptType) {
if (!file) {
toastr.error('No file provided.');
return;
@@ -1423,10 +1453,10 @@ async function onRegexImportFileChange(file, isScoped) {
const regexScripts = JSON.parse(await getFileText(file));
if (Array.isArray(regexScripts)) {
for (const regexScript of regexScripts) {
await onRegexImportObjectChange(regexScript, isScoped);
await onRegexImportObjectChange(regexScript, scriptType);
}
} else {
await onRegexImportObjectChange(regexScripts, isScoped);
await onRegexImportObjectChange(regexScripts, scriptType);
}
} catch (error) {
console.log(error);
@@ -1435,24 +1465,43 @@ async function onRegexImportFileChange(file, isScoped) {
}
}
function getScriptType(script) {
return getScriptsByType(SCRIPT_TYPES.SCOPED).some(s => s.id === script.id)
? SCRIPT_TYPES.SCOPED
: SCRIPT_TYPES.GLOBAL;
}
function getSelectedScripts() {
const scripts = getRegexScripts();
const selector = '#regex_container .regex-script-label:has(.regex_bulk_checkbox:checked)';
const selectedIds = Array.from(document.querySelectorAll(selector))
.map(e => e.getAttribute('id'))
.filter(id => id);
return scripts.filter(script => selectedIds.includes(script.id));
}
function purgeEmbeddedRegexScripts({ character }) {
const avatar = character?.avatar;
if (avatar && extension_settings.character_allowed_regex?.includes(avatar)) {
const index = extension_settings.character_allowed_regex.indexOf(avatar);
if (index !== -1) {
extension_settings.character_allowed_regex.splice(index, 1);
saveSettingsDebounced();
}
if (!avatar) {
return;
}
const checkKey = `AlertRegex_${characters[this_chid].avatar}`;
if (accountStorage.getItem(checkKey)) {
accountStorage.removeItem(checkKey);
}
const index = extension_settings.character_allowed_regex.indexOf(avatar);
if (index !== -1) {
extension_settings.character_allowed_regex.splice(index, 1);
saveSettingsDebounced();
}
}
async function checkEmbeddedRegexScripts() {
async function checkCharEmbeddedRegexScripts() {
const chid = this_chid;
if (chid !== undefined && !selected_group) {
const avatar = characters[chid]?.avatar;
const scripts = characters[chid]?.data?.extensions?.regex_scripts;
const scripts = getScriptsByType(SCRIPT_TYPES.SCOPED);
if (Array.isArray(scripts) && scripts.length > 0) {
if (avatar && !extension_settings.character_allowed_regex.includes(avatar)) {
@@ -1497,7 +1546,7 @@ jQuery(async () => {
const settingsHtml = $(await renderExtensionTemplateAsync('regex', 'dropdown'));
$('#regex_container').append(settingsHtml);
$('#open_regex_editor').on('click', function () {
onRegexEditorOpenClick(false, false);
onRegexEditorOpenClick(false, SCRIPT_TYPES.GLOBAL);
});
$('#open_regex_debugger').on('click', onRegexDebuggerOpenClick);
$('#open_scoped_editor').on('click', function () {
@@ -1511,19 +1560,19 @@ jQuery(async () => {
return;
}
onRegexEditorOpenClick(false, true);
onRegexEditorOpenClick(false, SCRIPT_TYPES.SCOPED);
});
$('#import_regex_file').on('change', async function () {
let target = 'global';
let target = SCRIPT_TYPES.GLOBAL;
const template = $(await renderExtensionTemplateAsync('regex', 'importTarget'));
template.find('#regex_import_target_global').on('input', () => target = 'global');
template.find('#regex_import_target_scoped').on('input', () => target = 'scoped');
template.find('#regex_import_target_global').on('input', () => (target = SCRIPT_TYPES.GLOBAL));
template.find('#regex_import_target_scoped').on('input', () => (target = SCRIPT_TYPES.SCOPED));
await callGenericPopup(template, POPUP_TYPE.TEXT);
const inputElement = this instanceof HTMLInputElement && this;
for (const file of inputElement.files) {
await onRegexImportFileChange(file, target === 'scoped');
await onRegexImportFileChange(file, target);
}
inputElement.value = '';
});
@@ -1531,13 +1580,6 @@ jQuery(async () => {
$('#import_regex_file').trigger('click');
});
function getSelectedScripts() {
const scripts = getRegexScripts();
const selector = '#regex_container .regex-script-label:has(.regex_bulk_checkbox:checked)';
const selectedIds = Array.from(document.querySelectorAll(selector)).map(e => e.getAttribute('id')).filter(id => id);
return scripts.filter(script => selectedIds.includes(script.id));
}
$('#bulk_select_all_toggle').on('click', async function () {
const checkboxes = $('#regex_container .regex_bulk_checkbox');
if (checkboxes.length === 0) {
@@ -1577,6 +1619,31 @@ jQuery(async () => {
await loadRegexScripts();
});
/**
* Bulk move regex scripts to the specified type
* @param {SCRIPT_TYPES} toType destination type
*/
async function bulkMoveRegexScript(toType) {
const scripts = getSelectedScripts();
if (scripts.length === 0) {
toastr.warning(t`No regex scripts selected for moving.`);
return;
}
for (const script of scripts) {
await moveRegexScript(script, toType, getScriptType(script), false);
}
await loadRegexScripts();
// Reload the current chat to undo previous markdown
const currentChatId = getCurrentChatId();
if (currentChatId !== undefined && currentChatId !== null) {
await reloadCurrentChat();
}
}
$('#bulk_regex_move_to_global').on('click', () => bulkMoveRegexScript(SCRIPT_TYPES.GLOBAL));
$('#bulk_regex_move_to_scoped').on('click', () => bulkMoveRegexScript(SCRIPT_TYPES.SCOPED));
$('#bulk_delete_regex').on('click', async function () {
const scripts = getSelectedScripts();
if (scripts.length === 0) {
@@ -1588,11 +1655,11 @@ jQuery(async () => {
return;
}
for (const script of scripts) {
const isScoped = characters[this_chid]?.data?.extensions?.regex_scripts?.some(s => s.id === script.id);
await deleteRegexScript({ id: script.id, isScoped: isScoped });
await deleteRegexScript(script.id, getScriptType(script), false);
}
await reloadCurrentChat();
saveSettingsDebounced();
await loadRegexScripts();
await reloadCurrentChat();
});
$('#bulk_export_regex').on('click', async function () {
@@ -1611,12 +1678,12 @@ jQuery(async () => {
{
selector: '#saved_regex_scripts',
setter: x => extension_settings.regex = x,
getter: () => extension_settings.regex ?? [],
getter: () => getScriptsByType(SCRIPT_TYPES.GLOBAL),
},
{
selector: '#saved_scoped_scripts',
setter: x => writeExtensionField(this_chid, 'regex_scripts', x),
getter: () => characters[this_chid]?.data?.extensions?.regex_scripts ?? [],
getter: () => getScriptsByType(SCRIPT_TYPES.SCOPED),
},
];
for (const { selector, setter, getter } of sortableDatas) {
@@ -1638,6 +1705,7 @@ jQuery(async () => {
saveSettingsDebounced();
console.debug(`Regex scripts in ${selector} reordered`);
await reloadCurrentChat();
await loadRegexScripts();
},
});
@@ -1676,12 +1744,49 @@ jQuery(async () => {
// @ts-ignore
$('#saved_regex_scripts').sortable('enable');
/**
* @typedef {object} ScriptDecorators
* @property {string} typename
* @property {import('../../slash-commands/SlashCommandEnumValue.js').EnumType} color
* @property {string} icon
*/
/**
* @param {SCRIPT_TYPES} type
* @returns {ScriptDecorators}
*/
function getScriptDecorators(type) {
switch (type) {
case SCRIPT_TYPES.GLOBAL:
return {
typename: 'global',
color: enumTypes.enum,
icon: 'G',
};
case SCRIPT_TYPES.SCOPED:
return {
typename: 'scoped',
color: enumTypes.name,
icon: 'S',
};
}
return {
typename: 'Unknown',
color: enumTypes.variable,
icon: 'Unknown',
};
}
const localEnumProviders = {
regexScripts: () => getRegexScripts().map(script => {
const isGlobal = extension_settings.regex?.some(x => x.scriptName === script.scriptName);
return new SlashCommandEnumValue(script.scriptName, `${enumIcons.getStateIcon(!script.disabled)} [${isGlobal ? 'global' : 'scoped'}] ${script.findRegex}`,
isGlobal ? enumTypes.enum : enumTypes.name, isGlobal ? 'G' : 'S');
}),
regexScripts: () =>
getRegexScripts().map(script => {
const type = getScriptType(script);
const { typename, color, icon } = getScriptDecorators(type);
return new SlashCommandEnumValue(
script.scriptName,
`${enumIcons.getStateIcon(!script.disabled)} [${typename}] ${script.findRegex}`,
color,
icon,
);
}),
};
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
@@ -1750,7 +1855,7 @@ jQuery(async () => {
`,
}));
eventSource.on(event_types.CHAT_CHANGED, checkEmbeddedRegexScripts);
eventSource.on(event_types.CHAT_CHANGED, checkCharEmbeddedRegexScripts);
eventSource.on(event_types.CHARACTER_DELETED, purgeEmbeddedRegexScripts);
presetManager.setupEventListeners();
@@ -12,10 +12,10 @@
<i class="fa-solid fa-pencil"></i>
</div>
<div class="move_to_global menu_button" data-i18n="[title]ext_regex_move_to_global" title="Move to global scripts">
<i class="fa-solid fa-arrow-up"></i>
<i class="fa-solid fa-globe"></i>
</div>
<div class="move_to_scoped menu_button" data-i18n="[title]ext_regex_move_to_scoped" title="Move to scoped scripts">
<i class="fa-solid fa-arrow-down"></i>
<i class="fa-solid fa-address-card"></i>
</div>
<div class="export_regex menu_button" data-i18n="[title]ext_regex_export_script" title="Export script">
<i class="fa-solid fa-file-export"></i>
+6 -1
View File
@@ -139,7 +139,8 @@ input.enable_scoped {
}
.regex_settings .regex_bulk_operations,
.regex_settings .regex_bulk_checkbox {
.regex_settings .regex_bulk_checkbox,
.regex_settings .regex_bulk_operations_hr {
display: none;
}
@@ -147,6 +148,10 @@ input.enable_scoped {
display: flex;
}
.regex_settings:has(#regex_bulk_edit:checked) .regex_bulk_operations_hr {
display: block;
}
.regex_settings:has(#regex_bulk_edit:checked) .regex_bulk_checkbox {
display: inline-grid;
}