-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
396 lines (333 loc) · 15.9 KB
/
Copy pathindex.js
File metadata and controls
396 lines (333 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
(async function () {
'use strict';
// Imports from SillyTavern
const { getContext } = await import('../../../../scripts/st-context.js');
const { extension_settings } = await import('../../../extensions.js');
// Extension details
const extensionName = 'dynamic-vars';
const extensionFolderPath = `scripts/extensions/third-party/${extensionName}`;
const context = getContext();
const EXTENSION_NAME_DISPLAY = 'Dynamic Variable Hooks';
// A simple debounce function to prevent rapid execution
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// --- State Management ---
let variablePools = {};
const sessionVariables = {};
let isNewSession = false;
// --- Settings and UI ---
function loadVariablePools() {
const settings = extension_settings[extensionName] ?? {};
if (settings && Object.keys(settings).length > 0) {
variablePools = settings;
console.log(`[${EXTENSION_NAME_DISPLAY}] Loaded ${Object.keys(variablePools).length} variable pools.`);
} else {
variablePools = {
name: ['小红', '小丽', '小芳', '小燕', '小娟', '小静', '小梅', '小玲', '小慧', '小英', '王芳', '李丽', '赵敏', '徐文静', '钱多多', '田甜', '贝贝', '菲菲', '婷婷', '媛媛', '冰冰', '彩彩', '芳芳', '洁洁', '美美', '糖糖', '薇薇', '雪雪', '艳艳', '宝宝'],
age: ['16', '17', '18', '19', '20', '21', '22', '23'],
};
console.log(`[${EXTENSION_NAME_DISPLAY}] No settings found. Using default pools.`);
}
}
// This function will be called to rebuild the UI from the settings object
function renderPools() {
const settings = extension_settings[extensionName] ?? {};
const list = $('#dynamic-vars-pools-list');
list.empty(); // Clear the current list
for (const [name, values] of Object.entries(settings)) {
if (Array.isArray(values)) {
addPoolRow(name, values.join(', '));
}
}
}
// This function adds a single row to the UI, optionally with pre-filled data
function addPoolRow(name = '', values = '') {
const list = $('#dynamic-vars-pools-list');
const template = $('#dynamic-vars-pool-template').clone();
template.removeAttr('id'); // Remove ID from the clone
template.find('.dynamic-vars-pool-name').val(name);
template.find('.dynamic-vars-pool-values').val(values);
// Attach event listeners
template.find('.dynamic-vars-pool-delete').on('click', function() {
$(this).closest('.dynamic-vars-pool-row').remove();
onSettingsChange(); // Trigger a save after deleting
});
const debouncedSave = debounce(onSettingsChange, 500);
template.find('input, textarea').on('input', debouncedSave);
// Auto-resize textarea
template.find('textarea').on('input', function() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
template.css('display', 'flex'); // Make it visible
list.append(template);
// Trigger initial resize
template.find('textarea').trigger('input');
}
// This function now reads from the UI and saves
function onSettingsChange() {
const newSettings = {};
let hasError = false;
let duplicatesRemoved = false; // Flag to track if any duplicates were removed
let valuesSorted = false; // Flag to track if any values were sorted
$('#dynamic-vars-pools-list .dynamic-vars-pool-row').each(function() {
const row = $(this);
const nameInput = row.find('.dynamic-vars-pool-name');
const name = nameInput.val().trim();
const valuesInput = row.find('.dynamic-vars-pool-values');
const values = valuesInput.val();
nameInput.removeClass('error');
if (!name) {
// Skip empty rows silently, they won't be saved.
return;
}
// Check for duplicate names
if (newSettings.hasOwnProperty(name)) {
nameInput.addClass('error');
hasError = true;
const status = $('#dynamic-vars-status');
status.text(`Error: Duplicate variable name "${name}".`).addClass('error').removeClass('success').fadeIn();
return; // Stop processing this row
}
const valuesArray = values.split(',')
.map(v => v.trim())
.filter(v => v); // Remove empty strings
// Create a new array with unique values using a Set
const uniqueValuesArray = [...new Set(valuesArray)];
// Check if duplicates were removed
if (uniqueValuesArray.length < valuesArray.length) {
duplicatesRemoved = true;
}
// Sort the array. localeCompare with numeric option handles numbers and strings well.
const sortedValuesArray = [...uniqueValuesArray].sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
// Check if sorting changed the order of the unique array
if (JSON.stringify(uniqueValuesArray) !== JSON.stringify(sortedValuesArray)) {
valuesSorted = true;
}
// If the UI needs updating (duplicates removed or values sorted), do it once.
if (duplicatesRemoved || valuesSorted) {
valuesInput.val(sortedValuesArray.join(', '));
}
newSettings[name] = sortedValuesArray;
});
if (hasError) {
return; // Don't save if there are errors
}
// Combine notifications into one
const notifications = [];
if (duplicatesRemoved) {
notifications.push('duplicates removed');
}
if (valuesSorted) {
notifications.push('values sorted');
}
if (notifications.length > 0) {
toastr.info(`Values were automatically updated: ${notifications.join(' & ')}.`, 'Auto-Updated');
}
try {
extension_settings[extensionName] = newSettings;
context.saveSettingsDebounced();
loadVariablePools(); // Reload pools in the extension logic
const status = $('#dynamic-vars-status');
status.text('Settings saved!').addClass('success').removeClass('error').fadeIn();
setTimeout(() => status.fadeOut(), 3000);
} catch (error) {
console.error(`[${EXTENSION_NAME_DISPLAY}] Error saving settings:`, error);
const status = $('#dynamic-vars-status');
status.text(`Error: ${error.message}.`).addClass('error').removeClass('success').fadeIn();
}
}
async function onResetSettings() {
const confirmation = await context.callGenericPopup(
'Are you sure you want to reset all settings for this extension? This cannot be undone.',
context.POPUP_TYPE.CONFIRM,
);
if (confirmation === context.POPUP_RESULT.AFFIRMATIVE) {
extension_settings[extensionName] = {};
context.saveSettingsDebounced();
renderPools(); // Re-render the UI to show it's empty
toastr.success('Dynamic Variable Hooks settings have been reset.');
}
}
// This function now just calls renderPools
function loadUiSettings() {
// Ensure the extension's settings object exists.
if (!extension_settings[extensionName]) {
extension_settings[extensionName] = {};
}
renderPools();
}
// --- Core Logic (processing placeholders) ---
function clearObject(obj) {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
delete obj[key];
}
}
}
function getRandomFromPool(name) {
const pool = variablePools[name];
if (!pool || pool.length === 0) {
console.warn(`[${EXTENSION_NAME_DISPLAY}] Variable pool "${name}" not found or is empty.`);
return `{{getrand::${name}}}`;
}
return pool[Math.floor(Math.random() * pool.length)];
}
// Helper for inline pipe-separated lists (one-off, no session storage)
function handleInlinePool(match, name) {
const inlinePool = name.split('|').map(v => v.trim()).filter(Boolean);
if (inlinePool.length > 0) {
const randomValue = inlinePool[Math.floor(Math.random() * inlinePool.length)];
console.log(`[${EXTENSION_NAME_DISPLAY}] Generated new inline value for ${match}: "${randomValue}"`);
return randomValue;
}
// If the inline pool is empty after trimming (e.g., "{{getrand::|}}"), return the original match
return match;
}
// Helper for number ranges
function handleNumberRange(match, name) {
const rangeMatch = name.match(/^(\d+)-(\d+)$/);
if (!rangeMatch) return null; // Indicates it's not a range
const min = parseInt(rangeMatch[1], 10);
const max = parseInt(rangeMatch[2], 10);
if (min > max) {
console.warn(`[${EXTENSION_NAME_DISPLAY}] Invalid range in ${match}: min > max.`);
return match; // Return original match to indicate an error
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function process(text) {
if (typeof text !== 'string') return text;
return text.replace(/\{\{(getrand|regetrand)::(.*?)\}\}/g, (match, command, name) => {
// 1. Handle inline pipe-separated lists (one-off, no session storage)
// These are always treated as a one-off, regardless of getrand/regetrand.
if (name.includes('|')) {
return handleInlinePool(match, name);
}
// 2. For 'getrand', check for an existing session variable and return it if found.
if (command === 'getrand' && sessionVariables[name] !== undefined) {
return sessionVariables[name];
}
// 3. Generate a new value (for 'regetrand' or a first-time 'getrand').
let newValue = handleNumberRange(match, name);
if (newValue === null) { // If it wasn't a number range, try a named pool.
newValue = getRandomFromPool(name);
}
// If generation failed (e.g., invalid range, pool not found), return the original placeholder.
if (newValue === match || String(newValue).includes('::')) {
return match;
}
// 4. Store and return the new value for the session.
const logMessage = command === 'regetrand' ? 'Re-generated' : 'Generated new';
sessionVariables[name] = newValue;
console.log(`[${EXTENSION_NAME_DISPLAY}] ${logMessage} value for ${match}: "${sessionVariables[name]}"`);
return sessionVariables[name];
});
}
// --- Event Handlers (for placeholder logic) ---
function onNewSessionStarted(eventName) {
console.log(`[${EXTENSION_NAME_DISPLAY}] EVENT: '${eventName}' received. Flagging for new session.`);
isNewSession = true;
}
function onChatLoaded(event) {
const character = event?.detail?.character ?? context.characters?.[context.characterId];
if (!character) {
return;
}
if (isNewSession) {
console.log(`[${EXTENSION_NAME_DISPLAY}] New session detected. Clearing session variables.`);
clearObject(sessionVariables);
isNewSession = false;
}
if (context.chat?.length === 1 && !context.chat[0].is_user && character.first_mes) {
const firstMessage = context.chat[0];
const processedGreeting = process(character.first_mes);
if (firstMessage.mes !== processedGreeting) {
firstMessage.mes = processedGreeting;
context.updateMessageBlock(0, firstMessage);
}
}
}
function onUserMessageRendered(index) {
// Guard against invalid index
if (typeof index !== 'number' || index < 0 || index >= context.chat.length) {
return;
}
const message = context.chat[index];
// Double-check it's a user message and hasn't been processed before
// to prevent loops if updateMessageBlock re-triggers the event.
if (message && message.is_user && !message.is_dynamic_vars_processed) {
const originalText = message.mes;
const processedText = process(originalText);
if (originalText !== processedText) {
console.log(`[${EXTENSION_NAME_DISPLAY}] Processing rendered user message (index ${index}) via 'user_message_rendered' event.`);
console.log(`[${EXTENSION_NAME_DISPLAY}] - Original: "${originalText}"`);
console.log(`[${EXTENSION_NAME_DISPLAY}] - Processed: "${processedText}"`);
message.mes = processedText;
// Mark as processed to prevent infinite loops. This property is transient.
message.is_dynamic_vars_processed = true;
context.updateMessageBlock(index, message);
}
}
}
function onAfterCombinePrompts(eventData) {
if (eventData && typeof eventData.prompt === 'string' && eventData.prompt.length > 0) {
eventData.prompt = process(eventData.prompt);
}
}
function onChatCompletionPromptReady(eventData) {
const promptArray = eventData?.prompt ?? eventData?.chat;
if (eventData && Array.isArray(promptArray)) {
promptArray.forEach(message => {
if (typeof message.content === 'string') {
message.content = process(message.content);
}
});
}
}
// --- Main Initialization ---
function initialize() {
loadVariablePools();
const onSettingsReload = () => {
loadVariablePools();
loadUiSettings();
};
const { eventSource } = context;
eventSource.on(context.event_types.CHAT_CHANGED, () => onNewSessionStarted('CHAT_CHANGED'));
eventSource.on('chat_created', () => onNewSessionStarted('chat_created'));
eventSource.on('chatLoaded', onChatLoaded);
eventSource.on('user_message_rendered', onUserMessageRendered);
eventSource.on('generate_after_combine_prompts', onAfterCombinePrompts);
eventSource.on('chat_completion_prompt_ready', onChatCompletionPromptReady);
eventSource.on('settings_loaded', onSettingsReload);
eventSource.on('extension_settings_loaded', onSettingsReload);
console.log(`[${EXTENSION_NAME_DISPLAY}] Extension logic is active.`);
}
// This function runs when the DOM is ready.
jQuery(async () => {
try {
const settingsHtml = await $.get(`${extensionFolderPath}/ui.html`);
$('#extensions_settings2').append(settingsHtml);
// Attach listener for the "Add Variable" button
$('#dynamic-vars-add-pool').on('click', function() {
addPoolRow();
});
$('#dynamic-vars-reset-settings').on('click', onResetSettings);
loadUiSettings();
console.log(`[${EXTENSION_NAME_DISPLAY}] UI loaded.`);
} catch (error) {
console.error(`[${EXTENSION_NAME_DISPLAY}] Failed to load or initialize UI. This is likely due to a missing or incorrect 'ui.html' file.`, error);
toastr.error('Failed to initialize the Dynamic Variable Hooks UI. Check the console (F12) for details.', 'Extension Error');
}
});
initialize();
})();