vertex_ai_search-1.0.0-beta4/js/exclude_regex.js
js/exclude_regex.js
function setSubmitDisabled(element, disabled) {
const form = element.closest('form');
if (form) {
const submit = form.querySelector('[type="submit"]');
if (submit) {
submit.disabled = disabled;
}
}
}
(function (Drupal, drupalSettings, once) {
Drupal.behaviors.excludeRegexValidation = {
attach(context) {
const config = drupalSettings.vertex_ai_search?.regex;
once('validation', '#edit-keys', context).forEach(function (element) {
const validateAndDispatch = () => {
// Always remove any existing notice first
const next = element.nextElementSibling;
if (next && next.classList.contains('exclude-regex-notice')) {
next.remove();
}
let matched = false;
let message = '';
let severity = null;
let regex = null;
const lines = config.split(/\r?\n/);
const value = element.value;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line.trim()) continue;
const [pattern, msg, sev] = line.split('::');
try {
regex = new RegExp(pattern, 'gi');
if (value.match(regex)) {
matched = true;
message =
msg || 'Unable to perform a search with the words provided.';
severity = sev || 'error';
break; // Only show the first match
}
} catch (e) {
// Invalid regex, skip
console.error('Invalid regex in rule:', pattern, e);
}
}
// Dispatch event for developer override
const event = new CustomEvent('RegexValidationCheck', {
bubbles: true,
detail: {
handled: false,
element,
matched,
severity,
message,
regex,
},
});
element.dispatchEvent(event);
// If not handled, do default behavior
if (!event.defaultPrevented && !event.detail.handled && matched) {
let notice = element.nextElementSibling;
if (
!notice ||
!notice.classList?.contains('exclude-regex-notice')
) {
notice = document.createElement('div');
notice.className = 'exclude-regex-notice';
element.insertAdjacentElement('afterEnd', notice);
}
notice.textContent = message;
let color = 'black';
if (severity === 'warning') {
color = 'orange';
} else if (severity === 'error') {
color = 'red';
}
notice.style.color = color;
setSubmitDisabled(element, severity === 'error');
} else {
// No match or handled by custom code: remove notice and enable submit
const next = element.nextElementSibling;
if (next && next.classList.contains('exclude-regex-notice')) {
next.remove();
}
setSubmitDisabled(element, false);
}
};
element.addEventListener('input', () => {
validateAndDispatch();
});
if (element.value.trim() !== '') {
validateAndDispatch();
}
});
},
};
})(Drupal, drupalSettings, once);
