ExpressionEditor.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace InABox.Core
  7. {
  8. public interface IExpressionModelGenerator
  9. {
  10. public List<string> GetVariables(object?[] items);
  11. }
  12. public delegate IEnumerable<String> GetVariables();
  13. public class ExpressionEditor : BaseEditor
  14. {
  15. /// <summary>
  16. /// The <see cref="IExpressionModel"/> to use for this expression; if set to null, the variables must be manually set for the editor.
  17. /// </summary>
  18. public Type? ModelType { get; set; }
  19. private IExpressionModelGenerator? _modelGenerator;
  20. public Type? ModelGenerator { get; }
  21. public event GetVariables OnGetVariables;
  22. [DoNotSerialize]
  23. [JsonIgnore]
  24. public List<string>? VariableNames { get; set; }
  25. public ExpressionEditor(Type? modelType, Type? modelGenerator = null)
  26. {
  27. ModelType = modelType;
  28. if (modelGenerator != null)
  29. {
  30. if (!typeof(IExpressionModelGenerator).IsAssignableFrom(modelGenerator))
  31. {
  32. throw new Exception($"Model generator must be a {nameof(IExpressionModelGenerator)}");
  33. }
  34. ModelGenerator = modelGenerator;
  35. }
  36. }
  37. protected override BaseEditor DoClone()
  38. {
  39. var result = new ExpressionEditor(ModelType, ModelGenerator)
  40. {
  41. VariableNames = VariableNames
  42. };
  43. result.OnGetVariables = OnGetVariables;
  44. return result;
  45. }
  46. public IEnumerable<String> GetVariables(object?[] items)
  47. {
  48. if (VariableNames != null)
  49. return VariableNames;
  50. if (ModelGenerator != null)
  51. {
  52. _modelGenerator ??= (Activator.CreateInstance(ModelGenerator) as IExpressionModelGenerator)!;
  53. return _modelGenerator.GetVariables(items);
  54. }
  55. if (ModelType != null)
  56. return CoreExpression.GetModelVariables(ModelType);
  57. return OnGetVariables?.Invoke() ?? new String[] { };
  58. }
  59. }
  60. }