import { saveSettingsDebounced, callPopup, getRequestHeaders, substituteParams, eventSource, event_types, animation_duration } from '../../../script.js'; import { getContext, extension_settings } from '../../extensions.js'; import { getSortableDelay, escapeHtml, delay } from '../../utils.js'; import { executeSlashCommands, registerSlashCommand } from '../../slash-commands.js'; import { ContextMenu } from './src/ContextMenu.js'; import { MenuItem } from './src/MenuItem.js'; import { MenuHeader } from './src/MenuHeader.js'; import { loadMovingUIState } from '../../power-user.js'; import { dragElement } from '../../RossAscends-mods.js'; export { MODULE_NAME }; const MODULE_NAME = 'quick-reply'; const UPDATE_INTERVAL = 1000; let presets = []; let selected_preset = ''; const defaultSettings = { quickReplyEnabled: false, numberOfSlots: 5, quickReplySlots: [], placeBeforeInputEnabled: false, quickActionEnabled: false, AutoInputInject: true, }; //method from worldinfo async function updateQuickReplyPresetList() { const result = await fetch('/api/settings/get', { method: 'POST', headers: getRequestHeaders(), body: JSON.stringify({}), }); if (result.ok) { var data = await result.json(); presets = data.quickReplyPresets?.length ? data.quickReplyPresets : []; console.debug('Quick Reply presets', presets); $('#quickReplyPresets').find('option[value!=""]').remove(); if (presets !== undefined) { presets.forEach((item) => { const option = document.createElement('option'); option.value = item.name; option.innerText = item.name; option.selected = selected_preset.includes(item.name); $('#quickReplyPresets').append(option); }); } } } async function loadSettings(type) { if (type === 'init') { await updateQuickReplyPresetList(); } if (Object.keys(extension_settings.quickReply).length === 0) { Object.assign(extension_settings.quickReply, defaultSettings); } if (extension_settings.quickReply.AutoInputInject === undefined) { extension_settings.quickReply.AutoInputInject = true; } // If the user has an old version of the extension, update it if (!Array.isArray(extension_settings.quickReply.quickReplySlots)) { extension_settings.quickReply.quickReplySlots = []; extension_settings.quickReply.numberOfSlots = defaultSettings.numberOfSlots; for (let i = 1; i <= extension_settings.quickReply.numberOfSlots; i++) { extension_settings.quickReply.quickReplySlots.push({ mes: extension_settings.quickReply[`quickReply${i}Mes`], label: extension_settings.quickReply[`quickReply${i}Label`], enabled: true, }); delete extension_settings.quickReply[`quickReply${i}Mes`]; delete extension_settings.quickReply[`quickReply${i}Label`]; } } initializeEmptySlots(extension_settings.quickReply.numberOfSlots); generateQuickReplyElements(); for (let i = 1; i <= extension_settings.quickReply.numberOfSlots; i++) { $(`#quickReply${i}Mes`).val(extension_settings.quickReply.quickReplySlots[i - 1]?.mes).trigger('input'); $(`#quickReply${i}Label`).val(extension_settings.quickReply.quickReplySlots[i - 1]?.label).trigger('input'); } $('#quickReplyEnabled').prop('checked', extension_settings.quickReply.quickReplyEnabled); $('#quickReplyNumberOfSlots').val(extension_settings.quickReply.numberOfSlots); $('#placeBeforeInputEnabled').prop('checked', extension_settings.quickReply.placeBeforeInputEnabled); $('#quickActionEnabled').prop('checked', extension_settings.quickReply.quickActionEnabled); $('#AutoInputInject').prop('checked', extension_settings.quickReply.AutoInputInject); } function onQuickReplyInput(id) { extension_settings.quickReply.quickReplySlots[id - 1].mes = $(`#quickReply${id}Mes`).val(); $(`#quickReply${id}`).attr('title', String($(`#quickReply${id}Mes`).val())); saveSettingsDebounced(); } function onQuickReplyLabelInput(id) { extension_settings.quickReply.quickReplySlots[id - 1].label = $(`#quickReply${id}Label`).val(); addQuickReplyBar(); saveSettingsDebounced(); } async function onQuickReplyContextMenuChange(id) { extension_settings.quickReply.quickReplySlots[id - 1].contextMenu = JSON.parse($(`#quickReplyContainer > [data-order="${id}"]`).attr('data-contextMenu')); saveSettingsDebounced(); } async function onQuickReplyCtxButtonClick(id) { const editorHtml = $(await $.get('scripts/extensions/quick-reply/contextMenuEditor.html')); const popupResult = callPopup(editorHtml, 'confirm', undefined, { okButton: 'Save', wide: false, large: false, rows: 1 }); const qr = extension_settings.quickReply.quickReplySlots[id - 1]; if (!qr.contextMenu) { qr.contextMenu = []; } /**@type {HTMLTemplateElement}*/ const tpl = document.querySelector('#quickReply_contextMenuEditor_itemTemplate'); const fillPresetSelect = (select, item) => { [{ name: 'Select a preset', value: '' }, ...presets].forEach(preset => { const opt = document.createElement('option'); { opt.value = preset.value ?? preset.name; opt.textContent = preset.name; opt.selected = preset.name == item.preset; select.append(opt); } }); }; const addCtxItem = (item, idx) => { const dom = tpl.content.cloneNode(true); const ctxItem = dom.querySelector('.quickReplyContextMenuEditor_item'); ctxItem.setAttribute('data-order', idx); const select = ctxItem.querySelector('.quickReply_contextMenuEditor_preset'); fillPresetSelect(select, item); dom.querySelector('.quickReply_contextMenuEditor_chaining').checked = item.chain; $('.quickReply_contextMenuEditor_remove', ctxItem).on('click', () => ctxItem.remove()); document.querySelector('#quickReply_contextMenuEditor_content').append(ctxItem); }; [...qr.contextMenu, {}].forEach((item, idx) => { addCtxItem(item, idx); }); $('#quickReply_contextMenuEditor_addPreset').on('click', () => { addCtxItem({}, document.querySelector('#quickReply_contextMenuEditor_content').children.length); }); $('#quickReply_contextMenuEditor_content').sortable({ delay: getSortableDelay(), stop: () => { }, }); $('#quickReply_autoExecute_userMessage').prop('checked', qr.autoExecute_userMessage ?? false); $('#quickReply_autoExecute_botMessage').prop('checked', qr.autoExecute_botMessage ?? false); $('#quickReply_autoExecute_chatLoad').prop('checked', qr.autoExecute_chatLoad ?? false); $('#quickReply_autoExecute_appStartup').prop('checked', qr.autoExecute_appStartup ?? false); $('#quickReply_hidden').prop('checked', qr.hidden ?? false); $('#quickReply_hidden').on('input', () => { const state = !!$('#quickReply_hidden').prop('checked'); qr.hidden = state; saveSettingsDebounced(); }); $('#quickReply_autoExecute_appStartup').on('input', () => { const state = !!$('#quickReply_autoExecute_appStartup').prop('checked'); qr.autoExecute_appStartup = state; saveSettingsDebounced(); }); $('#quickReply_autoExecute_userMessage').on('input', () => { const state = !!$('#quickReply_autoExecute_userMessage').prop('checked'); qr.autoExecute_userMessage = state; saveSettingsDebounced(); }); $('#quickReply_autoExecute_botMessage').on('input', () => { const state = !!$('#quickReply_autoExecute_botMessage').prop('checked'); qr.autoExecute_botMessage = state; saveSettingsDebounced(); }); $('#quickReply_autoExecute_chatLoad').on('input', () => { const state = !!$('#quickReply_autoExecute_chatLoad').prop('checked'); qr.autoExecute_chatLoad = state; saveSettingsDebounced(); }); $('#quickReply_ui_title').val(qr.title ?? ''); if (await popupResult) { qr.contextMenu = Array.from(document.querySelectorAll('#quickReply_contextMenuEditor_content > .quickReplyContextMenuEditor_item')) .map(item => ({ preset: item.querySelector('.quickReply_contextMenuEditor_preset').value, chain: item.querySelector('.quickReply_contextMenuEditor_chaining').checked, })) .filter(item => item.preset); $(`#quickReplyContainer[data-order="${id}"]`).attr('data-contextMenu', JSON.stringify(qr.contextMenu)); qr.title = $('#quickReply_ui_title').val(); saveSettingsDebounced(); updateQuickReplyPreset(); onQuickReplyLabelInput(id); } } async function onQuickReplyEnabledInput() { let isEnabled = $(this).prop('checked'); extension_settings.quickReply.quickReplyEnabled = !!isEnabled; if (isEnabled === true) { $('#quickReplyBar').show(); } else { $('#quickReplyBar').hide(); } saveSettingsDebounced(); } // New function to handle input on quickActionEnabled async function onQuickActionEnabledInput() { extension_settings.quickReply.quickActionEnabled = !!$(this).prop('checked'); saveSettingsDebounced(); } async function onPlaceBeforeInputEnabledInput() { extension_settings.quickReply.placeBeforeInputEnabled = !!$(this).prop('checked'); saveSettingsDebounced(); } async function onAutoInputInject() { extension_settings.quickReply.AutoInputInject = !!$(this).prop('checked'); saveSettingsDebounced(); } async function sendQuickReply(index) { const prompt = extension_settings.quickReply.quickReplySlots[index]?.mes || ''; return await performQuickReply(prompt, index); } async function executeQuickReplyByName(name) { if (!extension_settings.quickReply.quickReplyEnabled) { throw new Error('Quick Reply is disabled'); } let qr = extension_settings.quickReply.quickReplySlots.find(x => x.label == name); if (!qr && name.includes('.')) { const [presetName, qrName] = name.split('.'); const preset = presets.find(x => x.name == presetName); if (preset) { qr = preset.quickReplySlots.find(x => x.label == qrName); } } if (!qr) { throw new Error(`Quick Reply "${name}" not found`); } return await performQuickReply(qr.mes); } window['executeQuickReplyByName'] = executeQuickReplyByName; async function performQuickReply(prompt, index) { if (!prompt) { console.warn(`Quick reply slot ${index} is empty! Aborting.`); return; } const existingText = $('#send_textarea').val(); let newText; if (existingText && extension_settings.quickReply.AutoInputInject) { if (extension_settings.quickReply.placeBeforeInputEnabled) { newText = `${prompt} ${existingText} `; } else { newText = `${existingText} ${prompt} `; } } else { // If no existing text and placeBeforeInputEnabled false, add prompt only (with a trailing space) newText = `${prompt} `; } // the prompt starts with '/' - execute slash commands natively if (prompt.startsWith('/')) { const result = await executeSlashCommands(newText); return typeof result === 'object' ? result?.pipe : ''; } newText = substituteParams(newText); $('#send_textarea').val(newText); // Set the focus back to the textarea $('#send_textarea').trigger('focus'); // Only trigger send button if quickActionEnabled is not checked or if (!extension_settings.quickReply.quickActionEnabled) { $('#send_but').trigger('click'); } } function buildContextMenu(qr, chainMes = null, hierarchy = [], labelHierarchy = []) { const tree = { label: qr.label, mes: (chainMes && qr.mes ? `${chainMes} | ` : '') + qr.mes, children: [], }; qr.contextMenu?.forEach(ctxItem => { let chain = ctxItem.chain; let subName = ctxItem.preset; const sub = presets.find(it => it.name == subName); if (sub) { // prevent circular references if (hierarchy.indexOf(sub.name) == -1) { const nextHierarchy = [...hierarchy, sub.name]; const nextLabelHierarchy = [...labelHierarchy, tree.label]; tree.children.push(new MenuHeader(sub.name)); sub.quickReplySlots.forEach(subQr => { const subInfo = buildContextMenu(subQr, chain ? tree.mes : null, nextHierarchy, nextLabelHierarchy); tree.children.push(new MenuItem( subInfo.label, subInfo.mes, (evt) => { evt.stopPropagation(); performQuickReply(subInfo.mes.replace(/%%parent(-\d+)?%%/g, (_, index) => { return nextLabelHierarchy.slice(parseInt(index ?? '-1'))[0]; })); }, subInfo.children, )); }); } } }); return tree; } async function doQuickReplyBarPopout() { //shared elements const newQuickRepliesDiv = '
'; const popoutButtonClone = $('#quickReplyPopoutButton'); if ($('#quickReplyBarPopout').length === 0) { console.debug('did not see popout yet, creating'); const template = $('#zoomed_avatar_template').html(); const controlBarHtml = `