variable.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 type CtorType = new (...args: any[]) => {};
  24. export interface VariableTypes {
  25. [key: string]: {
  26. name: string;
  27. ctor: CtorType;
  28. description: string;
  29. supportsMulti?: boolean;
  30. };
  31. }
  32. export let variableTypes: VariableTypes = {};
  33. export { assignModelProperties };
  34. export function containsVariable(...args: any[]) {
  35. const variableName = args[args.length - 1];
  36. args[0] = _.isString(args[0]) ? args[0] : Object['values'](args[0]).join(' ');
  37. const variableString = args.slice(0, -1).join(' ');
  38. const matches = variableString.match(variableRegex);
  39. const isMatchingVariable =
  40. matches !== null
  41. ? matches.find(match => {
  42. const varMatch = variableRegexExec(match);
  43. return varMatch !== null && varMatch.indexOf(variableName) > -1;
  44. })
  45. : false;
  46. return !!isMatchingVariable;
  47. }