ExpressionEditor.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 class ExpressionEditor : BaseEditor
  13. {
  14. /// <summary>
  15. /// The <see cref="IExpressionModel"/> to use for this expression; if set to null, the variables must be manually set for the editor.
  16. /// </summary>
  17. public Type? ModelType { get; set; }
  18. private IExpressionModelGenerator? _modelGenerator;
  19. public Type? ModelGenerator { get; }
  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. return new ExpressionEditor(ModelType, ModelGenerator)
  38. {
  39. VariableNames = VariableNames
  40. };
  41. }
  42. public List<string> GetVariables(object?[] items)
  43. {
  44. if (VariableNames != null)
  45. return VariableNames;
  46. if (ModelGenerator != null)
  47. {
  48. _modelGenerator ??= (Activator.CreateInstance(ModelGenerator) as IExpressionModelGenerator)!;
  49. return _modelGenerator.GetVariables(items);
  50. }
  51. if(ModelType != null)
  52. return CoreExpression.GetModelVariables(ModelType);
  53. return new List<string>();
  54. }
  55. }
  56. }