ExpressionEditor.cs 2.2 KB

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