feat: Advanced Regex Chain Debugger and Testing Panel (#4418)
* feat: Advanced Regex Chain Debugger and Testing Panel * fix * fix_2 * fix_3 * Address code review suggestions for debugger feature * feat: Add match statistics to debugger * ESLint * feat: Enhance debugger with diff view and nav popup * ESLint * Fix styles and full results expand * Diff clean-up --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,255 @@
|
||||
/* Styles for the debugger UI */
|
||||
#regex_debugger_rules {
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
#regex_debugger_rules,
|
||||
#regex_debugger_rules .sortable-list {
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.regex-debugger-rules-list {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.regex-debugger-rule {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--SmartThemeBorderColor);
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
background-color: var(--black30a);
|
||||
gap: 5px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
#regex_debugger_run_test_header {
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#regex_debugger_expand_steps,
|
||||
#regex_debugger_expand_final,
|
||||
#regex_debugger_save_order {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.regex-debugger-rule:hover {
|
||||
filter: brightness(1.1);
|
||||
}
|
||||
|
||||
.regex-debugger-rule .handle {
|
||||
cursor: grab;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.regex-debugger-rule .rule-details {
|
||||
flex-grow: 1;
|
||||
text-align: left;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.regex-debugger-rule .rule-name {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.regex-debugger-rule .rule-regex {
|
||||
font-size: 0.8em;
|
||||
opacity: 0.8;
|
||||
font-family: var(--monoFontFamily);
|
||||
}
|
||||
|
||||
.regex-debugger-rule .rule-scope {
|
||||
font-size: 0.8em;
|
||||
padding: 2px 6px;
|
||||
border-radius: 5px;
|
||||
background-color: var(--black30a);
|
||||
margin-left: auto;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
.regex-debugger-rule .menu_button {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#regex_debugger_raw_input {
|
||||
min-height: 1.8em;
|
||||
}
|
||||
|
||||
#regex_debugger_steps_output {
|
||||
min-height: 2em;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--SmartThemeBorderColor);
|
||||
border-radius: 5px;
|
||||
padding: 5px;
|
||||
background-color: var(--black30a);
|
||||
font-family: var(--monoFontFamily);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
#regex_debugger_final_output {
|
||||
min-height: 2em;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--SmartThemeBorderColor);
|
||||
border-radius: 5px;
|
||||
padding: 5px;
|
||||
background-color: var(--black30a);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.step-header {
|
||||
margin-top: 10px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.step-output {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
padding: 5px;
|
||||
background-color: var(--black30a);
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* Classes to replace inline styles */
|
||||
.regex-debugger-no-rules {
|
||||
padding: 10px;
|
||||
text-align: center;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.regex-debugger-list-header {
|
||||
font-weight: bold;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
/* Styles for statistics */
|
||||
.step-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.step-metrics {
|
||||
font-size: 0.8em;
|
||||
opacity: 0.8;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.regex-debugger-summary {
|
||||
padding: 8px;
|
||||
margin-bottom: 10px;
|
||||
border: 1px solid var(--SmartThemeBorderColor);
|
||||
background-color: var(--black30a);
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.regex-debugger-tester .results-header {
|
||||
position: relative;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.regex-debugger-tester .radio_group {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Styles for statistics and highlighting additions */
|
||||
.step-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
/* Allow wrapping on small screens */
|
||||
}
|
||||
|
||||
.step-metrics {
|
||||
font-size: 0.8em;
|
||||
opacity: 0.8;
|
||||
font-weight: normal;
|
||||
white-space: nowrap;
|
||||
/* Prevent metrics from breaking line */
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.regex-debugger-summary {
|
||||
padding: 8px;
|
||||
margin-bottom: 10px;
|
||||
border: 1px solid var(--SmartThemeBorderColor);
|
||||
background-color: var(--black30a);
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* New highlight color for added text */
|
||||
mark.green_hl {
|
||||
background-color: #28a745;
|
||||
/* A standard green color */
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* New highlight color for deleted text */
|
||||
mark.red_hl {
|
||||
background-color: #dc3545;
|
||||
/* A standard red color */
|
||||
color: white;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
/* Styles for the expanded view with navigation */
|
||||
.expanded-regex-container {
|
||||
display: flex;
|
||||
height: 75vh;
|
||||
/* Give the container a good height */
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.expanded-regex-nav {
|
||||
flex: 0 0 200px;
|
||||
/* Fixed width for the nav bar */
|
||||
border-right: 1px solid var(--SmartThemeBorderColor);
|
||||
padding: 5px;
|
||||
overflow-y: auto;
|
||||
background-color: var(--black30a);
|
||||
}
|
||||
|
||||
.expanded-regex-nav a {
|
||||
display: block;
|
||||
padding: 6px 8px;
|
||||
text-decoration: none;
|
||||
color: var(--SmartThemeMainColor);
|
||||
border-radius: 5px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.expanded-regex-nav a:hover {
|
||||
background-color: var(--background_hover_color);
|
||||
}
|
||||
|
||||
.expanded-regex-nav a.active {
|
||||
background-color: var(--highlight_color);
|
||||
color: var(--text_color_black);
|
||||
}
|
||||
|
||||
.expanded-regex-content {
|
||||
flex-grow: 1;
|
||||
overflow-y: auto;
|
||||
padding-left: 10px;
|
||||
}
|
||||
|
||||
#regex_debugger_render_mode {
|
||||
padding-right: 20px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
<div class="regex-debugger-container">
|
||||
<!-- Rules List Column -->
|
||||
<div class="regex-debugger-rules-list">
|
||||
<h3>
|
||||
<i class="fa-solid fa-list-ol"></i>
|
||||
<span data-i18n="ext_regex_debugger_active_rules"
|
||||
>Active Rules</span
|
||||
>
|
||||
</h3>
|
||||
<div class="flex-container">
|
||||
<button
|
||||
id="regex_debugger_save_order"
|
||||
class="menu_button menu_button_icon interactable"
|
||||
title="Save current rule order"
|
||||
tabindex="0"
|
||||
>
|
||||
<i class="fa-solid fa-floppy-disk"></i>
|
||||
<span data-i18n="ext_regex_debugger_save_order"
|
||||
>Save Order</span
|
||||
>
|
||||
</button>
|
||||
</div>
|
||||
<ul id="regex_debugger_rules" class="sortable-list">
|
||||
<!-- Rules will be populated here by JavaScript -->
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- Testing Area Column -->
|
||||
<div class="regex-debugger-tester">
|
||||
<h3>
|
||||
<i class="fa-solid fa-vial"></i>
|
||||
<span data-i18n="ext_regex_debugger_testing_area"
|
||||
>Testing Area</span
|
||||
>
|
||||
</h3>
|
||||
<div class="regex-debugger-io">
|
||||
<div class="regex-debugger-input">
|
||||
<label
|
||||
for="regex_debugger_raw_input"
|
||||
data-i18n="ext_regex_debugger_raw_input"
|
||||
>Raw Input</label
|
||||
>
|
||||
<textarea
|
||||
id="regex_debugger_raw_input"
|
||||
class="text_pole autoSetHeight"
|
||||
rows="4"
|
||||
></textarea>
|
||||
</div>
|
||||
<div
|
||||
id="regex_debugger_run_test_header"
|
||||
class="flex-container"
|
||||
>
|
||||
<button
|
||||
id="regex_debugger_run_test"
|
||||
class="menu_button menu_button_icon interactable"
|
||||
title="Run the test pipeline"
|
||||
tabindex="0"
|
||||
>
|
||||
<i class="fa-solid fa-play"></i>
|
||||
<span data-i18n="ext_regex_debugger_run_test"
|
||||
>Run Test</span
|
||||
>
|
||||
</button>
|
||||
<div class="flex-container gap10px">
|
||||
<div class="radio_group">
|
||||
<label
|
||||
><input
|
||||
type="radio"
|
||||
name="display_mode"
|
||||
value="replace"
|
||||
checked
|
||||
/>
|
||||
<span data-i18n="ext_regex_debugger_display_replace"
|
||||
>Replace</span
|
||||
></label
|
||||
>
|
||||
<label
|
||||
><input
|
||||
type="radio"
|
||||
name="display_mode"
|
||||
value="highlight"
|
||||
/>
|
||||
<span
|
||||
data-i18n="ext_regex_debugger_display_highlight"
|
||||
>Highlight</span
|
||||
></label
|
||||
>
|
||||
</div>
|
||||
<select
|
||||
id="regex_debugger_render_mode"
|
||||
>
|
||||
<option
|
||||
value="text"
|
||||
data-i18n="ext_regex_debugger_render_text"
|
||||
>
|
||||
Render as Text
|
||||
</option>
|
||||
<option
|
||||
value="message"
|
||||
data-i18n="ext_regex_debugger_render_message"
|
||||
>
|
||||
Render as Message
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="regex-debugger-results">
|
||||
<div class="results-header">
|
||||
<h4>
|
||||
<i class="fa-solid fa-shoe-prints"></i>
|
||||
<span data-i18n="ext_regex_debugger_step_by_step"
|
||||
>Step-by-step Transformation</span
|
||||
>
|
||||
</h4>
|
||||
<div
|
||||
id="regex_debugger_expand_steps"
|
||||
class="menu_button menu_button_icon"
|
||||
title="Expand view"
|
||||
>
|
||||
<i class="fa-solid fa-expand"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div id="regex_debugger_steps_output" class="results-box"></div>
|
||||
|
||||
<div class="results-header">
|
||||
<h4>
|
||||
<i class="fa-solid fa-flag-checkered"></i>
|
||||
<span data-i18n="ext_regex_debugger_final_output"
|
||||
>Final Output</span
|
||||
>
|
||||
</h4>
|
||||
<div
|
||||
id="regex_debugger_expand_final"
|
||||
class="menu_button menu_button_icon"
|
||||
title="Expand view"
|
||||
>
|
||||
<i class="fa-solid fa-expand"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
id="regex_debugger_final_output"
|
||||
class="results-box final-output"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Template for a single rule item -->
|
||||
<template id="regex_debugger_rule_template">
|
||||
<li class="regex-debugger-rule" draggable="true">
|
||||
<i class="fa-solid fa-grip-vertical handle"></i>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" class="rule-enabled" checked />
|
||||
</label>
|
||||
<div class="rule-details">
|
||||
<span class="rule-name"></span>
|
||||
<code class="rule-regex"></code>
|
||||
<small class="rule-scope"></small>
|
||||
</div>
|
||||
<div class="menu_button menu_button_icon edit_rule" title="Edit Rule">
|
||||
<i class="fa-solid fa-pencil"></i>
|
||||
</div>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<!-- Template for a single transformation step -->
|
||||
<template id="regex_debugger_step_template">
|
||||
<div class="step-result">
|
||||
<div class="step-header">
|
||||
<strong></strong>
|
||||
</div>
|
||||
<pre class="step-output"></pre>
|
||||
</div>
|
||||
</template>
|
||||
@@ -26,6 +26,10 @@
|
||||
<i class="fa-solid fa-edit"></i>
|
||||
<small data-i18n="ext_regex_bulk_edit">Bulk Edit</small>
|
||||
</label>
|
||||
<div id="open_regex_debugger" class="menu_button menu_button_icon" data-i18n="[title]ext_regex_debugger_desc" title="Advanced Regex Debugger">
|
||||
<i class="fa-solid fa-bug-slash"></i>
|
||||
<small data-i18n="ext_regex_debugger">Debugger</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="regex_bulk_operations flex-container justifyCenter">
|
||||
<div id="bulk_select_all_toggle" class="menu_button menu_button_icon" title="Toggle Select All">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { characters, eventSource, event_types, getCurrentChatId, reloadCurrentChat, saveSettingsDebounced, this_chid } from '../../../script.js';
|
||||
import { characters, eventSource, event_types, getCurrentChatId, messageFormatting, reloadCurrentChat, saveSettingsDebounced, this_chid } from '../../../script.js';
|
||||
import { extension_settings, renderExtensionTemplateAsync, writeExtensionField } from '../../extensions.js';
|
||||
import { selected_group } from '../../group-chats.js';
|
||||
import { callGenericPopup, POPUP_TYPE } from '../../popup.js';
|
||||
@@ -7,7 +7,7 @@ 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 } from '../../utils.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 { t } from '../../i18n.js';
|
||||
import { accountStorage } from '../../util/AccountStorage.js';
|
||||
@@ -94,6 +94,11 @@ async function saveRegexScript(regexScript, existingScriptIndex, isScoped) {
|
||||
if (currentChatId !== undefined && currentChatId !== null) {
|
||||
await reloadCurrentChat();
|
||||
}
|
||||
|
||||
const debuggerPopup = $('#regex_debugger_popup');
|
||||
if (debuggerPopup.length) {
|
||||
populateDebuggerRuleList(debuggerPopup.parent());
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteRegexScript({ id, isScoped }) {
|
||||
@@ -329,6 +334,442 @@ async function onRegexEditorOpenClick(existingId, isScoped) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an HTML string for a replacement, highlighting literal parts in green
|
||||
* and keeping back-referenced parts plain.
|
||||
* @param {RegExpMatchArray} match The match object from `matchAll`.
|
||||
* @param {string} pattern The replacement pattern string (e.g., "new text $1").
|
||||
* @returns {string} The constructed HTML string.
|
||||
*/
|
||||
function buildReplacementHtml(match, pattern) {
|
||||
const container = document.createDocumentFragment();
|
||||
let lastIndex = 0;
|
||||
const backrefRegex = /\$\$|\$&|\$`|\$'|\$(\d{1,2})/g;
|
||||
|
||||
let reMatch;
|
||||
while ((reMatch = backrefRegex.exec(pattern)) !== null) {
|
||||
// Part of the pattern before the back-reference is a literal.
|
||||
const literalPart = pattern.substring(lastIndex, reMatch.index);
|
||||
if (literalPart) {
|
||||
const mark = document.createElement('mark');
|
||||
mark.className = 'green_hl';
|
||||
mark.innerText = literalPart;
|
||||
container.appendChild(mark);
|
||||
}
|
||||
|
||||
const backref = reMatch[0];
|
||||
if (backref === '$$') {
|
||||
container.appendChild(document.createTextNode('$'));
|
||||
} else if (backref === '$&') {
|
||||
const mark = document.createElement('mark');
|
||||
mark.className = 'yellow_hl';
|
||||
mark.innerText = match[0];
|
||||
container.appendChild(mark);
|
||||
} else if (backref === '$`') {
|
||||
container.appendChild(document.createTextNode(match.input.substring(0, match.index)));
|
||||
} else if (backref === '$\'') {
|
||||
container.appendChild(document.createTextNode(match.input.substring(match.index + match[0].length)));
|
||||
} else { // It's a numbered capture group, $n.
|
||||
const groupIndex = parseInt(reMatch[1], 10);
|
||||
if (groupIndex > 0 && groupIndex < match.length && match[groupIndex] !== undefined) {
|
||||
const mark = document.createElement('mark');
|
||||
mark.className = 'yellow_hl';
|
||||
mark.innerText = match[groupIndex];
|
||||
container.appendChild(mark);
|
||||
} else {
|
||||
// Not a valid group index, treat it as a literal.
|
||||
const mark = document.createElement('mark');
|
||||
mark.className = 'green_hl';
|
||||
mark.innerText = backref;
|
||||
container.appendChild(mark);
|
||||
}
|
||||
}
|
||||
lastIndex = backrefRegex.lastIndex;
|
||||
}
|
||||
|
||||
// The final part of the pattern after the last back-reference.
|
||||
const finalLiteralPart = pattern.substring(lastIndex);
|
||||
if (finalLiteralPart) {
|
||||
const mark = document.createElement('mark');
|
||||
mark.className = 'green_hl';
|
||||
mark.innerText = finalLiteralPart;
|
||||
container.appendChild(mark);
|
||||
}
|
||||
|
||||
// To get the HTML content, we need a temporary parent element.
|
||||
const tempDiv = document.createElement('div');
|
||||
tempDiv.appendChild(container);
|
||||
return tempDiv.innerHTML;
|
||||
}
|
||||
|
||||
function executeRegexScriptForDebugging(script, text) {
|
||||
let err;
|
||||
let originalRegex;
|
||||
|
||||
try {
|
||||
originalRegex = regexFromString(script.findRegex);
|
||||
if (!originalRegex) throw new Error('Invalid regex string');
|
||||
} catch (e) {
|
||||
err = `Compile error: ${e.message}`;
|
||||
return { output: text, highlightedOutput: text, error: err, charsCaptured: 0, charsAdded: 0, charsRemoved: 0 };
|
||||
}
|
||||
|
||||
const globalRegex = new RegExp(originalRegex.source, originalRegex.flags.includes('g') ? originalRegex.flags : originalRegex.flags + 'g');
|
||||
const matches = [...text.matchAll(globalRegex)];
|
||||
|
||||
if (matches.length === 0) {
|
||||
return { output: text, highlightedOutput: escapeHtml(text), error: null, charsCaptured: 0, charsAdded: 0, charsRemoved: 0 };
|
||||
}
|
||||
|
||||
let outputText = '';
|
||||
let highlightedOutput = ''; // This will now be our "diff view"
|
||||
let lastIndex = 0;
|
||||
let totalCharsCaptured = 0;
|
||||
let totalCharsAdded = 0;
|
||||
let totalCharsRemoved = 0;
|
||||
|
||||
try {
|
||||
for (const match of matches) {
|
||||
const originalMatchText = match[0];
|
||||
totalCharsCaptured += originalMatchText.length;
|
||||
|
||||
// Append text between matches (this part is unchanged)
|
||||
const precedingText = text.substring(lastIndex, match.index);
|
||||
outputText += precedingText;
|
||||
highlightedOutput += escapeHtml(precedingText);
|
||||
|
||||
// --- Start of new diff and statistics logic ---
|
||||
let charsAddedInMatch = 0;
|
||||
let charsKeptFromMatch = 0;
|
||||
const backrefRegex = /\$\$|\$&|\$`|\$'|\$(\d{1,2})/g;
|
||||
let lastPatternIndex = 0;
|
||||
let reMatch;
|
||||
let replacementForPlainText = '';
|
||||
|
||||
// This loop calculates the stats accurately
|
||||
while ((reMatch = backrefRegex.exec(script.replaceString)) !== null) {
|
||||
const literalPart = script.replaceString.substring(lastPatternIndex, reMatch.index);
|
||||
charsAddedInMatch += literalPart.length;
|
||||
replacementForPlainText += literalPart;
|
||||
const backref = reMatch[0];
|
||||
if (backref === '$$') {
|
||||
replacementForPlainText += '$';
|
||||
} else if (backref === '$&') {
|
||||
charsKeptFromMatch += (match[0] || '').length; replacementForPlainText += (match[0] || '');
|
||||
} else if (backref === '$`') {
|
||||
const part = match.input.substring(0, match.index); charsKeptFromMatch += part.length; replacementForPlainText += part;
|
||||
} else if (backref === '$\'') {
|
||||
const part = match.input.substring(match.index + match[0].length); charsKeptFromMatch += part.length; replacementForPlainText += part;
|
||||
} else {
|
||||
const groupIndex = parseInt(reMatch[1], 10);
|
||||
if (groupIndex > 0 && groupIndex < match.length && match[groupIndex] !== undefined) {
|
||||
charsKeptFromMatch += match[groupIndex].length;
|
||||
replacementForPlainText += match[groupIndex];
|
||||
}
|
||||
}
|
||||
lastPatternIndex = backrefRegex.lastIndex;
|
||||
}
|
||||
const finalLiteralPart = script.replaceString.substring(lastPatternIndex);
|
||||
charsAddedInMatch += finalLiteralPart.length;
|
||||
replacementForPlainText += finalLiteralPart;
|
||||
|
||||
totalCharsAdded += charsAddedInMatch;
|
||||
totalCharsRemoved += (originalMatchText.length - charsKeptFromMatch);
|
||||
|
||||
outputText += replacementForPlainText;
|
||||
// --- End of statistics logic ---
|
||||
|
||||
// --- Build the new Diff View HTML ---
|
||||
// 1. Show the entire original match as "removed" (red strikethrough)
|
||||
highlightedOutput += `<mark class='red_hl'>${escapeHtml(originalMatchText)}</mark>`;
|
||||
// 2. Add an arrow to signify transformation
|
||||
highlightedOutput += ' → ';
|
||||
// 3. Build the replacement string with green (added) and yellow (kept) parts
|
||||
highlightedOutput += buildReplacementHtml(match, script.replaceString);
|
||||
|
||||
lastIndex = match.index + originalMatchText.length;
|
||||
}
|
||||
|
||||
// Append text after the last match
|
||||
const trailingText = text.substring(lastIndex);
|
||||
outputText += trailingText;
|
||||
highlightedOutput += escapeHtml(trailingText);
|
||||
|
||||
} catch (e) {
|
||||
err = (err ? err + '; ' : '') + `Replace error: ${e.message}`;
|
||||
outputText = text; // Fallback
|
||||
highlightedOutput = escapeHtml(text);
|
||||
}
|
||||
|
||||
return {
|
||||
output: outputText,
|
||||
highlightedOutput: highlightedOutput,
|
||||
error: err,
|
||||
charsCaptured: totalCharsCaptured,
|
||||
charsAdded: totalCharsAdded,
|
||||
charsRemoved: totalCharsRemoved,
|
||||
};
|
||||
}
|
||||
|
||||
function populateDebuggerRuleList(container) {
|
||||
const rulesContainer = container.find('#regex_debugger_rules');
|
||||
const ruleTemplate = container.find('#regex_debugger_rule_template');
|
||||
if (!rulesContainer.length || !ruleTemplate.length) {
|
||||
console.error('Regex Debugger: Could not find rule list or template in the DOM.');
|
||||
return;
|
||||
}
|
||||
|
||||
rulesContainer.empty();
|
||||
|
||||
const allScripts = getRegexScripts();
|
||||
if (!allScripts || allScripts.length === 0) {
|
||||
rulesContainer.append('<div class="regex-debugger-no-rules">No regex rules found.</div>');
|
||||
return;
|
||||
}
|
||||
|
||||
const globalScriptIds = new Set((extension_settings.regex ?? []).map(s => s.id));
|
||||
const globalScripts = [];
|
||||
const scopedScripts = [];
|
||||
|
||||
allScripts.forEach(script => {
|
||||
const scriptCopy = structuredClone(script); // Use structuredClone for deep copy
|
||||
if (globalScriptIds.has(script.id)) {
|
||||
// @ts-ignore
|
||||
scriptCopy.isScoped = false;
|
||||
globalScripts.push(scriptCopy);
|
||||
} else {
|
||||
// @ts-ignore
|
||||
scriptCopy.isScoped = true;
|
||||
scopedScripts.push(scriptCopy);
|
||||
}
|
||||
});
|
||||
|
||||
container.data('allScripts', [...globalScripts, ...scopedScripts]);
|
||||
|
||||
const renderRule = (script) => {
|
||||
if (!script.id) script.id = uuidv4();
|
||||
const ruleElementContent = $(ruleTemplate.prop('content')).clone();
|
||||
const ruleElement = ruleElementContent.find('.regex-debugger-rule');
|
||||
|
||||
ruleElement.attr('data-id', script.id);
|
||||
// @ts-ignore
|
||||
ruleElement.find('.rule-name').text(script.scriptName);
|
||||
ruleElement.find('.rule-regex').text(script.findRegex);
|
||||
// @ts-ignore
|
||||
ruleElement.find('.rule-scope').text(script.isScoped ? 'Scoped' : 'Global');
|
||||
ruleElement.find('.rule-enabled').prop('checked', !script.disabled);
|
||||
// @ts-ignore
|
||||
ruleElement.find('.edit_rule').on('click', () => onRegexEditorOpenClick(script.id, script.isScoped));
|
||||
|
||||
ruleElement.on('click', function (event) {
|
||||
if ($(event.target).is('input, .menu_button, .menu_button i')) {
|
||||
return;
|
||||
}
|
||||
const scriptId = $(this).data('id');
|
||||
const stepElement = $(`#step-result-${scriptId}`);
|
||||
const container = $('#regex_debugger_steps_output');
|
||||
|
||||
if (stepElement.length && container.length) {
|
||||
// Replace scrollIntoView with scrollTop animation
|
||||
const targetTop = stepElement.position().top;
|
||||
const containerScrollTop = container.scrollTop();
|
||||
const containerHeight = container.height();
|
||||
|
||||
// Center the element if possible
|
||||
let scrollTo = containerScrollTop + targetTop - (containerHeight / 2) + (stepElement.height() / 2);
|
||||
|
||||
container.animate({ scrollTop: scrollTo }, 300); // 300ms smooth scroll
|
||||
|
||||
stepElement.css('transition', 'background-color 0.5s').css('background-color', 'var(--highlight_color)');
|
||||
setTimeout(() => stepElement.css('background-color', ''), 1000);
|
||||
}
|
||||
});
|
||||
|
||||
return ruleElementContent;
|
||||
};
|
||||
|
||||
if (globalScripts.length > 0) {
|
||||
rulesContainer.append('<div class="list-header regex-debugger-list-header">Global Rules</div>');
|
||||
const globalList = $('<ul id="regex_debugger_rules_global" class="sortable-list"></ul>');
|
||||
globalScripts.forEach(script => globalList.append(renderRule(script)));
|
||||
rulesContainer.append(globalList);
|
||||
}
|
||||
|
||||
if (scopedScripts.length > 0) {
|
||||
rulesContainer.append('<div class="list-header regex-debugger-list-header">Scoped Rules</div>');
|
||||
const scopedList = $('<ul id="regex_debugger_rules_scoped" class="sortable-list"></ul>');
|
||||
scopedScripts.forEach(script => scopedList.append(renderRule(script)));
|
||||
rulesContainer.append(scopedList);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the regex debugger.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function onRegexDebuggerOpenClick() {
|
||||
const templateContent = await renderExtensionTemplateAsync('regex', 'debugger');
|
||||
const debuggerHtml = $('<div>').html(templateContent);
|
||||
|
||||
const stepTemplate = debuggerHtml.find('#regex_debugger_step_template');
|
||||
|
||||
populateDebuggerRuleList(debuggerHtml);
|
||||
|
||||
// @ts-ignore
|
||||
debuggerHtml.find('#regex_debugger_rules_global').sortable({ delay: getSortableDelay() }).disableSelection();
|
||||
// @ts-ignore
|
||||
debuggerHtml.find('#regex_debugger_rules_scoped').sortable({ delay: getSortableDelay() }).disableSelection();
|
||||
|
||||
debuggerHtml.find('#regex_debugger_run_test').on('click', function () {
|
||||
const allScripts = debuggerHtml.data('allScripts');
|
||||
const orderedRuleIds = [
|
||||
...$('#regex_debugger_rules_global').find('li.regex-debugger-rule').map((i, el) => $(el).data('id')).get(),
|
||||
...$('#regex_debugger_rules_scoped').find('li.regex-debugger-rule').map((i, el) => $(el).data('id')).get(),
|
||||
];
|
||||
|
||||
const rawInput = String($('#regex_debugger_raw_input').val());
|
||||
const stepsOutput = $('#regex_debugger_steps_output');
|
||||
const finalOutput = $('#regex_debugger_final_output');
|
||||
|
||||
if (!stepsOutput.length || !finalOutput.length) return;
|
||||
|
||||
const displayMode = $('input[name="display_mode"]:checked').val();
|
||||
stepsOutput.empty();
|
||||
finalOutput.empty();
|
||||
$('#regex_debugger_final_summary').remove();
|
||||
|
||||
if (!allScripts) return;
|
||||
let textForNextStep = rawInput;
|
||||
let totalCharsCaptured = 0;
|
||||
let totalCharsAdded = 0;
|
||||
let totalCharsRemoved = 0;
|
||||
|
||||
orderedRuleIds.forEach(scriptId => {
|
||||
const ruleElement = $(`#regex_debugger_rules [data-id="${scriptId}"]`);
|
||||
if (!ruleElement.find('.rule-enabled').is(':checked')) return;
|
||||
|
||||
const script = allScripts.find(s => s.id === scriptId);
|
||||
|
||||
if (script) {
|
||||
const result = executeRegexScriptForDebugging(script, textForNextStep);
|
||||
totalCharsCaptured += result.charsCaptured;
|
||||
totalCharsAdded += result.charsAdded;
|
||||
totalCharsRemoved += result.charsRemoved;
|
||||
|
||||
const stepElement = $(stepTemplate.prop('content')).clone();
|
||||
// Set the ID on the TOP-LEVEL element that is being appended.
|
||||
stepElement.find('>:first-child').attr('id', `step-result-${script.id}`);
|
||||
const stepHeader = stepElement.find('.step-header');
|
||||
stepHeader.find('strong').text(`After: ${script.scriptName}`);
|
||||
|
||||
const metricsHtml = `<span class="step-metrics">Captured: ${result.charsCaptured}, Added: +${result.charsAdded}, Removed: -${result.charsRemoved}</span>`;
|
||||
stepHeader.append(metricsHtml);
|
||||
|
||||
if (displayMode === 'highlight') {
|
||||
stepElement.find('.step-output').html(result.highlightedOutput);
|
||||
} else {
|
||||
stepElement.find('.step-output').text(result.output);
|
||||
}
|
||||
|
||||
if (result.error) {
|
||||
stepHeader.append($(`<div class='warning_text text_rose-500'>${result.error}</div>`));
|
||||
}
|
||||
|
||||
stepsOutput.append(stepElement);
|
||||
textForNextStep = result.output;
|
||||
}
|
||||
});
|
||||
|
||||
const summaryHtml = `
|
||||
<div id="regex_debugger_final_summary" class="regex-debugger-summary">
|
||||
<strong>Total Captured:</strong> ${totalCharsCaptured} | <strong>Total Added:</strong> +${totalCharsAdded} | <strong>Total Removed:</strong> -${totalCharsRemoved}
|
||||
</div>
|
||||
`;
|
||||
finalOutput.before(summaryHtml);
|
||||
|
||||
const renderMode = $('#regex_debugger_render_mode').val();
|
||||
if (renderMode === 'message') {
|
||||
const formattedHtml = messageFormatting(textForNextStep, 'Debugger', true, false, null);
|
||||
const messageBlock = $('<div class="mes"><div class="mes_text"></div></div>');
|
||||
messageBlock.find('.mes_text').html(formattedHtml);
|
||||
finalOutput.append(messageBlock);
|
||||
} else {
|
||||
finalOutput.text(textForNextStep);
|
||||
}
|
||||
});
|
||||
|
||||
debuggerHtml.find('#regex_debugger_save_order').on('click', async function () {
|
||||
const allKnownScripts = getRegexScripts();
|
||||
const newGlobalScripts = $('#regex_debugger_rules_global').children('li').map((_, el) => allKnownScripts.find(s => s.id === $(el).data('id'))).get().filter(Boolean);
|
||||
const newScopedScripts = $('#regex_debugger_rules_scoped').children('li').map((_, el) => allKnownScripts.find(s => s.id === $(el).data('id'))).get().filter(Boolean);
|
||||
|
||||
extension_settings.regex = newGlobalScripts;
|
||||
if (this_chid !== undefined) {
|
||||
await writeExtensionField(this_chid, 'regex_scripts', newScopedScripts);
|
||||
}
|
||||
|
||||
saveSettingsDebounced();
|
||||
await loadRegexScripts();
|
||||
toastr.success(t`Regex script order saved!`);
|
||||
|
||||
const currentPopupContent = $('div:has(> #regex_debugger_rules)');
|
||||
populateDebuggerRuleList(currentPopupContent);
|
||||
// @ts-ignore
|
||||
currentPopupContent.find('#regex_debugger_rules_global').sortable({ delay: getSortableDelay() }).disableSelection();
|
||||
// @ts-ignore
|
||||
currentPopupContent.find('#regex_debugger_rules_scoped').sortable({ delay: getSortableDelay() }).disableSelection();
|
||||
});
|
||||
|
||||
debuggerHtml.find('#regex_debugger_expand_steps').on('click', function () {
|
||||
const popupContainer = $('<div class="expanded-regex-container"></div>');
|
||||
const navPanel = $('<div class="expanded-regex-nav"><h4>Steps</h4></div>');
|
||||
const contentPanel = $('<div class="expanded-regex-content"></div>');
|
||||
|
||||
const content = $('#regex_debugger_steps_output').clone().html();
|
||||
contentPanel.html(content);
|
||||
|
||||
$('#regex_debugger_rules .regex-debugger-rule').each(function () {
|
||||
const ruleElement = $(this);
|
||||
const scriptId = ruleElement.data('id');
|
||||
const scriptName = ruleElement.find('.rule-name').text();
|
||||
|
||||
const link = $(`<a href="#">${escapeHtml(scriptName)}</a>`);
|
||||
link.data('target-id', `step-result-${scriptId}`);
|
||||
|
||||
link.on('click', function (e) {
|
||||
e.preventDefault();
|
||||
navPanel.find('a').removeClass('active');
|
||||
$(this).addClass('active');
|
||||
|
||||
const targetId = $(this).data('target-id');
|
||||
// The selector is now correct for the structure.
|
||||
const targetElement = contentPanel.find(`#${targetId}`);
|
||||
|
||||
if (targetElement.length) {
|
||||
const scrollTo = contentPanel.scrollTop() + targetElement.position().top;
|
||||
contentPanel.animate({ scrollTop: scrollTo }, 300);
|
||||
|
||||
targetElement.css('transition', 'background-color 0.5s').css('background-color', 'var(--highlight_color)');
|
||||
setTimeout(() => targetElement.css('background-color', ''), 1000);
|
||||
}
|
||||
});
|
||||
|
||||
navPanel.append(link);
|
||||
});
|
||||
|
||||
popupContainer.append(navPanel).append(contentPanel);
|
||||
callGenericPopup(popupContainer, POPUP_TYPE.TEXT, 'Step-by-step Transformation', { wide: true, allowVerticalScrolling: false });
|
||||
});
|
||||
|
||||
debuggerHtml.find('#regex_debugger_expand_final').on('click', function () {
|
||||
const content = $('#regex_debugger_final_output').html();
|
||||
const popupContent = $('<div style="height: 70vh; overflow-y: auto;"></div>').html(content);
|
||||
callGenericPopup(popupContent, POPUP_TYPE.TEXT, 'Final Output', { wide: true, allowVerticalScrolling: true });
|
||||
});
|
||||
|
||||
await callGenericPopup(debuggerHtml.children(), POPUP_TYPE.TEXT, '', { wide: true, allowVerticalScrolling: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the info block in the regex editor with hints regarding the find regex.
|
||||
* @param {JQuery<HTMLElement>} editorHtml The editor HTML
|
||||
@@ -606,6 +1047,7 @@ jQuery(async () => {
|
||||
$('#open_regex_editor').on('click', function () {
|
||||
onRegexEditorOpenClick(false, false);
|
||||
});
|
||||
$('#open_regex_debugger').on('click', onRegexDebuggerOpenClick);
|
||||
$('#open_scoped_editor').on('click', function () {
|
||||
if (this_chid === undefined) {
|
||||
toastr.error(t`No character selected.`);
|
||||
@@ -726,6 +1168,7 @@ jQuery(async () => {
|
||||
},
|
||||
];
|
||||
for (const { selector, setter, getter } of sortableDatas) {
|
||||
// @ts-ignore
|
||||
$(selector).sortable({
|
||||
delay: getSortableDelay(),
|
||||
stop: async function () {
|
||||
@@ -778,6 +1221,7 @@ jQuery(async () => {
|
||||
});
|
||||
|
||||
await loadRegexScripts();
|
||||
// @ts-ignore
|
||||
$('#saved_regex_scripts').sortable('enable');
|
||||
|
||||
const localEnumProviders = {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
@import "debugger.css";
|
||||
|
||||
.regex_settings .menu_button {
|
||||
width: fit-content;
|
||||
display: flex;
|
||||
|
||||
Reference in New Issue
Block a user