Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

implement template vars for select field

Forhad Hosain865bdfc0e3ce
diff --git a/packages/app/src/builder-ui/components/Component.class/index.ts b/packages/app/src/builder-ui/components/Component.class/index.ts
index 23aace6f..bab6944a 100644
--- a/packages/app/src/builder-ui/components/Component.class/index.ts
+++ b/packages/app/src/builder-ui/components/Component.class/index.ts
@@ -262,6 +262,14 @@ export class Component extends EventEmitter {
this.data = this.properties.data || {};
+ // Auto-initialize templateVarToggleStates for template variable toggle functionality
+ if (
+ !this.data.templateVarToggleStates ||
+ typeof this.data.templateVarToggleStates !== 'object'
+ ) {
+ this.data.templateVarToggleStates = {};
+ }
+
if (this.properties.template) {
const template = this.properties.template;
this.properties.inputs = [
diff --git a/packages/app/src/builder-ui/components/Component.class/settings-editor.ts b/packages/app/src/builder-ui/components/Component.class/settings-editor.ts
index 09c1cc3a..e6ddec0e 100644
--- a/packages/app/src/builder-ui/components/Component.class/settings-editor.ts
+++ b/packages/app/src/builder-ui/components/Component.class/settings-editor.ts
@@ -379,6 +379,11 @@ async function onSave(values) {
for (let name in component.settings) {
component.data[name] = settingsValues[name];
}
+
+ // Always copy templateVarToggleStates if it exists (auto-injected field)
+ if (settingsValues.hasOwnProperty('templateVarToggleStates')) {
+ component.data.templateVarToggleStates = settingsValues.templateVarToggleStates;
+ }
} else {
//if it's a template we match template variables to their respective values ==> they will be replaced in the backend
const tplSettings = component.templateSettings;
@@ -393,6 +398,11 @@ async function onSave(values) {
for (let name in tplSettings) {
component.data._templateVars[name] = settingsValues[name];
}
+
+ // Always copy templateVarToggleStates if it exists (auto-injected field)
+ if (settingsValues.hasOwnProperty('templateVarToggleStates')) {
+ component.data.templateVarToggleStates = settingsValues.templateVarToggleStates;
+ }
}
//console.log('new settings', component.settings);
@@ -518,6 +528,14 @@ export async function closeSettings(component: Component, force = false) {
}
export async function editSettings(component: Component) {
Component.curComponentSettings = component;
+
+ // Expose Component.curComponentSettings on window so form fields can access it
+ if (typeof window !== 'undefined') {
+ if (!(window as any).Component) {
+ (window as any).Component = {};
+ }
+ (window as any).Component.curComponentSettings = component;
+ }
component.workspace.domElement
.querySelectorAll('.component.active')
.forEach((component: HTMLElement) => {
@@ -933,6 +951,12 @@ export async function editSettings(component: Component) {
for (let name in component.settings) {
component.data[name] = settingsValues[name];
}
+
+ // Always copy templateVarToggleStates if it exists (auto-injected field)
+ if (settingsValues.hasOwnProperty('templateVarToggleStates')) {
+ component.data.templateVarToggleStates =
+ settingsValues.templateVarToggleStates;
+ }
} else {
//if it's a template we match template variables to their respective values ==> they will be replaced in the backend
const tplSettings = component.templateSettings;
@@ -949,6 +973,12 @@ export async function editSettings(component: Component) {
templateData[name] = settingsValues[name];
}
//component.data._templateData = JSON.stringify(templateData);
+
+ // Always copy templateVarToggleStates if it exists (auto-injected field)
+ if (settingsValues.hasOwnProperty('templateVarToggleStates')) {
+ component.data.templateVarToggleStates =
+ settingsValues.templateVarToggleStates;
+ }
}
console.log('template save settings', component.settings);
diff --git a/packages/app/src/builder-ui/components/GenAILLM.class.ts b/packages/app/src/builder-ui/components/GenAILLM.class.ts
index c39839ba..89767c5c 100644
--- a/packages/app/src/builder-ui/components/GenAILLM.class.ts
+++ b/packages/app/src/builder-ui/components/GenAILLM.class.ts
@@ -720,6 +720,7 @@ export class GenAILLM extends Component {
],
attributes: {
'data-template-vars': 'true',
+ 'data-template-excluded-vars': 'Attachment',
'data-supported-models': this.gpt5Models.join(','),
},
help: 'Control how much reasoning detail appears in the response.',
diff --git a/packages/app/src/builder-ui/ui/form/createFormField.ts b/packages/app/src/builder-ui/ui/form/createFormField.ts
index d862c854..2e95e383 100644
--- a/packages/app/src/builder-ui/ui/form/createFormField.ts
+++ b/packages/app/src/builder-ui/ui/form/createFormField.ts
@@ -76,7 +76,6 @@ export default function createFormField(entry, displayType = 'block', entryIndex
let templateVarToggle: HTMLInputElement | null = null;
let templateVarModeDefault = false;
let hasTemplateVarToggle = false;
- let lastSelectValue = value;
switch (entry.type) {
case 'select':
@@ -93,29 +92,6 @@ export default function createFormField(entry, displayType = 'block', entryIndex
hasTemplateVarToggle =
String(attributes?.['data-template-vars'] || '').toLowerCase() === 'true';
- if (hasTemplateVarToggle) {
- templateVarInput = createInput(value);
- templateVarInput.setAttribute('type', 'text');
- templateVarInput.setAttribute('placeholder', 'Enter template variables...');
-
- // Add data-template-vars to enable template variable insertion
- templateVarInput.setAttribute('data-template-vars', 'true');
-
- // Remove Metro UI data-role to prevent Metro styling
- templateVarInput.removeAttribute('data-role');
-
- templateVarInput.classList.add('template-var-input');
- // Don't set display:none here - let the wrapper control visibility
- templateVarInput.style.paddingRight = '36px';
-
- // Ensure input looks enabled with proper styling
- templateVarInput.style.backgroundColor = '#ffffff';
- templateVarInput.style.cursor = 'text';
- templateVarInput.style.opacity = '1';
-
- templateVarModeDefault = typeof value === 'string' && /{{.*?}}/.test(value);
- }
-
break;
case 'checkbox':
case 'CHECKBOX':
@@ -348,7 +324,9 @@ export default function createFormField(entry, displayType = 'block', entryIndex
case 'hidden':
case 'HIDDEN':
- formElement = createHiddenInput(value);
+ // Serialize objects to JSON string for hidden fields (they only accept strings)
+ const serializedValue = typeof value === 'object' ? JSON.stringify(value) : value;
+ formElement = createHiddenInput(serializedValue);
break;
@@ -543,14 +521,10 @@ export default function createFormField(entry, displayType = 'block', entryIndex
// Store events to be attached after MetroUI initialization
formElement.setAttribute('data-deferred-events', JSON.stringify(events));
} else {
- // Add events for non-tag inputs
+ // Add events for non-tag inputs (template var input events are handled in createTemplateVarToggle)
for (let event in events) formElement.addEventListener(event, events[event]);
}
- if (templateVarInput && !isTagInput) {
- for (let event in events) templateVarInput.addEventListener(event, events[event]);
- }
-
// add template variables
if (entry?.variables) {
const variables = window['__FIELD_TEMPLATE_VARIABLES__']?.[entry?.name] || new Map();
@@ -686,60 +660,17 @@ export default function createFormField(entry, displayType = 'block', entryIndex
}
});
- if (labelElement && templateVarInput) {
- templateVarToggle = document.createElement('input');
- templateVarToggle.type = 'checkbox';
- templateVarToggle.className = 'sr-only peer';
- templateVarToggle.title = 'Use template variable';
- templateVarToggle.setAttribute('aria-label', 'Use template variable');
- templateVarToggle.id = `template-toggle-${entry.name}`;
-
- const toggleLabel = document.createElement('label');
- toggleLabel.className =
- 'text-xs font-semibold text-gray-700 cursor-pointer select-none hover:text-gray-900 transition-colors';
- toggleLabel.textContent = 'Use Template Vars';
- toggleLabel.htmlFor = `template-toggle-${entry.name}`;
-
- const toggleSwitch = document.createElement('div');
- toggleSwitch.className =
- 'relative w-11 h-6 bg-gray-300 rounded-full cursor-pointer transition-all duration-300 shadow-inner hover:shadow-md';
- toggleSwitch.setAttribute('role', 'presentation');
-
- const toggleThumb = document.createElement('div');
- toggleThumb.className =
- 'absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow-md transition-all duration-300 transform';
- toggleSwitch.appendChild(toggleThumb);
-
- const toggleWrapper = document.createElement('div');
- toggleWrapper.className = 'flex items-center gap-2.5';
- toggleWrapper.appendChild(toggleLabel);
- toggleWrapper.appendChild(templateVarToggle);
- toggleWrapper.appendChild(toggleSwitch);
-
- // Update toggle switch appearance when checkbox changes
- templateVarToggle.addEventListener('change', () => {
- if (templateVarToggle.checked) {
- toggleSwitch.classList.remove('bg-gray-300');
- toggleSwitch.classList.add('bg-blue-500');
- toggleThumb.classList.add('translate-x-5');
- toggleThumb.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.2)';
- } else {
- toggleSwitch.classList.add('bg-gray-300');
- toggleSwitch.classList.remove('bg-blue-500');
- toggleThumb.classList.remove('translate-x-5');
- toggleThumb.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.1)';
- }
- });
-
- // Make the switch clickable
- toggleSwitch.addEventListener('click', () => {
- templateVarToggle.click();
- });
+ // Create template variable toggle if needed
+ if (hasTemplateVarToggle && labelElement) {
+ const toggleResult = createTemplateVarToggle(entry, value, formElement, events);
+ templateVarInput = toggleResult.templateVarInput;
+ templateVarToggle = toggleResult.templateVarToggle;
+ templateVarModeDefault = toggleResult.templateVarModeDefault;
labelWrapper = document.createElement('div');
labelWrapper.className = 'flex items-center justify-between gap-2 mb-0.5';
labelWrapper.appendChild(labelElement);
- labelWrapper.appendChild(toggleWrapper);
+ labelWrapper.appendChild(toggleResult.toggleWrapper);
}
const labelContainer = labelWrapper || labelElement;
@@ -889,71 +820,6 @@ export default function createFormField(entry, displayType = 'block', entryIndex
formElement.dispatchEvent(new Event('created'));
- if (templateVarInput && templateVarToggle) {
- const templateVarOnlyPattern = /^\s*{{[^{}]+}}\s*(?:[,\s]+{{[^{}]+}}\s*)*$/;
- const setSelectVisibility = (useTemplateInput: boolean) => {
- const selectWrapper =
- formElement.closest('label.select') || formElement.closest('.select') || formElement;
- if (selectWrapper instanceof HTMLElement) {
- selectWrapper.style.display = useTemplateInput ? 'none' : '';
- }
- const inputWrapper = (templateVarInput as HTMLInputElement & { wrapper?: HTMLElement })
- .wrapper;
- if (inputWrapper) {
- inputWrapper.style.display = useTemplateInput ? '' : 'none';
- } else {
- templateVarInput.style.display = useTemplateInput ? '' : 'none';
- }
-
- if (useTemplateInput) {
- if (!templateVarInput.value) {
- templateVarInput.value = templateVarModeDefault ? String(value ?? '') : '';
- }
- const trimmedValue = templateVarInput.value.trim();
- const isValid = trimmedValue.length === 0 || templateVarOnlyPattern.test(trimmedValue);
- templateVarInput.classList.toggle('invalid', !isValid);
- templateVarInput.setAttribute('name', entry.name);
- templateVarInput.setAttribute('id', entry.name);
- formElement.removeAttribute('name');
- formElement.removeAttribute('id');
- } else {
- templateVarInput.classList.remove('invalid');
- formElement.setAttribute('name', entry.name);
- formElement.setAttribute('id', entry.name);
- templateVarInput.removeAttribute('name');
- templateVarInput.removeAttribute('id');
-
- const selectElement = formElement as HTMLSelectElement;
- const nextValue =
- selectElement.options &&
- [...selectElement.options].some((opt) => opt.value === lastSelectValue)
- ? lastSelectValue
- : selectElement.value;
- selectElement.value = nextValue;
- }
- };
-
- formElement.addEventListener('change', () => {
- lastSelectValue = (formElement as HTMLSelectElement).value;
- });
-
- templateVarToggle.checked = templateVarModeDefault;
- templateVarToggle.disabled = entry.readonly;
-
- templateVarToggle.addEventListener('change', () => {
- setSelectVisibility(templateVarToggle.checked);
- });
-
- templateVarInput.addEventListener('input', () => {
- if (!templateVarToggle?.checked) return;
- const trimmedValue = templateVarInput.value.trim();
- const isValid = trimmedValue.length === 0 || templateVarOnlyPattern.test(trimmedValue);
- templateVarInput.classList.toggle('invalid', !isValid);
- });
-
- setTimeout(() => setSelectVisibility(templateVarModeDefault), 0);
- }
-
// Handle tag input events after MetroUI initialization
if (isTagInput && Object.keys(events).length > 0) {
delay(100).then(() => {
@@ -971,6 +837,246 @@ export default function createFormField(entry, displayType = 'block', entryIndex
return div;
}
+/**
+ * Creates template variable toggle UI and logic for select fields
+ * Uses native HTML input (no Metro UI) for better control and performance
+ * @param entry - The form field entry configuration
+ * @param value - The current value of the field
+ * @param formElement - The main form element (select)
+ * @param events - Event handlers to attach to template input
+ * @returns Object containing template input, toggle elements, and default state
+ */
+function createTemplateVarToggle(
+ entry: any,
+ value: any,
+ formElement: HTMLElement,
+ events: Record<string, Function>,
+) {
+ // Create native HTML input (no Metro UI) for template variables
+ const templateVarInput = document.createElement('input');
+ templateVarInput.type = 'text';
+ templateVarInput.value = value || '';
+ templateVarInput.placeholder = 'Click to select a template variable';
+ templateVarInput.autocomplete = 'off';
+ templateVarInput.setAttribute('data-template-vars', 'true');
+ templateVarInput.classList.add('template-var-input');
+ templateVarInput.style.paddingRight = '36px';
+ templateVarInput.style.backgroundColor = '#ffffff';
+ templateVarInput.style.cursor = 'pointer';
+ templateVarInput.style.opacity = '1';
+
+ // Copy template-related attributes from entry for variable filtering
+ const attributes = entry.attributes || {};
+ if (attributes['data-template-excluded-vars']) {
+ templateVarInput.setAttribute(
+ 'data-template-excluded-vars',
+ attributes['data-template-excluded-vars'],
+ );
+ }
+ if (attributes['data-template-excluded-var-types']) {
+ templateVarInput.setAttribute(
+ 'data-template-excluded-var-types',
+ attributes['data-template-excluded-var-types'],
+ );
+ }
+
+ // Prevent keyboard input - users should only insert template variables via buttons
+ templateVarInput.addEventListener('keydown', (e) => {
+ const allowedKeys = [
+ 'ArrowLeft',
+ 'ArrowRight',
+ 'ArrowUp',
+ 'ArrowDown',
+ 'Home',
+ 'End',
+ 'Tab',
+ 'Backspace',
+ 'Delete',
+ ];
+ const isCtrlCmd = e.ctrlKey || e.metaKey;
+ const isSelectionKey =
+ isCtrlCmd && (e.key === 'a' || e.key === 'A' || e.key === 'c' || e.key === 'C');
+
+ if (!allowedKeys.includes(e.key) && !isSelectionKey) {
+ e.preventDefault();
+ }
+ });
+
+ templateVarInput.addEventListener('paste', (e) => {
+ e.preventDefault();
+ });
+
+ // Attach events to template input
+ for (let event in events) {
+ templateVarInput.addEventListener(event, events[event] as EventListener);
+ }
+
+ // Get saved toggle state from component data
+ const currentComponent = (window as any).Component?.curComponentSettings;
+ const savedToggleState = currentComponent?.data?.templateVarToggleStates?.[entry.name];
+ const templateVarModeDefault =
+ savedToggleState !== undefined
+ ? savedToggleState
+ : typeof value === 'string' && /{{.*?}}/.test(value);
+
+ // Create toggle checkbox
+ const templateVarToggle = document.createElement('input');
+ templateVarToggle.type = 'checkbox';
+ templateVarToggle.className = 'sr-only peer';
+ templateVarToggle.title = 'Use template variable';
+ templateVarToggle.setAttribute('aria-label', 'Use template variable');
+ templateVarToggle.id = `template-toggle-${entry.name}`;
+ templateVarToggle.checked = templateVarModeDefault;
+ templateVarToggle.disabled = entry.readonly;
+
+ // Create toggle UI elements
+ const toggleLabel = document.createElement('label');
+ toggleLabel.className =
+ 'text-xs font-medium text-gray-600 cursor-pointer select-none hover:text-gray-800 transition-colors';
+ toggleLabel.textContent = 'Use Template Vars';
+ toggleLabel.htmlFor = `template-toggle-${entry.name}`;
+
+ const toggleSwitch = document.createElement('div');
+ toggleSwitch.className =
+ 'relative w-8 h-4 bg-gray-300 rounded-full cursor-pointer transition-all duration-300 shadow-inner hover:shadow-md';
+ toggleSwitch.setAttribute('role', 'presentation');
+
+ const toggleThumb = document.createElement('div');
+ toggleThumb.className =
+ 'absolute top-0.5 left-0.5 w-3 h-3 bg-white rounded-full shadow-sm transition-all duration-300 transform';
+ toggleSwitch.appendChild(toggleThumb);
+
+ const toggleWrapper = document.createElement('div');
+ toggleWrapper.className = 'flex items-center gap-2';
+ toggleWrapper.appendChild(toggleLabel);
+ toggleWrapper.appendChild(templateVarToggle);
+ toggleWrapper.appendChild(toggleSwitch);
+
+ // Initialize toggle appearance
+ if (templateVarModeDefault) {
+ toggleSwitch.classList.remove('bg-gray-300');
+ toggleSwitch.classList.add('bg-blue-500');
+ toggleThumb.classList.add('translate-x-4');
+ toggleThumb.style.boxShadow = '0 1px 2px rgba(0, 0, 0, 0.2)';
+ }
+
+ // Update toggle switch appearance on change
+ templateVarToggle.addEventListener('change', () => {
+ if (templateVarToggle.checked) {
+ toggleSwitch.classList.remove('bg-gray-300');
+ toggleSwitch.classList.add('bg-blue-500');
+ toggleThumb.classList.add('translate-x-4');
+ toggleThumb.style.boxShadow = '0 1px 2px rgba(0, 0, 0, 0.2)';
+ } else {
+ toggleSwitch.classList.add('bg-gray-300');
+ toggleSwitch.classList.remove('bg-blue-500');
+ toggleThumb.classList.remove('translate-x-4');
+ toggleThumb.style.boxShadow = '0 1px 2px rgba(0, 0, 0, 0.1)';
+ }
+
+ // Update hidden form field for persistence
+ const form = templateVarToggle.closest('form');
+ const hiddenField = form?.querySelector(
+ 'input[name="templateVarToggleStates"]',
+ ) as HTMLInputElement;
+
+ if (hiddenField) {
+ try {
+ const currentStates = hiddenField.value ? JSON.parse(hiddenField.value) : {};
+ currentStates[entry.name] = templateVarToggle.checked;
+ hiddenField.value = JSON.stringify(currentStates);
+ } catch (e) {
+ console.error('[Template Vars] Failed to update hidden field:', e);
+ }
+ }
+ });
+
+ // Make the switch clickable
+ toggleSwitch.addEventListener('click', () => {
+ templateVarToggle.click();
+ });
+
+ // Create visibility toggle logic
+ let lastSelectValue = value;
+ const templateVarOnlyPattern = /^\s*{{[^{}]+}}\s*$/;
+
+ const setSelectVisibility = (useTemplateInput: boolean) => {
+ const selectWrapper =
+ formElement.closest('label.select') || formElement.closest('.select') || formElement;
+ if (selectWrapper instanceof HTMLElement) {
+ selectWrapper.style.display = useTemplateInput ? 'none' : '';
+ }
+ const inputWrapper = (templateVarInput as HTMLInputElement & { wrapper?: HTMLElement }).wrapper;
+ if (inputWrapper) {
+ inputWrapper.style.display = useTemplateInput ? '' : 'none';
+ } else {
+ templateVarInput.style.display = useTemplateInput ? '' : 'none';
+ }
+
+ if (useTemplateInput) {
+ const currentValue = templateVarInput.value.trim();
+ const isCurrentValueValid =
+ currentValue.length === 0 || templateVarOnlyPattern.test(currentValue);
+
+ if (!isCurrentValueValid && !templateVarModeDefault) {
+ templateVarInput.value = '';
+ } else if (!templateVarInput.value && templateVarModeDefault) {
+ templateVarInput.value = String(value ?? '');
+ }
+
+ const trimmedValue = templateVarInput.value.trim();
+ const isValid = trimmedValue.length === 0 || templateVarOnlyPattern.test(trimmedValue);
+ templateVarInput.classList.toggle('invalid', !isValid);
+ templateVarInput.setAttribute('name', entry.name);
+ templateVarInput.setAttribute('id', entry.name);
+ formElement.removeAttribute('name');
+ formElement.removeAttribute('id');
+ } else {
+ templateVarInput.classList.remove('invalid');
+ formElement.setAttribute('name', entry.name);
+ formElement.setAttribute('id', entry.name);
+ templateVarInput.removeAttribute('name');
+ templateVarInput.removeAttribute('id');
+
+ const selectElement = formElement as HTMLSelectElement;
+ const nextValue =
+ selectElement.options &&
+ [...selectElement.options].some((opt) => opt.value === lastSelectValue)
+ ? lastSelectValue
+ : selectElement.value;
+ selectElement.value = nextValue;
+ }
+ };
+
+ // Track select changes
+ formElement.addEventListener('change', () => {
+ lastSelectValue = (formElement as HTMLSelectElement).value;
+ });
+
+ // Set up toggle change handler
+ templateVarToggle.addEventListener('change', () => {
+ setSelectVisibility(templateVarToggle.checked);
+ });
+
+ // Set up input validation
+ templateVarInput.addEventListener('input', () => {
+ if (!templateVarToggle?.checked) return;
+ const trimmedValue = templateVarInput.value.trim();
+ const isValid = trimmedValue.length === 0 || templateVarOnlyPattern.test(trimmedValue);
+ templateVarInput.classList.toggle('invalid', !isValid);
+ });
+
+ // Initialize visibility
+ setTimeout(() => setSelectVisibility(templateVarModeDefault), 0);
+
+ return {
+ templateVarInput,
+ templateVarToggle,
+ toggleWrapper,
+ templateVarModeDefault,
+ };
+}
+
/**
* Setup events for tag inputs using MetroUI's event system
*/
diff --git a/packages/app/src/builder-ui/ui/form/form.ts b/packages/app/src/builder-ui/ui/form/form.ts
index 07be02d3..abdb4030 100644
--- a/packages/app/src/builder-ui/ui/form/form.ts
+++ b/packages/app/src/builder-ui/ui/form/form.ts
@@ -95,6 +95,23 @@ export function createForm(entriesObject, displayType = 'block'): FormHTMLElemen
if (Object.values(entriesObject).find((e: any) => e.validate))
form.setAttribute('data-role', 'validator');
+ // Auto-inject templateVarToggleStates hidden field if any field has data-template-vars
+ const hasTemplateVarsField = Object.values(entriesObject).some(
+ (entry: any) => entry?.attributes?.['data-template-vars'] === 'true',
+ );
+
+ if (hasTemplateVarsField && !entriesObject['templateVarToggleStates']) {
+ // Get current component's templateVarToggleStates from window
+ const currentComponent = (window as any).Component?.curComponentSettings;
+ const templateVarToggleStates = currentComponent?.data?.templateVarToggleStates || {};
+
+ // Auto-inject the hidden field by directly mutating the object
+ entriesObject['templateVarToggleStates'] = {
+ type: 'hidden',
+ value: templateVarToggleStates,
+ };
+ }
+
const sections = {};
const sectionsHelp = {};
sections['main'] = [];
@@ -308,6 +325,16 @@ export function readFormValues(form, entriesObject) {
case 'span':
case 'p':
break;
+ case 'hidden':
+ // Deserialize JSON strings back to objects, fallback to raw string value
+ try {
+ const deserialized = JSON.parse(inputField.value);
+ result[key] = deserialized;
+ } catch (e) {
+ // Not valid JSON - use raw string value
+ result[key] = inputField.value;
+ }
+ break;
default:
result[key] = inputField.value;
}
diff --git a/packages/app/src/builder-ui/ui/form/misc.ts b/packages/app/src/builder-ui/ui/form/misc.ts
index 058ca97a..6e46ff2e 100644
--- a/packages/app/src/builder-ui/ui/form/misc.ts
+++ b/packages/app/src/builder-ui/ui/form/misc.ts
@@ -293,31 +293,47 @@ export function handleTemplateVars(targetElm, component = null) {
editor?.focus();
} else {
- // Get the start and end positions of the cursor.
- const startPosition = focusedField.selectionStart;
- const endPosition = focusedField.selectionEnd;
-
- // Insert the text into the textarea.
const value = buttonElm.getAttribute('data-var');
- focusedField.value = `${focusedField.value.substring(
- 0,
- startPosition,
- )}${value}${focusedField.value.substring(endPosition)}`;
-
- // Focus on the textarea again.
- focusedField.focus();
-
- dispatchInputEvent(focusedField);
-
- // Set the cursor position to the end of the text.
- const cursorPosition = startPosition + value?.length || 0;
- focusedField.setSelectionRange(cursorPosition, cursorPosition);
+ // Check if this is a template-var-input for a select field
+ // These inputs should only contain a single template variable
+ const isTemplateVarInput = focusedField.classList.contains('template-var-input');
+
+ if (isTemplateVarInput) {
+ // For select template var inputs: replace entire value with single template variable
+ focusedField.value = value;
+ focusedField.focus();
+ dispatchInputEvent(focusedField);
+
+ // Set cursor to end of the inserted variable
+ const cursorPosition = value?.length || 0;
+ focusedField.setSelectionRange(cursorPosition, cursorPosition);
+ } else {
+ // For regular textareas: insert at cursor position (existing behavior)
+ const startPosition = focusedField.selectionStart;
+ const endPosition = focusedField.selectionEnd;
+
+ focusedField.value = `${focusedField.value.substring(
+ 0,
+ startPosition,
+ )}${value}${focusedField.value.substring(endPosition)}`;
+
+ // Focus on the textarea again.
+ focusedField.focus();
+
+ dispatchInputEvent(focusedField);
+
+ // Set the cursor position to the end of the text.
+ const cursorPosition = startPosition + value?.length || 0;
+ focusedField.setSelectionRange(cursorPosition, cursorPosition);
+ }
}
}
// Remove the template variable buttons container
- const wrapper = document.querySelector(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}.tvb-${compUid}`);
+ const wrapper = document.querySelector(
+ `.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}.tvb-${compUid}`,
+ );
const parent = wrapper?.parentElement as HTMLElement;
wrapper?.remove();
resizeAceEditor(parent);
@@ -453,7 +469,9 @@ export function handleTemplateVars(targetElm, component = null) {
resizeAceEditor(focusedElmParent as HTMLElement);
} else {
// * Remove template variable buttons
- const wrapper = document.querySelector(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}.tvb-${compUid}`);
+ const wrapper = document.querySelector(
+ `.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}.tvb-${compUid}`,
+ );
const parent = wrapper?.parentElement as HTMLElement;
wrapper?.remove();
resizeAceEditor(parent);
@@ -490,7 +508,10 @@ export const setTabIndex = (selector: string): void => {
* Finds and returns the bracket match range for a given cursor position
* Only matches if cursor is ON or INSIDE the brackets, not before/after them
*/
-function findBracketMatch(text: string, cursorPosition: number): { start: number; end: number } | null {
+function findBracketMatch(
+ text: string,
+ cursorPosition: number,
+): { start: number; end: number } | null {
const regex = /{{.*?}}/g;
let match;
@@ -522,7 +543,8 @@ function _bracketSelectionEvent(e: any) {
// Handle Ace editor clicks
const editorContainer = aceContentElement.closest('.ace-editor');
const textarea = editorContainer?.previousElementSibling as any;
- const editor = textarea?._editor ||
+ const editor =
+ textarea?._editor ||
(aceContentElement.closest('.form-group')?.querySelector('.json-editor') as any)?._editor;
if (editor) {
@@ -542,7 +564,9 @@ function _bracketSelectionEvent(e: any) {
} else if (inputElement?.classList?.contains('fake-textarea')) {
// Handle Metro UI fake textarea clicks
const textareaWrapper = inputElement.closest('.textarea');
- const realTextarea = textareaWrapper?.querySelector('textarea:not(.fake-textarea)') as HTMLTextAreaElement;
+ const realTextarea = textareaWrapper?.querySelector(
+ 'textarea:not(.fake-textarea)',
+ ) as HTMLTextAreaElement;
if (realTextarea) {
realTextarea.focus();