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.

improve the template variable so it can be reused across multiple fields and support datalist type inputs

Forhad Hosaina2041a5cf063
diff --git a/packages/app/src/builder-ui/components/GenAILLM.class.ts b/packages/app/src/builder-ui/components/GenAILLM.class.ts
index 0a5c2a8b..ee528b71 100644
--- a/packages/app/src/builder-ui/components/GenAILLM.class.ts
+++ b/packages/app/src/builder-ui/components/GenAILLM.class.ts
@@ -970,7 +970,11 @@ export class GenAILLM extends Component {
type: 'text',
label: 'City',
value: '',
- attributes: openAIAttributes,
+ attributes: {
+ ...openAIAttributes,
+ 'data-template-vars': '{"enabled": true, "singleOnly": true}',
+ 'data-template-excluded-vars': 'Attachment',
+ },
class: 'hidden',
help: "The city: free text strings, like 'Minneapolis'.",
validate: 'maxlength=100',
@@ -986,7 +990,8 @@ export class GenAILLM extends Component {
attributes: {
...openAIAttributes,
placeholder: 'Type country name or code (e.g., United States or US)',
- autocomplete: 'off',
+ 'data-template-vars': '{"enabled": true, "singleOnly": true}',
+ 'data-template-excluded-vars': 'Attachment',
},
class: 'hidden',
help: "Country: type the full country name or two-letter ISO code, like 'United States' or 'US'. Select from the dropdown to confirm.",
@@ -997,7 +1002,11 @@ export class GenAILLM extends Component {
type: 'text',
label: 'Region',
value: '',
- attributes: openAIAttributes,
+ attributes: {
+ ...openAIAttributes,
+ 'data-template-vars': '{"enabled": true, "singleOnly": true}',
+ 'data-template-excluded-vars': 'Attachment',
+ },
class: 'hidden',
help: "Region: free text strings, like 'Minnesota'.",
validate: 'maxlength=100',
@@ -1013,7 +1022,8 @@ export class GenAILLM extends Component {
attributes: {
...openAIAttributes,
placeholder: 'Type to search timezones (e.g., America/Chicago)',
- autocomplete: 'off',
+ 'data-template-vars': '{"enabled": true, "singleOnly": true}',
+ 'data-template-excluded-vars': 'Attachment',
},
class: 'hidden',
help: 'Timezone: an IANA timezone like America/Chicago. Type to search.',
@@ -1174,7 +1184,8 @@ export class GenAILLM extends Component {
attributes: {
...xAIAttributes,
placeholder: 'Type country name or code (e.g., United States or US)',
- autocomplete: 'off',
+ 'data-template-vars': '{"enabled": true, "singleOnly": true}',
+ 'data-template-excluded-vars': 'Attachment',
},
class: 'hidden',
help: 'Country: type the full country name or two-letter ISO code to limit search results. Select from the dropdown to confirm.',
diff --git a/packages/app/src/builder-ui/ui/form/createFormField.ts b/packages/app/src/builder-ui/ui/form/createFormField.ts
index 5780ce04..efccf440 100644
--- a/packages/app/src/builder-ui/ui/form/createFormField.ts
+++ b/packages/app/src/builder-ui/ui/form/createFormField.ts
@@ -5,6 +5,7 @@ import {
handleVaultBtn,
isValidJson,
} from '../../utils';
+import { isTemplateVarsEnabled } from '../../utils/form.utils';
import {
attachTooltipV2,
mapMetroClassesToTooltipV2,
@@ -475,6 +476,19 @@ export default function createFormField(entry, displayType = 'block', entryIndex
formElement.setAttribute(attr, attributes[attr]);
}
+
+ // Automatically set autocomplete="off" for fields that support variable insertion
+ // data-template-vars can be "true" or an object like '{"enabled": true, "singleOnly": true}'
+ const hasTemplateVars = isTemplateVarsEnabled(attributes['data-template-vars']);
+
+ if (
+ (hasTemplateVars ||
+ attributes['data-agent-vars'] === 'true' ||
+ attributes['data-trigger-vars'] === 'true') &&
+ !attributes['autocomplete']
+ ) {
+ formElement.setAttribute('autocomplete', 'off');
+ }
}
}
diff --git a/packages/app/src/builder-ui/ui/form/misc.ts b/packages/app/src/builder-ui/ui/form/misc.ts
index a1532b44..73267df1 100644
--- a/packages/app/src/builder-ui/ui/form/misc.ts
+++ b/packages/app/src/builder-ui/ui/form/misc.ts
@@ -1,4 +1,4 @@
-import { dispatchInputEvent } from '../../utils/form.utils';
+import { dispatchInputEvent, isTemplateVarsEnabled } from '../../utils/form.utils';
type Action = {
id: string;
label: string;
@@ -127,6 +127,7 @@ export function createTemplateVarBtn(
type: string,
): HTMLButtonElement {
const button = document.createElement('button');
+ button.type = 'button'; // Explicitly set type to prevent form submission
button.classList.add('button', 'primary', 'small', 'template-var-button');
let cls = '';
@@ -141,7 +142,10 @@ export function createTemplateVarBtn(
button.className = `button primary small template-var-button${cls}`;
button.setAttribute('data-var', value);
- button.innerHTML = label;
+ button.textContent = label; // Use textContent instead of innerHTML for better event handling
+
+ // Mark button so we can identify it in event handlers
+ button.setAttribute('data-is-var-button', 'true');
return button;
}
@@ -231,15 +235,21 @@ function resizeAceEditor(parent: HTMLElement | null) {
if (!parent) return;
const editorEl =
parent.querySelector('.json-editor') ||
- parent.querySelector('textarea[data-template-vars=true]') ||
+ parent.querySelector('textarea[data-template-vars]') ||
parent.querySelector('textarea[data-agent-vars=true]') ||
parent.querySelector('textarea[data-trigger-vars=true]');
const editor = (editorEl as any)?._editor;
editor?.resize();
}
-// TODO: REFACTOR THIS FUNCTION
-export function handleTemplateVars(targetElm, component = null) {
+/**
+ * @deprecated This is the ORIGINAL implementation kept for safety during migration.
+ * Use handleTemplateVars() instead (the refactored version above).
+ * This will be removed after confirming no regressions with the new implementation.
+ *
+ * ORIGINAL handleTemplateVars implementation
+ */
+export function handleTemplateVars_ORIGINAL(targetElm, component = null) {
targetElm.onclick = (e) => {
try {
const clickedElm = e.target as HTMLInputElement;
@@ -317,7 +327,9 @@ export function handleTemplateVars(targetElm, component = null) {
}
// 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 +465,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 +504,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 +539,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 +560,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();
@@ -572,3 +592,489 @@ export function addBracketSelection(element: HTMLElement) {
element.addEventListener('click', _bracketSelectionEvent);
element.setAttribute('data-bracket-selection', 'true');
}
+
+/**
+ * Find variable button in event path
+ * Checks both the clicked element and its parents for a variable button
+ */
+function findVariableButtonInEvent(e: Event): HTMLElement | null {
+ const eventPath = e.composedPath ? e.composedPath() : [];
+
+ // Search the event path for a var button using data-is-var-button marker
+ for (const el of eventPath) {
+ if ((el as HTMLElement).getAttribute?.('data-is-var-button') === 'true') {
+ return el as HTMLElement;
+ }
+ }
+
+ // Fallback to closest check
+ const actualTarget = e.target as HTMLElement;
+ if (actualTarget.classList?.contains('template-var-button')) {
+ return actualTarget;
+ }
+
+ return actualTarget.closest?.('.template-var-button') as HTMLElement | null;
+}
+
+/**
+ * Check if processing should be skipped due to existing variables showing
+ * Returns true if variables are already displayed and we should skip processing
+ */
+function shouldSkipDueToExistingVars(clickedElm: HTMLElement): boolean {
+ // Check if focus event just showed variables (within 150ms)
+ if ((clickedElm as any).__varsJustShown) {
+ return true;
+ }
+
+ // Check if this element's form-group already has variables showing
+ const formGroup = clickedElm.closest('.form-group');
+ const hasExistingVars = formGroup?.querySelector(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}`);
+ const datalistInGroup = formGroup?.querySelector(
+ 'input[list][data-template-vars]',
+ ) as HTMLInputElement;
+
+ if (!hasExistingVars) {
+ return false;
+ }
+
+ // Check if this is a field that should show variables
+ const isDatalistField = clickedElm.getAttribute('list');
+ const isVarField =
+ isTemplateVarsEnabled(clickedElm.getAttribute('data-template-vars')) ||
+ clickedElm.getAttribute('data-agent-vars') === 'true' ||
+ clickedElm.getAttribute('data-trigger-vars') === 'true' ||
+ isDatalistField ||
+ !!datalistInGroup ||
+ clickedElm.closest?.('[data-template-vars]') ||
+ clickedElm.closest?.('[data-agent-vars="true"]') ||
+ clickedElm.closest?.('[data-trigger-vars="true"]');
+
+ return !!isVarField;
+}
+
+/**
+ * Find the target field for variable insertion within a form group
+ */
+function findTargetFieldForInsertion(
+ buttonElm: HTMLElement,
+): HTMLInputElement | HTMLTextAreaElement | null {
+ const storedField = window['__LAST_FIELD_ELEMENT_WITH_TEMPLATE_VARS__'] as
+ | HTMLInputElement
+ | HTMLTextAreaElement;
+ const formGroup = buttonElm.closest('.form-group');
+
+ // Check if the stored field is within this form group
+ const focusedField =
+ (formGroup?.contains(storedField) ? storedField : null) ||
+ (formGroup?.querySelector('.json-editor') as HTMLTextAreaElement) ||
+ (formGroup?.querySelector('textarea[data-template-vars]') as HTMLTextAreaElement) ||
+ (formGroup?.querySelector('textarea[data-agent-vars=true]') as HTMLTextAreaElement) ||
+ (formGroup?.querySelector('input[data-template-vars]') as HTMLInputElement) ||
+ (formGroup?.querySelector('input[data-agent-vars=true]') as HTMLInputElement) ||
+ (formGroup?.querySelector('textarea[data-trigger-vars=true]') as HTMLTextAreaElement) ||
+ (formGroup?.querySelector('input[data-trigger-vars=true]') as HTMLInputElement) ||
+ (formGroup?.querySelector('textarea') as HTMLTextAreaElement);
+
+ return focusedField;
+}
+
+/**
+ * Insert variable into a field (handles both ACE editors and regular inputs)
+ */
+function insertVariableIntoField(
+ focusedField: HTMLInputElement | HTMLTextAreaElement,
+ variableValue: string,
+): void {
+ // Check if it is an ACE editor
+ const editor = (focusedField as any)?._editor;
+
+ if (editor) {
+ // Insert text at current cursor position in ACE editor
+ editor.session.replace(editor?.selection?.getRange(), variableValue);
+ editor?.moveCursorToPosition(editor?.getCursorPosition());
+ editor?.focus();
+ } else {
+ // Regular input/textarea handling
+ const currentValue = focusedField.value;
+
+ // Check if this field only allows a single variable
+ let isSingleVarOnly = false;
+ const templateVarsAttr = focusedField.getAttribute('data-template-vars');
+
+ if (templateVarsAttr && templateVarsAttr !== 'true') {
+ try {
+ const config = JSON.parse(templateVarsAttr);
+ isSingleVarOnly = config.singleOnly === true;
+ } catch (e) {
+ // If parsing fails, treat as regular field
+ }
+ }
+
+ const hasExistingVariable = /\{\{[^}]+\}\}/.test(currentValue);
+
+ if (isSingleVarOnly && hasExistingVariable) {
+ // Replace the entire value with the new variable for single-var-only fields
+ focusedField.value = variableValue;
+ focusedField.focus();
+ dispatchInputEvent(focusedField);
+ focusedField.setSelectionRange(variableValue.length, variableValue.length);
+ } else {
+ // Insert at cursor position
+ const startPosition = focusedField.selectionStart;
+ const endPosition = focusedField.selectionEnd;
+
+ focusedField.value = `${focusedField.value.substring(
+ 0,
+ startPosition,
+ )}${variableValue}${focusedField.value.substring(endPosition)}`;
+
+ focusedField.focus();
+ dispatchInputEvent(focusedField);
+
+ const cursorPosition = startPosition + variableValue.length;
+ focusedField.setSelectionRange(cursorPosition, cursorPosition);
+ }
+ }
+}
+
+/**
+ * Handle variable button click - insert variable into associated field
+ */
+function handleVariableButtonClick(
+ varButton: HTMLElement,
+ targetElm: HTMLElement,
+ compUid: string,
+ e: Event,
+): void {
+ e.stopPropagation();
+ e.preventDefault();
+
+ // Find the button element in the current scope (handles modal vs inline forms)
+ const buttonElm = targetElm.querySelector(
+ `.template-var-button[data-var="${varButton.getAttribute('data-var')}"]`,
+ ) as HTMLElement;
+
+ if (!buttonElm) {
+ return;
+ }
+
+ // Find the target field for insertion
+ const focusedField = findTargetFieldForInsertion(buttonElm);
+
+ // Insert variable if field is valid and not readonly
+ if (focusedField && !focusedField.hasAttribute('readonly')) {
+ const variableValue = buttonElm.getAttribute('data-var');
+ insertVariableIntoField(focusedField, variableValue);
+ }
+
+ // Remove the template variable buttons container after insertion
+ const wrapper = document.querySelector(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}.tvb-${compUid}`);
+ const parent = wrapper?.parentElement as HTMLElement;
+ wrapper?.remove();
+ resizeAceEditor(parent);
+}
+
+/**
+ * Remove all existing variable button wrappers
+ * Ensures only one field shows variables at a time
+ */
+function removeAllVariableWrappers(): void {
+ document.querySelectorAll(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}`).forEach((wrapper) => {
+ const parent = wrapper?.parentElement as HTMLElement;
+ wrapper?.remove();
+ resizeAceEditor(parent);
+ });
+}
+
+/**
+ * Main handler for template variables functionality (REFACTORED VERSION)
+ * Manages showing/hiding variable buttons and inserting variables into fields
+ *
+ * This is the new implementation with improved structure and using shared utilities.
+ * The original version is kept as handleTemplateVars_ORIGINAL for safety.
+ */
+export function handleTemplateVars(targetElm, component = null) {
+ const handleTemplateVarsEvent = (e) => {
+ try {
+ const clickedElm = e.target as HTMLInputElement;
+ const compUid =
+ component?._uid || document.querySelector('.component.active')?.getAttribute('id') || '';
+
+ // CRITICAL: Check for variable button clicks FIRST
+ const varButton = findVariableButtonInEvent(e);
+
+ if (varButton && varButton.hasAttribute('data-var')) {
+ handleVariableButtonClick(varButton, targetElm, compUid, e);
+ return;
+ }
+
+ // Not a button click - apply early guards
+ if (shouldSkipDueToExistingVars(clickedElm)) {
+ return;
+ }
+
+ // Handle template-vars fields
+ if (
+ (isTemplateVarsEnabled(clickedElm.getAttribute('data-template-vars')) ||
+ (clickedElm as HTMLElement)?.closest?.('[data-template-vars]')) &&
+ !(clickedElm as HTMLElement)?.closest?.('[readonly]')
+ ) {
+ // * Display template variable buttons only if the field is not readonly
+
+ // Check if variables are already showing for this exact field
+ // This prevents double-processing when focus and click events both fire (e.g., datalist fields)
+ const formGroup = (clickedElm as HTMLElement).closest('.form-group');
+ const existingWrapper = formGroup?.querySelector(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}`);
+
+ if (existingWrapper) {
+ // Variables already showing for this field, skip processing
+ return;
+ }
+
+ // IMPORTANT: Remove ALL existing variable button wrappers before showing new ones
+ // This ensures only one field shows variables at a time
+ removeAllVariableWrappers();
+
+ const inputVariables = window['__INPUT_TEMPLATE_VARIABLES__']?.[compUid] || new Map();
+
+ // For ACE editors, find the actual textarea element to get the field name
+ let fieldName = clickedElm?.name;
+ let targetField: HTMLInputElement | HTMLTextAreaElement = clickedElm as HTMLInputElement;
+ if (!fieldName) {
+ const formGroup = (clickedElm as HTMLElement).closest('.form-group');
+ const textarea = formGroup?.querySelector(
+ 'textarea[data-template-vars]',
+ ) as HTMLTextAreaElement;
+ const input = formGroup?.querySelector('input[data-template-vars]') as HTMLInputElement;
+ targetField = textarea || input || (clickedElm as HTMLInputElement);
+ fieldName = targetField?.name;
+ }
+
+ // Store reference to the specific field element for variable insertion
+ window['__LAST_FIELD_WITH_TEMPLATE_VARS__'] = fieldName;
+ window['__LAST_FIELD_ELEMENT_WITH_TEMPLATE_VARS__'] = targetField;
+
+ let fieldVariables = window['__FIELD_TEMPLATE_VARIABLES__']?.[fieldName] || new Map();
+
+ let globalVariables = window['__GLOBAL_TEMPLATE_VARIABLES__'] || new Map();
+
+ const variables = new Map([
+ ...inputVariables,
+ ...fieldVariables,
+ ...globalVariables,
+ ]) as Map<string, { var: string; type: string }>;
+
+ // #region Exclude variable based on the data-template-excluded-vars = <VAR_NAME1>,<VAR_NAME2> (Input Names)
+ let excludeVars = clickedElm?.getAttribute('data-template-excluded-vars') || '';
+
+ for (const _var of excludeVars.split(',')) {
+ if (variables.has(_var)) {
+ variables.delete(_var);
+ }
+ }
+ // #endregion
+
+ // #region Exclude variable based on the data-template-excluded-var-types = <VAR_TYPE1>,<VAR_TYPE2> (Input Types)
+ const excludeVarTypes = clickedElm?.getAttribute('data-template-excluded-var-types') || '';
+ const excludeVarTypesArr = excludeVarTypes.split(',');
+
+ for (const [key, value] of variables) {
+ if (excludeVarTypesArr.includes(value.type)) {
+ variables.delete(key);
+ }
+ }
+ // #endregion
+
+ const focusedElmParent = clickedElm.closest('.form-group') as HTMLElement;
+ const buttonsContainer = generateTemplateVarBtns(
+ variables,
+ compUid,
+ focusedElmParent,
+ ) as HTMLDivElement;
+
+ if (!buttonsContainer) return;
+
+ focusedElmParent.appendChild(buttonsContainer);
+ resizeAceEditor(focusedElmParent);
+ } else if (
+ (clickedElm.getAttribute('data-agent-vars') === 'true' ||
+ (clickedElm as HTMLElement)?.closest?.('[data-agent-vars="true"]')) &&
+ !(clickedElm as HTMLElement)?.closest?.('[readonly]')
+ ) {
+ // * Display template variable buttons only if the field is not readonly
+
+ // Check if variables are already showing for this exact field
+ const formGroup = (clickedElm as HTMLElement).closest('.form-group');
+ const existingWrapper = formGroup?.querySelector(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}`);
+ if (existingWrapper) {
+ // Variables already showing for this field, skip processing
+ return;
+ }
+
+ // IMPORTANT: Remove ALL existing variable button wrappers before showing new ones
+ // This ensures only one field shows variables at a time
+ removeAllVariableWrappers();
+
+ // For ACE editors, find the actual textarea element to get the field name
+ let fieldName = clickedElm?.name;
+ let targetField: HTMLInputElement | HTMLTextAreaElement = clickedElm as HTMLInputElement;
+ if (!fieldName) {
+ const formGroup = (clickedElm as HTMLElement).closest('.form-group');
+ const textarea = formGroup?.querySelector(
+ 'textarea[data-agent-vars=true]',
+ ) as HTMLTextAreaElement;
+ const input = formGroup?.querySelector('input[data-agent-vars=true]') as HTMLInputElement;
+ targetField = textarea || input || (clickedElm as HTMLInputElement);
+ fieldName = targetField?.name;
+ }
+
+ // Store reference to the specific field element for variable insertion
+ window['__LAST_FIELD_WITH_TEMPLATE_VARS__'] = fieldName;
+ window['__LAST_FIELD_ELEMENT_WITH_TEMPLATE_VARS__'] = targetField;
+
+ let globalVariables = window['__GLOBAL_TEMPLATE_VARIABLES__'] || new Map();
+
+ const variables = new Map([...globalVariables]) as Map<
+ string,
+ { var: string; type: string }
+ >;
+
+ const focusedElmParent = clickedElm.closest('.form-group') as HTMLElement;
+ const buttonsContainer = generateTemplateVarBtns(
+ variables,
+ compUid,
+ focusedElmParent,
+ ) as HTMLDivElement;
+
+ if (!buttonsContainer) return;
+
+ focusedElmParent.appendChild(buttonsContainer);
+ resizeAceEditor(focusedElmParent);
+ } else if (
+ clickedElm.getAttribute('data-trigger-vars') === 'true' &&
+ !clickedElm?.hasAttribute('readonly')
+ ) {
+ // Check if variables are already showing for this exact field
+ const formGroup = (clickedElm as HTMLElement).closest('.form-group');
+ const existingWrapper = formGroup?.querySelector(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}`);
+ if (existingWrapper) {
+ // Variables already showing for this field, skip processing
+ return;
+ }
+
+ // IMPORTANT: Remove ALL existing variable button wrappers before showing new ones
+ // This ensures only one field shows variables at a time
+ removeAllVariableWrappers();
+
+ let dataTriggers = clickedElm.getAttribute('data-triggers');
+ if (!dataTriggers) return;
+
+ const triggersList = Array.isArray(dataTriggers) ? dataTriggers.split(',') : [dataTriggers];
+ const triggersSchema = triggersList.map((triggerId) => {
+ const component = document.getElementById(triggerId);
+ const control = (component as any)?._control;
+ return control?.schema;
+ });
+
+ //generate variables from schema
+ let variables = new Map();
+ for (const schema of triggersSchema) {
+ const triggerVariables = extractTriggerVariables(schema);
+ for (const [key, value] of triggerVariables) {
+ variables.set(key, value);
+ }
+ }
+
+ // Store reference to the specific field element for variable insertion
+ let fieldName = clickedElm?.name;
+ let targetField: HTMLInputElement | HTMLTextAreaElement = clickedElm as HTMLInputElement;
+ if (!fieldName) {
+ const formGroup = (clickedElm as HTMLElement).closest('.form-group');
+ const textarea = formGroup?.querySelector(
+ 'textarea[data-trigger-vars=true]',
+ ) as HTMLTextAreaElement;
+ const input = formGroup?.querySelector(
+ 'input[data-trigger-vars=true]',
+ ) as HTMLInputElement;
+ targetField = textarea || input || (clickedElm as HTMLInputElement);
+ fieldName = targetField?.name;
+ }
+ window['__LAST_FIELD_WITH_TEMPLATE_VARS__'] = fieldName;
+ window['__LAST_FIELD_ELEMENT_WITH_TEMPLATE_VARS__'] = targetField;
+
+ const buttonsContainer = generateTemplateVarBtns(variables, compUid) as HTMLDivElement;
+ if (!buttonsContainer) return;
+ const focusedElmParent = clickedElm.closest('.form-group');
+ focusedElmParent.appendChild(buttonsContainer);
+ resizeAceEditor(focusedElmParent as HTMLElement);
+ } else {
+ // * Remove template variable buttons only if not clicking on a field that supports variables
+ // This prevents hiding variables when clicking between fields (where focus might show them first)
+
+ // For datalist fields, the click might be on the dropdown arrow or parent element
+ // So we need to check if the form-group contains a datalist input with vars
+ const formGroupForCheck = (clickedElm as HTMLElement).closest('.form-group');
+ const datalistInGroup = formGroupForCheck?.querySelector(
+ 'input[list][data-template-vars]',
+ ) as HTMLInputElement;
+
+ const isVarField =
+ isTemplateVarsEnabled(clickedElm.getAttribute('data-template-vars')) ||
+ clickedElm.getAttribute('data-agent-vars') === 'true' ||
+ clickedElm.getAttribute('data-trigger-vars') === 'true' ||
+ clickedElm.getAttribute('list') || // Direct datalist field
+ !!datalistInGroup || // Datalist field in the same form-group (for clicks on dropdown arrow)
+ (clickedElm as HTMLElement)?.closest?.('[data-template-vars]') ||
+ (clickedElm as HTMLElement)?.closest?.('[data-agent-vars="true"]') ||
+ (clickedElm as HTMLElement)?.closest?.('[data-trigger-vars="true"]');
+
+ if (!isVarField) {
+ const wrapper = document.querySelector(
+ `.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}.tvb-${compUid}`,
+ );
+ const parent = wrapper?.parentElement as HTMLElement;
+ wrapper?.remove();
+ resizeAceEditor(parent);
+ }
+ }
+ } catch (err) {
+ console.log('Template variables display error: ', err);
+ }
+ };
+
+ // Primary event listener for showing/hiding template variables
+ targetElm.onclick = handleTemplateVarsEvent;
+
+ // Add focus event listener with event delegation for datalist inputs
+ // This ensures template variables show on first interaction with datalist fields
+ // where mousedown event (used to create datalist options) might prevent click event
+ targetElm.addEventListener(
+ 'focus',
+ (e) => {
+ const target = e.target as HTMLElement;
+
+ // Only trigger for datalist inputs with template vars (supports both "true" and object format)
+ if (
+ target.getAttribute('list') &&
+ isTemplateVarsEnabled(target.getAttribute('data-template-vars'))
+ ) {
+ // Check if variables are already showing for this field
+ const formGroup = target.closest('.form-group');
+ const existingWrapper = formGroup?.querySelector(`.${TEMPLATE_VAR_BTNS_WRAPPER_CLASS}`);
+
+ if (!existingWrapper) {
+ // Only call handleTemplateVarsEvent if variables are not already showing
+ // This prevents the click event from interfering
+ handleTemplateVarsEvent(e);
+
+ // Mark that we just processed this to prevent click event from double-processing
+ (target as any).__varsJustShown = true;
+ setTimeout(() => {
+ delete (target as any).__varsJustShown;
+ }, 150);
+ }
+ }
+ },
+ true,
+ ); // Use capture phase to catch the event early
+}
diff --git a/packages/app/src/builder-ui/utils/form.utils.ts b/packages/app/src/builder-ui/utils/form.utils.ts
index da584ef2..59b8558c 100644
--- a/packages/app/src/builder-ui/utils/form.utils.ts
+++ b/packages/app/src/builder-ui/utils/form.utils.ts
@@ -1,4 +1,3 @@
-
export const focusField = (elm: HTMLInputElement) => {
if (!elm) return;
@@ -29,3 +28,34 @@ export const dispatchInputEvent = (elm: HTMLInputElement | HTMLTextAreaElement):
});
elm.dispatchEvent(changeEvent);
};
+
+/**
+ * Checks if template variables are enabled based on the data-template-vars attribute value.
+ * Supports both simple boolean string ("true") and JSON object format ({"enabled": true, "singleOnly": true}).
+ *
+ * @example
+ * // String format
+ * isTemplateVarsEnabled("true") // returns true
+ *
+ * // Object format
+ * isTemplateVarsEnabled('{"enabled": true, "singleOnly": true}') // returns true
+ *
+ * // From element
+ * const attr = element.getAttribute('data-template-vars');
+ * isTemplateVarsEnabled(attr) // returns true if enabled
+ *
+ * @param attributeValue - The value of data-template-vars attribute
+ * @returns true if template vars are enabled, false otherwise
+ */
+export function isTemplateVarsEnabled(attributeValue: string | null | undefined): boolean {
+ if (!attributeValue) return false;
+ if (attributeValue === 'true') return true;
+
+ try {
+ const config = JSON.parse(attributeValue);
+ return config.enabled === true;
+ } catch {
+ // Fallback: check for "enabled":true or "enabled": true in string
+ return attributeValue.includes('"enabled":true') || attributeValue.includes('"enabled": true');
+ }
+}