variable.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import _ from 'lodash';
  2. import { assignModelProperties } from 'app/core/utils/model_utils';
  3. /*
  4. * This regex matches 3 types of variable reference with an optional format specifier
  5. * \$(\w+) $var1
  6. * \[\[([\s\S]+?)(?::(\w+))?\]\] [[var2]] or [[var2:fmt2]]
  7. * \${(\w+)(?::(\w+))?} ${var3} or ${var3:fmt3}
  8. */
  9. export const variableRegex = /\$(\w+)|\[\[([\s\S]+?)(?::(\w+))?\]\]|\${(\w+)(?::(\w+))?}/g;
  10. // Helper function since lastIndex is not reset
  11. export const variableRegexExec = (variableString: string) => {
  12. variableRegex.lastIndex = 0;
  13. return variableRegex.exec(variableString);
  14. };
  15. export interface Variable {
  16. setValue(option: any): any;
  17. updateOptions(): any;
  18. dependsOn(variable: any): any;
  19. setValueFromUrl(urlValue: any): any;
  20. getValueForUrl(): any;
  21. getSaveModel(): any;
  22. }
  23. export let variableTypes = {};
  24. export { assignModelProperties };
  25. export function containsVariable(...args: any[]) {
  26. const variableName = args[args.length - 1];
  27. args[0] = _.isString(args[0]) ? args[0] : Object['values'](args[0]).join(' ');
  28. const variableString = args.slice(0, -1).join(' ');
  29. const matches = variableString.match(variableRegex);
  30. const isMatchingVariable =
  31. matches !== null
  32. ? matches.find(match => {
  33. const varMatch = variableRegexExec(match);
  34. return varMatch !== null && varMatch.indexOf(variableName) > -1;
  35. })
  36. : false;
  37. return !!isMatchingVariable;
  38. }